Skip to content

Support type definitions created with type() in createEnv#382

Merged
yamcodes merged 8 commits intomainfrom
support-type-definitions-in-createenv
Nov 19, 2025
Merged

Support type definitions created with type() in createEnv#382
yamcodes merged 8 commits intomainfrom
support-type-definitions-in-createenv

Conversation

@yamcodes
Copy link
Owner

@yamcodes yamcodes commented Nov 18, 2025

Summary

This PR adds support for accepting type definitions created with ArkType's type() function in addition to raw schema objects in createEnv() and the vite plugin.

Changes

  • packages/arkenv/src/create-env.ts:

    • Added function overloads to accept both raw schema objects and type definitions
    • Implemented InferType<T> helper to extract types from type definitions
    • Added runtime detection for type definitions (checks for assert method)
    • Maintains full backward compatibility with existing raw schema objects
  • packages/vite-plugin/src/index.ts:

    • Updated to accept type definitions in addition to raw schema objects
    • Enables schema reuse patterns in Vite projects

Benefits

  • Backward compatible: Existing code using raw schema objects continues to work unchanged
  • Type safe: Full TypeScript type inference when using type definitions
  • Flexible: Users can choose between raw schemas (simple cases) or type definitions (reusable schemas)
  • Reusable: Schemas defined with type() can be shared across modules

Example Usage

import arkenv, { type } from "arkenv";

// Define schema once using type()
const envSchema = type({
  PORT: "number.port",
  HOST: "string.host",
  DEBUG: "boolean",
});

// Use the same schema in multiple places
const env1 = arkenv(envSchema, process.env);
const env2 = arkenv(envSchema, customEnv);

// Type inference works correctly
const port: number = env1.PORT; // ✅ Properly typed

Testing

  • ✅ Type inference verified to work correctly
  • ✅ Backward compatibility maintained
  • ✅ Both raw schemas and type definitions work as expected

Closes #381

Summary by CodeRabbit

  • New Features

    • arkenv and the Vite plugin now accept ArkType type definitions in addition to raw schemas.
  • Documentation

    • Added a how-to guide for reusing ArkType schemas across environments and modules.
  • Other

    • Feature banner on the website layout disabled.
    • Doc metadata updated (removed an icon flag).
    • Tests: external link rel checks made more flexible.

✏️ Tip: You can customize this high-level summary in your review settings.

- Add support for accepting type definitions created with ArkType's type() function
- Maintain backward compatibility with raw schema objects
- Implement InferType helper to extract types from type definitions
- Update vite plugin to also accept type definitions
- Full type inference works when using type definitions

Closes #381
@changeset-bot
Copy link

changeset-bot bot commented Nov 18, 2025

⚠️ No Changeset found

Latest commit: 7f7bba2

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 18, 2025

Walkthrough

Adds support for passing ArkType type() definitions (in addition to raw schema objects) to createEnv() and the Vite plugin; updates runtime detection and TypeScript overloads. Also adds documentation on schema reuse, updates docs metadata, and disables a homepage feature banner.

Changes

Cohort / File(s) Summary
Website & docs
apps/www/app/layout.tsx, apps/www/content/docs/meta.json, apps/www/content/docs/how-to/reuse-schemas.mdx, apps/www/content/docs/morphs.mdx
Disables the ArkType feature banner in layout; adds a new how-to doc about reusing schemas; updates docs navigation metadata; removes icon: New front-matter from morphs doc.
Core API — createEnv
packages/arkenv/src/create-env.ts
Adds InferType helper and multiple TypeScript overloads to accept either raw schema objects or type.Any; runtime detection checks for an assert method and uses type definitions directly or converts raw schemas via $.type.raw(); preserves ArkEnvError behavior.
Vite plugin typing
packages/vite-plugin/src/index.ts
Adds type.Any overload and updates implementation signature to accept `EnvSchema
Playground example
apps/playgrounds/node/index.ts
Replaces inline schema object with a type(...)-based envSchema and calls arkenv(envSchema, process.env); runtime usage unchanged.
Tests (playwright)
tooling/playwright-www/tests/docs-navigation.test.ts
Relaxed assertions for external link rel attributes: now checks rel contains noopener and noreferrer rather than matching exact ordering.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant arkenv/createEnv as createEnv
    participant Runtime as RuntimeDetection
    participant TypeDef as "type() definition"
    participant Raw as "raw schema object"
    Note over createEnv,Runtime: New runtime branch detection (checks for `assert`)
    User->>createEnv: call createEnv(def, env?)
    createEnv->>Runtime: inspect def (has assert?)
    alt def has assert (type.Any)
        Runtime->>TypeDef: treat as type definition -> use assert() to validate
        TypeDef-->>createEnv: validated/typed env
    else def is raw schema
        Runtime->>Raw: convert via $.type.raw(def) -> validate
        Raw-->>createEnv: validated/typed env
    end
    createEnv-->>User: return validated environment object
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Areas needing extra attention:
    • packages/arkenv/src/create-env.ts: correctness of TypeScript overloads, InferType helper, and runtime type-detection logic (presence-of-assert check).
    • packages/vite-plugin/src/index.ts: overload ordering and exported typings consistency with createEnv.
    • Example and tests: ensure example apps/playgrounds/node/index.ts and updated Playwright assertions reflect intended behavior.

Possibly related PRs

Suggested labels

example, tests

Poem

🐇
I hopped through schemas, fresh and keen,
Raw or typed — now both are seen.
I stitched the types and wrapped the rest,
Env fields cozy in my nest.
Hop on, dear devs — reuse with glee!

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Most changes are in-scope, but several files contain modifications beyond the core requirement: apps/www/app/layout.tsx disables a banner, apps/www/content/docs files are documentation additions, apps/www/content/docs/meta.json adds menu entries, and tooling/playwright-www test assertions are loosened—none directly related to supporting type() in createEnv. Consider separating documentation updates, banner changes, and test modifications into separate PRs focused on their specific purposes, keeping this PR focused on the core createEnv type() support.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding support for type definitions created with type() in createEnv, which directly matches the primary objective of the PR.
Linked Issues check ✅ Passed All linked issue #381 objectives are met: createEnv() accepts both raw schemas and type() definitions [#381], runtime detection checks for assert method [#381], InferType helper extracts types [#381], backward compatibility preserved [#381], and type inference works correctly [#381].
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch support-type-definitions-in-createenv

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@vercel
Copy link

vercel bot commented Nov 18, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
arkenv Ready Ready Preview Comment Nov 19, 2025 8:55pm

@yamcodes yamcodes changed the title feat: Support type definitions created with type() in createEnv Support type definitions created with type() in createEnv Nov 18, 2025
@github-actions github-actions bot added arkenv Changes to the `arkenv` npm package. @arkenv/vite-plugin Issues or Pull Requests involving the Vite plugin for ArkEnv labels Nov 18, 2025
@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 18, 2025

Open in StackBlitz

npm i https://pkg.pr.new/arkenv@382
npm i https://pkg.pr.new/@arkenv/vite-plugin@382

commit: 7f7bba2

@arkenv-bot
Copy link
Contributor

arkenv-bot bot commented Nov 18, 2025

📦 Bundle Size Report

No results found

All size limits passed!

@github-actions github-actions bot added docs Improvements or additions to documentation www Improvements or additions to arkenv.js.org labels Nov 18, 2025
…tions

- Added a new example for `env2` using a custom environment object with HOST, PORT, and DEBUG properties.
- Included type inference examples for both production and test environments to demonstrate consistent type structure.
- Added overloads to createEnv to support both EnvSchema and type.Any, improving type inference.
- Updated Vite plugin to utilize the new createEnv overloads, ensuring better type precision for environment configurations.
- Commented out the Banner component in layout.tsx for potential future use.
- Updated meta.json to reflect a new link format for reusing schemas.
- Revised morphs.mdx to remove the icon and clarify the description.
- Enhanced how-to/reuse-schemas.mdx documentation with improved titles, descriptions, and examples for better clarity on schema reuse and type definitions.
@yamcodes yamcodes marked this pull request as ready for review November 18, 2025 20:26
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
apps/www/app/layout.tsx (1)

1-1: Consider removing Banner code if the feature is long-term disabled

Commenting out the Banner import and JSX is fine short term, but if this banner is not coming back soon, consider deleting the commented code to reduce noise in the layout.

Also applies to: 51-62

apps/www/content/docs/how-to/reuse-schemas.mdx (2)

13-22: Clean up unused type import in the basic usage snippet

In the “Basic usage” example you import type from "arktype" but never use it; the snippet only shows a raw schema object. Either remove the import or update the example to demonstrate type() usage so it matches the surrounding explanation.


24-29: Add links to concrete runtime examples for reuse scenarios

Since this section calls out Vite, Next.js, and Bun as common multi-runtime setups, it would be helpful to link directly to the existing examples (Node.js, Bun, Vite) so readers can see full working configs alongside this pattern.

Based on learnings

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b39bad6 and b7e7971.

📒 Files selected for processing (6)
  • apps/www/app/layout.tsx (3 hunks)
  • apps/www/content/docs/how-to/reuse-schemas.mdx (1 hunks)
  • apps/www/content/docs/meta.json (1 hunks)
  • apps/www/content/docs/morphs.mdx (0 hunks)
  • packages/arkenv/src/create-env.ts (1 hunks)
  • packages/vite-plugin/src/index.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/www/content/docs/morphs.mdx
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: yamcodes
Repo: yamcodes/arkenv PR: 132
File: packages/arkenv/README.md:13-14
Timestamp: 2025-09-09T17:37:19.650Z
Learning: For yamcodes/arkenv project: Runtime support documentation should link to specific examples: Node.js (examples/basic), Bun (examples/with-bun), Vite (examples/with-vite-react-ts).
🧬 Code graph analysis (3)
apps/www/content/docs/how-to/reuse-schemas.mdx (3)
packages/arkenv/src/type.test.ts (6)
  • envType (29-47)
  • envType (202-217)
  • envType (5-9)
  • it (4-218)
  • envType (86-108)
  • envType (171-190)
packages/arkenv/src/index.test.ts (2)
  • vi (65-81)
  • vi (25-35)
packages/arkenv/src/custom-types.integration.test.ts (1)
  • env (191-197)
packages/vite-plugin/src/index.ts (3)
packages/arkenv/src/type.ts (1)
  • type (3-3)
packages/arkenv/src/create-env.ts (1)
  • EnvSchema (7-7)
packages/arkenv/src/type.test.ts (8)
  • envType (11-15)
  • envType (118-118)
  • envType (127-127)
  • envType (29-47)
  • envType (202-217)
  • envType (86-108)
  • envType (5-9)
  • envType (171-190)
packages/arkenv/src/create-env.ts (4)
packages/arkenv/src/type.ts (1)
  • type (3-3)
packages/arkenv/src/scope.ts (1)
  • $ (9-19)
packages/arkenv/src/type.test.ts (8)
  • envType (29-47)
  • envType (86-108)
  • envType (202-217)
  • envType (127-127)
  • envType (11-15)
  • envType (118-118)
  • envType (5-9)
  • envType (171-190)
packages/arkenv/src/custom-types.integration.test.ts (1)
  • env (191-197)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: test-e2e (e2e)
  • GitHub Check: test-e2e (a11y)
🔇 Additional comments (5)
apps/www/content/docs/meta.json (1)

13-14: New How-to nav entry looks consistent

The added “[New]Reuse your schema” entry (and its placement under the How-to section) matches the new doc slug and keeps the structure valid.

apps/www/content/docs/how-to/reuse-schemas.mdx (1)

141-164: Mixing raw schemas and type definitions is clearly illustrated

The “Mixing approaches” section does a good job showing one-off raw schemas alongside reusable type() definitions, matching the new API capabilities and making the trade-offs clear.

packages/vite-plugin/src/index.ts (1)

3-3: Overloads cleanly extend the plugin to accept type() definitions

The added arkenv(options: type.Any): Plugin overload and the combined implementation signature (EnvSchema<T> | type.Any) line up with createEnv’s new capabilities, and the type-only ArkType import keeps runtime unaffected. The comments about runtime behavior vs. overload precision are also helpful.

Please double-check against the current ArkType typings that type.Any is the right surface here and that import type { type } from "arktype" correctly exposes the Any type member in your TS version.

Also applies to: 11-17, 21-23

packages/arkenv/src/create-env.ts (2)

9-21: InferType<T> correctly bridges ArkType definitions to value types

The InferType<T> conditional nicely handles both callable ArkType types (via the function signature) and type.Any<…> directly, giving you the validated value type while excluding type.errors. This is a good fit for mapping type() definitions to the resulting env object shape.

Given this relies on ArkType’s type.Any and callable type shape, please confirm against the current ArkType .d.ts that type.Any still matches these assumptions (call signature + <Value, Scope> generics).


35-50: Overloads and runtime detection look sound; union typing may be worth re-checking

The overloads distinguish nicely between raw schemas (EnvSchema<T>) and type() definitions (type.Any), and the runtime check (typeof def === "function" && "assert" in def) should safely pick out top-level ArkType definitions without affecting existing object schemas (including those with nested type(...) values). The union overload using EnvSchema<T> | type.Any plus InferType<typeof def> should behave well for callers that accept both forms, especially in your Vite plugin use case.

It would be good to re-run your TS type tests or a local tsc check focusing on mixed-schema call sites (where def is typed as EnvSchema<T> | type.Any) to ensure the union overload returns the expected inferred env type in practice.

Also applies to: 51-56

…chema reuse

- Changed the environment variable setup in index.ts to utilize a schema defined with type() for better type safety.
- Updated how-to/reuse-schemas.mdx to clarify the benefits of sharing schemas across different environments and provided links to relevant examples.
- Updated tests in docs-navigation.test.ts to verify 'rel' attributes for GitHub and ArkType links using `getAttribute` and `toContain` for better clarity and accuracy.
- Removed redundant attribute checks for 'rel' and streamlined the assertions for improved readability.
@github-actions github-actions bot added the tests This issue or PR is about adding, removing or changing tests label Nov 19, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
tooling/playwright-www/tests/docs-navigation.test.ts (1)

149-163: Order-independent rel checks look good; consider a tiny DRY/helper improvement

Switching to substring checks for "noopener" / "noreferrer" makes the test robust to attribute order and matches the intent better than exact-string assertions. The GitHub and ArkType blocks now share the same pattern; if you want to tighten things up later, you could factor this into a small helper (e.g., assertSecureExternalLink(link)), or reuse the same approach in other external-link tests for consistency. Not blocking.

apps/playgrounds/node/index.ts (1)

3-12: New envSchema pattern correctly demonstrates type()-based arkenv usage

Defining envSchema with type({...}) (including the ALLOWED_ORIGINS default) and then calling arkenv(envSchema, process.env) is a clear example of the new “reusable schema” flow and should exercise the updated overloads as intended. If you later want this playground to double as a reuse example for docs, you might also export envSchema so it can be imported elsewhere, but the current setup is perfectly fine as-is.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7e7971 and 7f7bba2.

📒 Files selected for processing (3)
  • apps/playgrounds/node/index.ts (1 hunks)
  • apps/www/content/docs/how-to/reuse-schemas.mdx (1 hunks)
  • tooling/playwright-www/tests/docs-navigation.test.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/www/content/docs/how-to/reuse-schemas.mdx
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: yamcodes
Repo: yamcodes/arkenv PR: 132
File: packages/arkenv/README.md:13-14
Timestamp: 2025-09-09T17:37:19.650Z
Learning: For yamcodes/arkenv project: Runtime support documentation should link to specific examples: Node.js (examples/basic), Bun (examples/with-bun), Vite (examples/with-vite-react-ts).
🧬 Code graph analysis (2)
tooling/playwright-www/tests/docs-navigation.test.ts (5)
apps/www/components/page/star-us-button.test.tsx (4)
  • link (20-24)
  • link (48-51)
  • render (16-25)
  • render (42-52)
tooling/playwright-www/tests/morphs.test.ts (1)
  • page (106-126)
apps/www/components/page/edit-on-github.test.tsx (1)
  • mockGetLinkTitleAndHref (60-73)
tooling/playwright-www/tests/integrations.test.ts (1)
  • pages (128-149)
tooling/playwright-www/tests/homepage.test.ts (1)
  • page (55-92)
apps/playgrounds/node/index.ts (4)
packages/arkenv/src/type.ts (1)
  • type (3-3)
packages/vite-plugin/src/index.ts (2)
  • arkenv (15-36)
  • arkenv (10-29)
packages/arkenv/src/index.test.ts (2)
  • arkenv (50-53)
  • vi (65-81)
packages/arkenv/src/create-env.ts (1)
  • createEnv (21-34)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: test-e2e (a11y)
  • GitHub Check: test-e2e (e2e)

@yamcodes yamcodes merged commit e70e038 into main Nov 19, 2025
19 checks passed
@yamcodes yamcodes deleted the support-type-definitions-in-createenv branch November 19, 2025 21:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

@arkenv/vite-plugin Issues or Pull Requests involving the Vite plugin for ArkEnv arkenv Changes to the `arkenv` npm package. docs Improvements or additions to documentation tests This issue or PR is about adding, removing or changing tests www Improvements or additions to arkenv.js.org

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support type definitions created with type() in addition to raw schema objects

1 participant