arkenv 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,2 @@
1
- import{scope as e,type as t}from"arktype";const n=t(`unknown`).pipe(e=>{if(typeof e==`number`||typeof e!=`string`)return e;let t=e.trim();if(t===``)return e;if(t===`NaN`)return NaN;let n=Number(t);return Number.isNaN(n)?e:n}),r=t(`unknown`).pipe(e=>e===`true`?!0:e===`false`?!1:e),i=t(`0 <= number.integer <= 65535`),a=t(`string.ip | 'localhost'`),o=t(`unknown`).pipe(e=>{if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}),s=e({string:t.module({...t.keywords.string,host:a}),number:t.module({...t.keywords.number,port:i})}),c=(e,t=[])=>{let n=[];if(typeof e==`boolean`)return n;if(`const`in e&&(typeof e.const==`number`||typeof e.const==`boolean`)&&n.push({path:[...t],type:`primitive`}),`enum`in e&&e.enum&&e.enum.some(e=>typeof e==`number`||typeof e==`boolean`)&&n.push({path:[...t],type:`primitive`}),`type`in e)if(e.type===`number`||e.type===`integer`)n.push({path:[...t],type:`primitive`});else if(e.type===`boolean`)n.push({path:[...t],type:`primitive`});else if(e.type===`object`){if(`properties`in e&&e.properties&&Object.keys(e.properties).length>0&&n.push({path:[...t],type:`object`}),`properties`in e&&e.properties)for(let[r,i]of Object.entries(e.properties))n.push(...c(i,[...t,r]))}else e.type===`array`&&(n.push({path:[...t],type:`array`}),`items`in e&&e.items&&(Array.isArray(e.items)?e.items.forEach((e,r)=>{n.push(...c(e,[...t,`${r}`]))}):n.push(...c(e.items,[...t,`*`]))));if(`anyOf`in e&&e.anyOf)for(let r of e.anyOf)n.push(...c(r,t));if(`allOf`in e&&e.allOf)for(let r of e.allOf)n.push(...c(r,t));if(`oneOf`in e&&e.oneOf)for(let r of e.oneOf)n.push(...c(r,t));let r=new Set;return n.filter(e=>{let t=JSON.stringify(e.path)+e.type;return r.has(t)?!1:(r.add(t),!0)})},l=(e,t,i={})=>{let{arrayFormat:a=`comma`}=i,s=e=>{if(a===`json`)try{return JSON.parse(e)}catch{return e}return e.trim()?e.split(`,`).map(e=>e.trim()):[]};if(typeof e!=`object`||!e){if(t.some(e=>e.path.length===0)){let i=t.find(e=>e.path.length===0);if(i?.type===`object`&&typeof e==`string`)return o(e);if(i?.type===`array`&&typeof e==`string`)return s(e);let a=n(e);return typeof a==`number`?a:r(e)}return e}let c=[...t].sort((e,t)=>e.path.length-t.path.length),l=(e,t,i)=>{if(!e||typeof e!=`object`||t.length===0)return;if(t.length===1){let a=t[0];if(a===`*`){if(Array.isArray(e))for(let t=0;t<e.length;t++){let a=e[t];if(i===`primitive`){let i=n(a);typeof i==`number`?e[t]=i:e[t]=r(a)}else i===`object`&&(e[t]=o(a))}return}let c=e;if(Object.prototype.hasOwnProperty.call(c,a)){let e=c[a];if(i===`array`&&typeof e==`string`){c[a]=s(e);return}if(i===`object`&&typeof e==`string`){c[a]=o(e);return}if(Array.isArray(e)){if(i===`primitive`)for(let t=0;t<e.length;t++){let i=e[t],a=n(i);typeof a==`number`?e[t]=a:e[t]=r(i)}}else if(i===`primitive`){let t=n(e);typeof t==`number`?c[a]=t:c[a]=r(e)}}return}let[a,...c]=t;if(a===`*`){if(Array.isArray(e))for(let t of e)l(t,c,i);return}l(e[a],c,i)};for(let t of c)l(e,t.path,t.type);return e};function u(e,n){let r=c(e.in.toJsonSchema({fallback:e=>e.base}));return r.length===0?e:t(`unknown`).pipe(e=>l(e,r,n)).pipe(e)}const d=(e,t=2,{dontDetectNewlines:n=!1}={})=>n?`${` `.repeat(t)}${e}`:e.split(`
2
- `).map(e=>`${` `.repeat(t)}${e}`).join(`
3
- `),f={red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,reset:`\x1B[0m`},p=()=>typeof process<`u`&&process.versions!=null&&process.versions.node!=null,m=()=>!!(!p()||process.env.NO_COLOR!==void 0||process.env.CI!==void 0||process.stdout&&!process.stdout.isTTY),h=(e,t)=>p()&&!m()?`${f[e]}${t}${f.reset}`:t,g=e=>Object.entries(e.byPath).map(([e,t])=>{let n=t.message.startsWith(e)?t.message.slice(e.length):t.message,r=n.match(/\(was "([^"]+)"\)/),i=r?n.replace(`(was "${r[1]}")`,`(was ${h(`cyan`,`"${r[1]}"`)})`):n;return`${h(`yellow`,e)} ${i.trimStart()}`}).join(`
4
- `);var _=class extends Error{constructor(e,t=`Errors found while validating environment variables`){super(`${h(`red`,t)}\n${d(g(e))}\n`),this.name=`ArkEnvError`}};Object.defineProperty(_,`name`,{value:`ArkEnvError`});const v=s.type;function y(e,{env:t=process.env,coerce:n=!0,onUndeclaredKey:r=`delete`,arrayFormat:i=`comma`}={}){let a=typeof e==`function`&&`assert`in e?e:s.type.raw(e);a=a.onUndeclaredKey(r),n&&(a=u(a,{arrayFormat:i}));let o=a(t);if(o instanceof v.errors)throw new _(o);return o}var b=y;export{_ as ArkEnvError,y as createEnv,b as default,v as type};
1
+ import{t as e}from"./errors-D_Q1KGgZ.js";import{createRequire as t}from"node:module";function n(t,n){let{env:r=process.env,onUndeclaredKey:i=`delete`}=n,a={},o=[],s=new Set(Object.keys(r));for(let e in t){let n=t[e],i=r[e];if(!n||typeof n!=`object`||!(`~standard`in n))throw Error(`Invalid schema for key "${e}": expected a Standard Schema 1.0 validator (e.g. Zod, Valibot) in "standard" mode.`);let c=n[`~standard`].validate(i);if(c instanceof Promise)throw Error(`Async validation is not supported for key "${e}". ArkEnv is synchronous.`);if(c.issues)for(let t of c.issues)o.push({path:e,message:t.message});else a[e]=c.value;s.delete(e)}if(i!==`delete`)for(let e of s)i===`reject`?o.push({path:e,message:`Undeclared key`}):i===`ignore`&&(a[e]=r[e]);if(o.length>0)throw new e(o);return a}function r(){let e=t(import.meta.url),n=[`./arktype.cjs`,`../arktype.cjs`,`./arktype/index.cjs`,`../arktype/index.cjs`,`./arktype`,`../arktype`,`./arktype/index.ts`,`../arktype/index.ts`],r;for(let t of n)try{return e(t)}catch(e){if(r=e,e.code===`MODULE_NOT_FOUND`){let n=e.message||``;if((n.includes(`'arktype'`)||n.includes(`"arktype"`)||n.includes(`Cannot find module 'arktype'`))&&!n.includes(t))break}}let i=r?.message||``;throw r?.code===`MODULE_NOT_FOUND`&&(i.includes(`'arktype'`)||i.includes(`"arktype"`)||i.includes(`Cannot find module 'arktype'`))&&!i.includes(`./arktype`)&&!i.includes(`../arktype`)?Error(`The 'arktype' package is required when using the default validator mode. Please install it (npm install arktype) or set 'validator: "standard"' in your config if you only intend to use Standard Schema validators (like Zod or Valibot).`):r}function i(t,i={}){if((i.validator??`arktype`)===`standard`){if(!t||typeof t!=`object`||Array.isArray(t))throw new e([{path:``,message:`Invalid schema: expected an object mapping in "standard" mode.`}]);for(let n in t){let r=t[n];if(typeof r==`string`)throw new e([{path:n,message:`ArkType DSL strings are not supported in "standard" mode. Use a Standard Schema validator (e.g., Zod, Valibot) or set validator: "arktype".`}]);if(!r||typeof r!=`object`||!(`~standard`in r))throw new e([{path:n,message:`Invalid validator: expected a Standard Schema 1.0 validator (must have "~standard" property). ArkType validators are not supported in "standard" mode. Use validator: "arktype" for ArkType schemas.`}])}return n(t,i)}let{parse:a}=r();return a(t,i)}var a=i;export{e as ArkEnvError,i as createEnv,a as default};
5
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["e","t","n","i","n","r","e","t","results: CoercionTarget[]","t","maybeJson","maybeNumber","maybeBoolean","a","i","type","$","$"],"sources":["../../internal/keywords/dist/index.js","../../internal/scope/dist/index.js","../src/utils/coerce.ts","../src/utils/indent.ts","../src/utils/style-text.ts","../src/errors.ts","../src/type.ts","../src/create-env.ts","../src/index.ts"],"sourcesContent":["import{type as e}from\"arktype\";const t=e(`unknown`).pipe(e=>{if(typeof e==`number`||typeof e!=`string`)return e;let t=e.trim();if(t===``)return e;if(t===`NaN`)return NaN;let n=Number(t);return Number.isNaN(n)?e:n}),n=e(`unknown`).pipe(e=>e===`true`?!0:e===`false`?!1:e),r=e(`0 <= number.integer <= 65535`),i=e(`string.ip | 'localhost'`),a=e(`unknown`).pipe(e=>{if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}});export{i as host,n as maybeBoolean,a as maybeJson,t as maybeNumber,r as port};\n//# sourceMappingURL=index.js.map","import{host as e,port as t}from\"@repo/keywords\";import{scope as n,type as r}from\"arktype\";const i=n({string:r.module({...r.keywords.string,host:e}),number:r.module({...r.keywords.number,port:t})});export{i as $};\n//# sourceMappingURL=index.js.map","import { maybeBoolean, maybeJson, maybeNumber } from \"@repo/keywords\";\nimport { type BaseType, type JsonSchema, type } from \"arktype\";\n\n/**\n * A marker used in the coercion path to indicate that the target\n * is the *elements* of an array, rather than the array property itself.\n */\nconst ARRAY_ITEM_MARKER = \"*\";\n\n/**\n * @internal\n * Information about a path in the schema that requires coercion.\n */\ntype CoercionTarget = {\n\tpath: string[];\n\ttype: \"primitive\" | \"array\" | \"object\";\n};\n\n/**\n * Options for coercion behavior.\n */\nexport type CoerceOptions = {\n\t/**\n\t * format to use for array parsing\n\t * @default \"comma\"\n\t */\n\tarrayFormat?: \"comma\" | \"json\";\n};\n\n/**\n * Recursively find all paths in a JSON Schema that require coercion.\n * We prioritize \"number\", \"integer\", \"boolean\", \"array\", and \"object\" types.\n */\nconst findCoercionPaths = (\n\tnode: JsonSchema,\n\tpath: string[] = [],\n): CoercionTarget[] => {\n\tconst results: CoercionTarget[] = [];\n\n\tif (typeof node === \"boolean\") {\n\t\treturn results;\n\t}\n\n\tif (\"const\" in node) {\n\t\tif (typeof node.const === \"number\" || typeof node.const === \"boolean\") {\n\t\t\tresults.push({ path: [...path], type: \"primitive\" });\n\t\t}\n\t}\n\n\tif (\"enum\" in node && node.enum) {\n\t\tif (\n\t\t\tnode.enum.some((v) => typeof v === \"number\" || typeof v === \"boolean\")\n\t\t) {\n\t\t\tresults.push({ path: [...path], type: \"primitive\" });\n\t\t}\n\t}\n\n\tif (\"type\" in node) {\n\t\tif (node.type === \"number\" || node.type === \"integer\") {\n\t\t\tresults.push({ path: [...path], type: \"primitive\" });\n\t\t} else if (node.type === \"boolean\") {\n\t\t\tresults.push({ path: [...path], type: \"primitive\" });\n\t\t} else if (node.type === \"object\") {\n\t\t\t// Check if this object has properties defined\n\t\t\t// If it does, we want to coerce the whole object from a JSON string\n\t\t\t// But we also want to recursively check nested properties\n\t\t\tconst hasProperties =\n\t\t\t\t\"properties\" in node &&\n\t\t\t\tnode.properties &&\n\t\t\t\tObject.keys(node.properties).length > 0;\n\n\t\t\tif (hasProperties) {\n\t\t\t\t// Mark this path as needing object coercion (JSON parsing)\n\t\t\t\tresults.push({ path: [...path], type: \"object\" });\n\t\t\t}\n\n\t\t\t// Also recursively check nested properties for their own coercions\n\t\t\tif (\"properties\" in node && node.properties) {\n\t\t\t\tfor (const [key, prop] of Object.entries(node.properties)) {\n\t\t\t\t\tresults.push(\n\t\t\t\t\t\t...findCoercionPaths(prop as JsonSchema, [...path, key]),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (node.type === \"array\") {\n\t\t\t// Mark the array itself as a target for splitting strings\n\t\t\tresults.push({ path: [...path], type: \"array\" });\n\n\t\t\tif (\"items\" in node && node.items) {\n\t\t\t\tif (Array.isArray(node.items)) {\n\t\t\t\t\t// Tuple traversal\n\t\t\t\t\tnode.items.forEach((item, index) => {\n\t\t\t\t\t\tresults.push(\n\t\t\t\t\t\t\t...findCoercionPaths(item as JsonSchema, [...path, `${index}`]),\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// List traversal\n\t\t\t\t\tresults.push(\n\t\t\t\t\t\t...findCoercionPaths(node.items as JsonSchema, [\n\t\t\t\t\t\t\t...path,\n\t\t\t\t\t\t\tARRAY_ITEM_MARKER,\n\t\t\t\t\t\t]),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (\"anyOf\" in node && node.anyOf) {\n\t\tfor (const branch of node.anyOf) {\n\t\t\tresults.push(...findCoercionPaths(branch as JsonSchema, path));\n\t\t}\n\t}\n\n\tif (\"allOf\" in node && node.allOf) {\n\t\tfor (const branch of node.allOf) {\n\t\t\tresults.push(...findCoercionPaths(branch as JsonSchema, path));\n\t\t}\n\t}\n\n\tif (\"oneOf\" in node && node.oneOf) {\n\t\tfor (const branch of node.oneOf) {\n\t\t\tresults.push(...findCoercionPaths(branch as JsonSchema, path));\n\t\t}\n\t}\n\n\t// Deduplicate by path and type combination\n\tconst seen = new Set<string>();\n\treturn results.filter((t) => {\n\t\tconst key = JSON.stringify(t.path) + t.type;\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n};\n\n/**\n * Apply coercion to a data object based on identified paths.\n */\nconst applyCoercion = (\n\tdata: unknown,\n\ttargets: CoercionTarget[],\n\toptions: CoerceOptions = {},\n) => {\n\tconst { arrayFormat = \"comma\" } = options;\n\n\t// Helper to split string to array\n\tconst splitString = (val: string) => {\n\t\tif (arrayFormat === \"json\") {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(val);\n\t\t\t} catch {\n\t\t\t\treturn val;\n\t\t\t}\n\t\t}\n\n\t\tif (!val.trim()) return [];\n\t\treturn val.split(\",\").map((s) => s.trim());\n\t};\n\n\tif (typeof data !== \"object\" || data === null) {\n\t\t// If root data needs coercion\n\t\tif (targets.some((t) => t.path.length === 0)) {\n\t\t\tconst rootTarget = targets.find((t) => t.path.length === 0);\n\n\t\t\tif (rootTarget?.type === \"object\" && typeof data === \"string\") {\n\t\t\t\treturn maybeJson(data);\n\t\t\t}\n\n\t\t\tif (rootTarget?.type === \"array\" && typeof data === \"string\") {\n\t\t\t\treturn splitString(data);\n\t\t\t}\n\n\t\t\tconst asNumber = maybeNumber(data);\n\t\t\tif (typeof asNumber === \"number\") {\n\t\t\t\treturn asNumber;\n\t\t\t}\n\t\t\treturn maybeBoolean(data);\n\t\t}\n\t\treturn data;\n\t}\n\n\t// Sort targets by path length to ensure parent objects/arrays are coerced before their children\n\tconst sortedTargets = [...targets].sort(\n\t\t(a, b) => a.path.length - b.path.length,\n\t);\n\n\tconst walk = (\n\t\tcurrent: unknown,\n\t\ttargetPath: string[],\n\t\ttype: \"primitive\" | \"array\" | \"object\",\n\t) => {\n\t\tif (!current || typeof current !== \"object\") return;\n\n\t\tif (targetPath.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If we've reached the last key, apply coercion\n\t\tif (targetPath.length === 1) {\n\t\t\tconst lastKey = targetPath[0];\n\n\t\t\tif (lastKey === ARRAY_ITEM_MARKER) {\n\t\t\t\tif (Array.isArray(current)) {\n\t\t\t\t\tfor (let i = 0; i < current.length; i++) {\n\t\t\t\t\t\tconst original = current[i];\n\t\t\t\t\t\tif (type === \"primitive\") {\n\t\t\t\t\t\t\tconst asNumber = maybeNumber(original);\n\t\t\t\t\t\t\tif (typeof asNumber === \"number\") {\n\t\t\t\t\t\t\t\tcurrent[i] = asNumber;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcurrent[i] = maybeBoolean(original);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (type === \"object\") {\n\t\t\t\t\t\t\tcurrent[i] = maybeJson(original);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst record = current as Record<string, unknown>;\n\t\t\t// biome-ignore lint/suspicious/noPrototypeBuiltins: ES2020 compatibility\n\t\t\tif (Object.prototype.hasOwnProperty.call(record, lastKey)) {\n\t\t\t\tconst original = record[lastKey];\n\n\t\t\t\tif (type === \"array\" && typeof original === \"string\") {\n\t\t\t\t\trecord[lastKey] = splitString(original);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (type === \"object\" && typeof original === \"string\") {\n\t\t\t\t\trecord[lastKey] = maybeJson(original);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (Array.isArray(original)) {\n\t\t\t\t\tif (type === \"primitive\") {\n\t\t\t\t\t\tfor (let i = 0; i < original.length; i++) {\n\t\t\t\t\t\t\tconst item = original[i];\n\t\t\t\t\t\t\tconst asNumber = maybeNumber(item);\n\t\t\t\t\t\t\tif (typeof asNumber === \"number\") {\n\t\t\t\t\t\t\t\toriginal[i] = asNumber;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\toriginal[i] = maybeBoolean(item);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (type === \"primitive\") {\n\t\t\t\t\t\tconst asNumber = maybeNumber(original);\n\t\t\t\t\t\t// If numeric parsing didn't produce a number, try boolean coercion\n\t\t\t\t\t\tif (typeof asNumber === \"number\") {\n\t\t\t\t\t\t\trecord[lastKey] = asNumber;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trecord[lastKey] = maybeBoolean(original);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Recurse down\n\t\tconst [nextKey, ...rest] = targetPath;\n\n\t\tif (nextKey === ARRAY_ITEM_MARKER) {\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tfor (const item of current) {\n\t\t\t\t\twalk(item, rest, type);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst record = current as Record<string, unknown>;\n\t\twalk(record[nextKey], rest, type);\n\t};\n\n\tfor (const target of sortedTargets) {\n\t\twalk(data, target.path, target.type);\n\t}\n\n\treturn data;\n};\n\n/**\n * Create a coercing wrapper around an ArkType schema using JSON Schema introspection.\n * Pre-process input data to coerce string values to numbers/booleans at identified paths\n * before validation.\n */\nexport function coerce<t, $ = {}>(\n\tschema: BaseType<t, $>,\n\toptions?: CoerceOptions,\n): BaseType<t, $> {\n\t// Use a fallback to handle unjsonifiable parts of the schema (like predicates)\n\t// by preserving the base schema. This ensures that even if part of the schema\n\t// cannot be fully represented in JSON Schema, we can still perform coercion\n\t// for the parts that can.\n\tconst json = schema.in.toJsonSchema({\n\t\tfallback: (ctx) => ctx.base,\n\t});\n\tconst targets = findCoercionPaths(json);\n\n\tif (targets.length === 0) {\n\t\treturn schema;\n\t}\n\n\t/*\n\t * We use `type(\"unknown\")` to start the pipeline, which initializes a default scope.\n\t * Integrating the original `schema` with its custom scope `$` into this pipeline\n\t * creates a scope mismatch in TypeScript ({} vs $).\n\t * We cast to `BaseType<t, $>` to assert the final contract is maintained.\n\t */\n\treturn type(\"unknown\")\n\t\t.pipe((data) => applyCoercion(data, targets, options))\n\t\t.pipe(schema) as BaseType<t, $>;\n}\n","/**\n * Options for the `indent` function\n */\ntype IndentOptions = {\n\t/**\n\t * Whether to detect newlines and indent each line individually, defaults to false (indenting the whole string)\n\t */\n\tdontDetectNewlines?: boolean;\n};\n\n/**\n * Indent a string by a given amount\n * @param str - The string to indent\n * @param amt - The amount to indent by, defaults to 2\n * @param options - {@link IndentOptions}\n * @returns The indented string\n */\nexport const indent = (\n\tstr: string,\n\tamt = 2,\n\t{ dontDetectNewlines = false }: IndentOptions = {},\n) => {\n\tconst detectNewlines = !dontDetectNewlines;\n\tif (detectNewlines) {\n\t\treturn str\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => `${\" \".repeat(amt)}${line}`)\n\t\t\t.join(\"\\n\");\n\t}\n\n\treturn `${\" \".repeat(amt)}${str}`;\n};\n","/**\n * Cross-platform text styling utility\n * Uses ANSI colors in Node environments, plain text in browsers\n * Respects NO_COLOR, CI environment variables, and TTY detection\n */\n\n// ANSI color codes for Node environments\nconst colors = {\n\tred: \"\\x1b[31m\",\n\tyellow: \"\\x1b[33m\",\n\tcyan: \"\\x1b[36m\",\n\treset: \"\\x1b[0m\",\n} as const;\n\n/**\n * Check if we're in a Node environment (not browser)\n * Checked dynamically to allow for testing with mocked globals\n */\nconst isNode = (): boolean =>\n\ttypeof process !== \"undefined\" &&\n\tprocess.versions != null &&\n\tprocess.versions.node != null;\n\n/**\n * Check if colors should be disabled based on environment\n * Respects NO_COLOR, CI environment variables, and TTY detection\n */\nconst shouldDisableColors = (): boolean => {\n\tif (!isNode()) return true;\n\n\t// Respect NO_COLOR environment variable (https://no-color.org/)\n\tif (process.env.NO_COLOR !== undefined) return true;\n\n\t// Disable colors in CI environments by default\n\tif (process.env.CI !== undefined) return true;\n\n\t// Disable colors if not writing to a TTY\n\tif (process.stdout && !process.stdout.isTTY) return true;\n\n\treturn false;\n};\n\n/**\n * Style text with color. Uses ANSI codes in Node, plain text in browsers.\n * @param color - The color to apply\n * @param text - The text to style\n * @returns Styled text in Node (if colors enabled), plain text otherwise\n */\nexport const styleText = (\n\tcolor: \"red\" | \"yellow\" | \"cyan\",\n\ttext: string,\n): string => {\n\t// Use ANSI colors only in Node environments with colors enabled\n\tif (isNode() && !shouldDisableColors()) {\n\t\treturn `${colors[color]}${text}${colors.reset}`;\n\t}\n\t// Fall back to plain text in browsers or when colors are disabled\n\treturn text;\n};\n","import type { ArkErrors } from \"arktype\";\nimport { indent, styleText } from \"./utils\";\n\n/**\n * Format the errors returned by ArkType to be more readable\n * @param errors - The errors returned by ArkType\n * @returns A string of the formatted errors\n */\nexport const formatErrors = (errors: ArkErrors): string =>\n\tObject.entries(errors.byPath)\n\t\t.map(([path, error]) => {\n\t\t\tconst messageWithoutPath = error.message.startsWith(path)\n\t\t\t\t? error.message.slice(path.length)\n\t\t\t\t: error.message;\n\n\t\t\t// Extract the value in parentheses if it exists\n\t\t\tconst valueMatch = messageWithoutPath.match(/\\(was \"([^\"]+)\"\\)/);\n\t\t\tconst formattedMessage = valueMatch\n\t\t\t\t? messageWithoutPath.replace(\n\t\t\t\t\t\t`(was \"${valueMatch[1]}\")`,\n\t\t\t\t\t\t`(was ${styleText(\"cyan\", `\"${valueMatch[1]}\"`)})`,\n\t\t\t\t\t)\n\t\t\t\t: messageWithoutPath;\n\n\t\t\treturn `${styleText(\"yellow\", path)} ${formattedMessage.trimStart()}`;\n\t\t})\n\t\t.join(\"\\n\");\n\nexport class ArkEnvError extends Error {\n\tconstructor(\n\t\terrors: ArkErrors,\n\t\tmessage = \"Errors found while validating environment variables\",\n\t) {\n\t\tsuper(`${styleText(\"red\", message)}\\n${indent(formatErrors(errors))}\\n`);\n\t\tthis.name = \"ArkEnvError\";\n\t}\n}\n\nObject.defineProperty(ArkEnvError, \"name\", { value: \"ArkEnvError\" });\n","import { $ } from \"@repo/scope\";\n\nexport const type = $.type;\n","import { $ } from \"@repo/scope\";\nimport type { EnvSchemaWithType, InferType, SchemaShape } from \"@repo/types\";\nimport type { type as at, distill } from \"arktype\";\nimport { ArkEnvError } from \"./errors\";\nimport { type } from \"./type\";\nimport { type CoerceOptions, coerce } from \"./utils\";\n\nexport type EnvSchema<def> = at.validate<def, $>;\ntype RuntimeEnvironment = Record<string, string | undefined>;\n\n/**\n * Configuration options for `createEnv`\n */\nexport type ArkEnvConfig = {\n\t/**\n\t * The environment variables to validate. Defaults to `process.env`\n\t */\n\tenv?: RuntimeEnvironment;\n\t/**\n\t * Whether to coerce environment variables to their defined types. Defaults to `true`\n\t */\n\tcoerce?: boolean;\n\t/**\n\t * Control how ArkEnv handles environment variables that are not defined in your schema.\n\t *\n\t * Defaults to `'delete'` to ensure your output object only contains\n\t * keys you've explicitly declared. This differs from ArkType's standard behavior, which\n\t * mirrors TypeScript by defaulting to `'ignore'`.\n\t *\n\t * - `delete` (ArkEnv default): Undeclared keys are allowed on input but stripped from the output.\n\t * - `ignore` (ArkType default): Undeclared keys are allowed and preserved in the output.\n\t * - `reject`: Undeclared keys will cause validation to fail.\n\t *\n\t * @default \"delete\"\n\t * @see https://arktype.io/docs/configuration#onundeclaredkey\n\t */\n\tonUndeclaredKey?: \"ignore\" | \"delete\" | \"reject\";\n\n\t/**\n\t * The format to use for array parsing when coercion is enabled.\n\t *\n\t * - `comma` (default): Strings are split by comma and trimmed.\n\t * - `json`: Strings are parsed as JSON.\n\t *\n\t * @default \"comma\"\n\t */\n\tarrayFormat?: CoerceOptions[\"arrayFormat\"];\n};\n\n/**\n * TODO: `SchemaShape` is basically `Record<string, unknown>`.\n * If possible, find a better type than \"const T extends Record<string, unknown>\",\n * and be as close as possible to the type accepted by ArkType's `type`.\n */\n\n/**\n * Create an environment variables object from a schema and an environment\n * @param def - The environment variable schema (raw object or type definition created with `type()`)\n * @param config - Configuration options, see {@link ArkEnvConfig}\n * @returns The validated environment variable schema\n * @throws An {@link ArkEnvError | error} if the environment variables are invalid.\n */\nexport function createEnv<const T extends SchemaShape>(\n\tdef: EnvSchema<T>,\n\tconfig?: ArkEnvConfig,\n): distill.Out<at.infer<T, $>>;\nexport function createEnv<T extends EnvSchemaWithType>(\n\tdef: T,\n\tconfig?: ArkEnvConfig,\n): InferType<T>;\nexport function createEnv<const T extends SchemaShape>(\n\tdef: EnvSchema<T> | EnvSchemaWithType,\n\tconfig?: ArkEnvConfig,\n): distill.Out<at.infer<T, $>> | InferType<typeof def>;\nexport function createEnv<const T extends SchemaShape>(\n\tdef: EnvSchema<T> | EnvSchemaWithType,\n\t{\n\t\tenv = process.env,\n\t\tcoerce: shouldCoerce = true,\n\t\tonUndeclaredKey = \"delete\",\n\t\tarrayFormat = \"comma\",\n\t}: ArkEnvConfig = {},\n): distill.Out<at.infer<T, $>> | InferType<typeof def> {\n\t// If def is a type definition (has assert method), use it directly\n\t// Otherwise, use raw() to convert the schema definition\n\tconst isCompiledType = typeof def === \"function\" && \"assert\" in def;\n\tlet schema = isCompiledType ? def : $.type.raw(def as EnvSchema<T>);\n\n\t// Apply the `onUndeclaredKey` option\n\tschema = schema.onUndeclaredKey(onUndeclaredKey);\n\n\t// Apply coercion transformation to allow strings to be parsed as numbers/booleans\n\tif (shouldCoerce) {\n\t\tschema = coerce(schema, { arrayFormat });\n\t}\n\n\t// Validate the environment variables\n\tconst validatedEnv = schema(env);\n\n\tif (validatedEnv instanceof type.errors) {\n\t\tthrow new ArkEnvError(validatedEnv);\n\t}\n\n\treturn validatedEnv;\n}\n","export type { EnvSchema } from \"./create-env\";\n\nimport { createEnv } from \"./create-env\";\n\n/**\n * `arkenv`'s main export, an alias for {@link createEnv}\n *\n * {@link https://arkenv.js.org | ArkEnv} is a typesafe environment variables validator from editor to runtime.\n */\nconst arkenv = createEnv;\nexport default arkenv;\nexport { type } from \"./type\";\nexport { createEnv };\nexport { ArkEnvError } from \"./errors\";\n"],"mappings":"0CAA+B,MAAM,EAAEA,EAAE,UAAU,CAAC,KAAK,GAAG,CAAC,GAAG,OAAO,GAAG,UAAU,OAAO,GAAG,SAAS,OAAO,EAAE,IAAIC,EAAE,EAAE,MAAM,CAAC,GAAGA,IAAI,GAAG,OAAO,EAAE,GAAGA,IAAI,MAAM,MAAO,KAAI,IAAIC,EAAE,OAAOD,EAAE,CAAC,OAAO,OAAO,MAAMC,EAAE,CAAC,EAAEA,GAAG,CAAC,EAAEF,EAAE,UAAU,CAAC,KAAK,GAAG,IAAI,OAAO,CAAC,EAAE,IAAI,QAAQ,CAAC,EAAE,EAAE,CAAC,EAAEA,EAAE,+BAA+B,CAACG,EAAEH,EAAE,0BAA0B,CAAC,EAAEA,EAAE,UAAU,CAAC,KAAK,GAAG,CAAC,GAAG,OAAO,GAAG,SAAS,OAAO,EAAE,IAAIC,EAAE,EAAE,MAAM,CAAC,GAAG,CAACA,EAAE,WAAW,IAAI,EAAE,CAACA,EAAE,WAAW,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,KAAK,MAAMA,EAAE,MAAM,CAAC,OAAO,IAAI,CCApZ,EAAEG,EAAE,CAAC,OAAOC,EAAE,OAAO,CAAC,GAAGA,EAAE,SAAS,OAAO,KAAKC,EAAE,CAAC,CAAC,OAAOD,EAAE,OAAO,C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AAM,QAAQ,MAAM,EAAK,OAAO,CAChC,EAAM,QAGH,EAAa,EAAmB,MAAM,oBAAoB,CAC1D,EAAmB,EACtB,EAAmB,QACnB,SAAS,EAAW,GAAG,IACvB,QAAQ,EAAU,OAAQ,IAAI,EAAW,GAAG,GAAG,CAAC,GAChD,CACA,EAEH,MAAO,GAAG,EAAU,SAAU,EAAK,CAAC,GAAG,EAAiB,WAAW,IAClE,CACD,KAAK;EAAK,CAEb,IAAa,EAAb,cAAiC,KAAM,CACtC,YACC,EACA,EAAU,sDACT,CACD,MAAM,GAAG,EAAU,MAAO,EAAQ,CAAC,IAAI,EAAO,EAAa,EAAO,CAAC,CAAC,IAAI,CACxE,KAAK,KAAO,gBAId,OAAO,eAAe,EAAa,OAAQ,CAAE,MAAO,cAAe,CAAC,CCpCpE,MAAa,EAAOC,EAAE,KCwEtB,SAAgB,EACf,EACA,CACC,MAAM,QAAQ,IACd,OAAQ,EAAe,GACvB,kBAAkB,SAClB,cAAc,SACG,EAAE,CACkC,CAItD,IAAI,EADmB,OAAO,GAAQ,YAAc,WAAY,EAClC,EAAMC,EAAE,KAAK,IAAI,EAAoB,CAGnE,EAAS,EAAO,gBAAgB,EAAgB,CAG5C,IACH,EAAS,EAAO,EAAQ,CAAE,cAAa,CAAC,EAIzC,IAAM,EAAe,EAAO,EAAI,CAEhC,GAAI,aAAwB,EAAK,OAChC,MAAM,IAAI,EAAY,EAAa,CAGpC,OAAO,EC7FR,IAAA,EADe"}
1
+ {"version":3,"file":"index.js","names":["output: Record<string, unknown>","errors: InternalValidationError[]","lastError: any","e: any","msg"],"sources":["../src/parse-standard.ts","../src/utils/load-arktype.ts","../src/create-env.ts","../src/index.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@repo/types\";\nimport type { ArkEnvConfig } from \"./create-env.ts\";\nimport { ArkEnvError, type InternalValidationError } from \"./errors.ts\";\n\n/**\n * Standard Schema 1.0 parser dispatcher.\n * This helper implements parsing for the 'validator: \"standard\"' mode.\n */\nexport function parseStandard(\n\tdef: Record<string, unknown>,\n\tconfig: ArkEnvConfig,\n) {\n\tconst { env = process.env, onUndeclaredKey = \"delete\" } = config;\n\tconst output: Record<string, unknown> = {};\n\tconst errors: InternalValidationError[] = [];\n\tconst envKeys = new Set(Object.keys(env));\n\n\t// 1. Validate declared keys\n\tfor (const key in def) {\n\t\tconst validator = def[key];\n\t\tconst value = env[key];\n\n\t\t// Check if it's a Standard Schema validator\n\t\tif (\n\t\t\t!validator ||\n\t\t\ttypeof validator !== \"object\" ||\n\t\t\t!(\"~standard\" in validator)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid schema for key \"${key}\": expected a Standard Schema 1.0 validator (e.g. Zod, Valibot) in \"standard\" mode.`,\n\t\t\t);\n\t\t}\n\n\t\tconst result = (validator as StandardSchemaV1)[\"~standard\"].validate(value);\n\n\t\tif (result instanceof Promise) {\n\t\t\tthrow new Error(\n\t\t\t\t`Async validation is not supported for key \"${key}\". ArkEnv is synchronous.`,\n\t\t\t);\n\t\t}\n\n\t\tif (result.issues) {\n\t\t\tfor (const issue of result.issues) {\n\t\t\t\terrors.push({\n\t\t\t\t\tpath: key,\n\t\t\t\t\tmessage: issue.message,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\toutput[key] = result.value;\n\t\t}\n\n\t\tenvKeys.delete(key);\n\t}\n\n\t// 2. Handle undeclared keys\n\tif (onUndeclaredKey !== \"delete\") {\n\t\tfor (const key of envKeys) {\n\t\t\tif (onUndeclaredKey === \"reject\") {\n\t\t\t\terrors.push({\n\t\t\t\t\tpath: key,\n\t\t\t\t\tmessage: \"Undeclared key\",\n\t\t\t\t});\n\t\t\t} else if (onUndeclaredKey === \"ignore\") {\n\t\t\t\toutput[key] = env[key];\n\t\t\t}\n\t\t}\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new ArkEnvError(errors);\n\t}\n\n\treturn output;\n}\n","import { createRequire } from \"node:module\";\n\n/**\n * Dynamically loads the ArkType validator module.\n * Provides a clear error message if the 'arktype' peer dependency is missing.\n */\nexport function loadArkTypeValidator() {\n\tconst require = createRequire(import.meta.url);\n\n\t// We try multiple paths to support both source execution (src/utils/load-arktype.ts)\n\t// and bundled execution (dist/index.js or dist/index.cjs where this is inlined).\n\tconst searchPaths = [\n\t\t\"./arktype.cjs\",\n\t\t\"../arktype.cjs\",\n\t\t\"./arktype/index.cjs\",\n\t\t\"../arktype/index.cjs\",\n\t\t\"./arktype\",\n\t\t\"../arktype\",\n\t\t\"./arktype/index.ts\",\n\t\t\"../arktype/index.ts\",\n\t];\n\n\tlet lastError: any;\n\n\tfor (const path of searchPaths) {\n\t\ttry {\n\t\t\treturn require(path);\n\t\t} catch (e: any) {\n\t\t\tlastError = e;\n\n\t\t\t// Check if this error is specifically about the 'arktype' package being missing.\n\t\t\t// If require(path) failed because of a missing 'arktype' dependency INSIDE the path,\n\t\t\t// the error code will be MODULE_NOT_FOUND, but the message will not mention our path.\n\t\t\tif (e.code === \"MODULE_NOT_FOUND\") {\n\t\t\t\tconst msg = e.message || \"\";\n\t\t\t\t// Nested failure: The error is about 'arktype' (the package) but we were trying to load a relative path.\n\t\t\t\tconst isNestedArkTypeFailure =\n\t\t\t\t\t(msg.includes(\"'arktype'\") ||\n\t\t\t\t\t\tmsg.includes('\"arktype\"') ||\n\t\t\t\t\t\tmsg.includes(\"Cannot find module 'arktype'\")) &&\n\t\t\t\t\t!msg.includes(path);\n\n\t\t\t\tif (isNestedArkTypeFailure) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we reach here, either we searched all paths and none worked,\n\t// or we broke early because of a missing peer dependency.\n\tconst msg = lastError?.message || \"\";\n\t// Simpler heuristic: if the code is MODULE_NOT_FOUND and the message contains 'arktype'\n\t// but doesn't look like a relative path error for the current try.\n\tconst isMissingArkType =\n\t\tlastError?.code === \"MODULE_NOT_FOUND\" &&\n\t\t(msg.includes(\"'arktype'\") ||\n\t\t\tmsg.includes('\"arktype\"') ||\n\t\t\tmsg.includes(\"Cannot find module 'arktype'\")) &&\n\t\t!msg.includes(\"./arktype\") &&\n\t\t!msg.includes(\"../arktype\");\n\n\tif (isMissingArkType) {\n\t\tthrow new Error(\n\t\t\t\"The 'arktype' package is required when using the default validator mode. \" +\n\t\t\t\t\"Please install it (npm install arktype) or set 'validator: \\\"standard\\\"' in your config \" +\n\t\t\t\t\"if you only intend to use Standard Schema validators (like Zod or Valibot).\",\n\t\t);\n\t}\n\n\t// If it's some other error (like a syntax error in the validator), propagate it\n\tthrow lastError;\n}\n","import type { $ } from \"@repo/scope\";\nimport type {\n\tCompiledEnvSchema,\n\tDict,\n\tInferType,\n\tSchemaShape,\n\tStandardSchemaV1,\n} from \"@repo/types\";\nimport type { type as at, distill } from \"arktype\";\nimport { ArkEnvError } from \"./errors.ts\";\nimport { parseStandard } from \"./parse-standard.ts\";\nimport { loadArkTypeValidator } from \"./utils/load-arktype.ts\";\n\n/**\n * Declarative environment schema definition accepted by ArkEnv.\n *\n * Represents a declarative schema object mapping environment\n * variable names to schema definitions (e.g. ArkType DSL strings\n * or Standard Schema validators).\n *\n * This type is used to validate that a schema object is compatible with\n * ArkEnv’s validator scope before being compiled or parsed.\n *\n * Most users will provide schemas in this form.\n *\n * @template def - The schema shape object\n */\nexport type EnvSchema<def> = at.validate<def, $>;\ntype RuntimeEnvironment = Dict<string>;\n\n/**\n * Configuration options for `createEnv`\n */\nexport type ArkEnvConfig = {\n\t/**\n\t * The environment variables to parse. Defaults to `process.env`\n\t */\n\tenv?: RuntimeEnvironment;\n\t/**\n\t * Whether to coerce environment variables to their defined types. Defaults to `true`\n\t */\n\tcoerce?: boolean;\n\t/**\n\t * Control how ArkEnv handles environment variables that are not defined in your schema.\n\t *\n\t * Defaults to `'delete'` to ensure your output object only contains\n\t * keys you've explicitly declared. This differs from ArkType's standard behavior, which\n\t * mirrors TypeScript by defaulting to `'ignore'`.\n\t *\n\t * - `delete` (ArkEnv default): Undeclared keys are allowed on input but stripped from the output.\n\t * - `ignore` (ArkType default): Undeclared keys are allowed and preserved in the output.\n\t * - `reject`: Undeclared keys will cause validation to fail.\n\t *\n\t * @default \"delete\"\n\t * @see https://arktype.io/docs/configuration#onundeclaredkey\n\t */\n\tonUndeclaredKey?: \"ignore\" | \"delete\" | \"reject\";\n\n\t/**\n\t * The format to use for array parsing when coercion is enabled.\n\t *\n\t * - `comma` (default): Strings are split by comma and trimmed.\n\t * - `json`: Strings are parsed as JSON.\n\t *\n\t * @default \"comma\"\n\t */\n\tarrayFormat?: \"comma\" | \"json\";\n\t/**\n\t * Choose the validator engine to use.\n\t *\n\t * - `arktype` (default): Uses ArkType for all validation and coercion.\n\t * - `standard`: Uses Standard Schema 1.0 directly for validation. Coercion is not supported in this mode.\n\t *\n\t * @default \"arktype\"\n\t */\n\tvalidator?: \"arktype\" | \"standard\";\n};\n\n/**\n * TODO: `SchemaShape` is basically `Record<string, unknown>`.\n * If possible, find a better type than \"const T extends Record<string, unknown>\",\n * and be as close as possible to the type accepted by ArkType's `type`.\n */\n\n/**\n * Utility to parse environment variables using ArkType or Standard Schema\n * @param def - The schema definition\n * @param config - The evaluation configuration\n * @returns The parsed environment variables\n * @throws An {@link ArkEnvError | error} if the environment variables are invalid.\n */\nexport function createEnv<const T extends Record<string, StandardSchemaV1>>(\n\tdef: T,\n\tconfig: ArkEnvConfig & { validator: \"standard\" },\n): { [K in keyof T]: StandardSchemaV1.InferOutput<T[K]> };\nexport function createEnv<const T extends SchemaShape>(\n\tdef: EnvSchema<T>,\n\tconfig?: ArkEnvConfig,\n): distill.Out<at.infer<T, $>>;\nexport function createEnv<T extends CompiledEnvSchema>(\n\tdef: T,\n\tconfig?: ArkEnvConfig,\n): InferType<T>;\nexport function createEnv<const T extends SchemaShape>(\n\tdef: EnvSchema<T> | CompiledEnvSchema,\n\tconfig: ArkEnvConfig = {},\n): distill.Out<at.infer<T, $>> | InferType<typeof def> {\n\tconst mode = config.validator ?? \"arktype\";\n\n\tif (mode === \"standard\") {\n\t\t// Runtime guard: reject ArkType values in standard mode\n\t\tif (!def || typeof def !== \"object\" || Array.isArray(def)) {\n\t\t\tthrow new ArkEnvError([\n\t\t\t\t{\n\t\t\t\t\tpath: \"\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t'Invalid schema: expected an object mapping in \"standard\" mode.',\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\n\t\t// Check each entry to ensure it's a Standard Schema validator\n\t\tfor (const key in def) {\n\t\t\tconst validator = (def as Record<string, unknown>)[key];\n\n\t\t\t// Reject strings (ArkType DSL)\n\t\t\tif (typeof validator === \"string\") {\n\t\t\t\tthrow new ArkEnvError([\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: key,\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t'ArkType DSL strings are not supported in \"standard\" mode. Use a Standard Schema validator (e.g., Zod, Valibot) or set validator: \"arktype\".',\n\t\t\t\t\t},\n\t\t\t\t]);\n\t\t\t}\n\n\t\t\t// Reject non-objects or objects without ~standard property (likely ArkType)\n\t\t\tif (\n\t\t\t\t!validator ||\n\t\t\t\ttypeof validator !== \"object\" ||\n\t\t\t\t!(\"~standard\" in validator)\n\t\t\t) {\n\t\t\t\tthrow new ArkEnvError([\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: key,\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t'Invalid validator: expected a Standard Schema 1.0 validator (must have \"~standard\" property). ArkType validators are not supported in \"standard\" mode. Use validator: \"arktype\" for ArkType schemas.',\n\t\t\t\t\t},\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\n\t\treturn parseStandard(def as Record<string, unknown>, config);\n\t}\n\n\tconst validator = loadArkTypeValidator();\n\tconst { parse } = validator;\n\n\treturn parse(def, config);\n}\n","import { createEnv } from \"./create-env.ts\";\n\nexport { createEnv };\nexport type { ArkEnvConfig, EnvSchema } from \"./create-env.ts\";\nexport { ArkEnvError } from \"./errors.ts\";\n\n/**\n * ArkEnv's main export, an alias for {@link createEnv}\n *\n * {@link https://arkenv.js.org | ArkEnv} is a typesafe environment variables validator from editor to runtime.\n */\nconst arkenv = createEnv;\nexport default arkenv;\n"],"mappings":"qFAQA,SAAgB,EACf,EACA,EACC,CACD,GAAM,CAAE,MAAM,QAAQ,IAAK,kBAAkB,UAAa,EACpDA,EAAkC,EAAE,CACpCC,EAAoC,EAAE,CACtC,EAAU,IAAI,IAAI,OAAO,KAAK,EAAI,CAAC,CAGzC,IAAK,IAAM,KAAO,EAAK,CACtB,IAAM,EAAY,EAAI,GAChB,EAAQ,EAAI,GAGlB,GACC,CAAC,GACD,OAAO,GAAc,UACrB,EAAE,cAAe,GAEjB,MAAU,MACT,2BAA2B,EAAI,qFAC/B,CAGF,IAAM,EAAU,EAA+B,aAAa,SAAS,EAAM,CAE3E,GAAI,aAAkB,QACrB,MAAU,MACT,8CAA8C,EAAI,2BAClD,CAGF,GAAI,EAAO,OACV,IAAK,IAAM,KAAS,EAAO,OAC1B,EAAO,KAAK,CACX,KAAM,EACN,QAAS,EAAM,QACf,CAAC,MAGH,EAAO,GAAO,EAAO,MAGtB,EAAQ,OAAO,EAAI,CAIpB,GAAI,IAAoB,aAClB,IAAM,KAAO,EACb,IAAoB,SACvB,EAAO,KAAK,CACX,KAAM,EACN,QAAS,iBACT,CAAC,CACQ,IAAoB,WAC9B,EAAO,GAAO,EAAI,IAKrB,GAAI,EAAO,OAAS,EACnB,MAAM,IAAI,EAAY,EAAO,CAG9B,OAAO,ECnER,SAAgB,GAAuB,CACtC,IAAM,EAAU,EAAc,OAAO,KAAK,IAAI,CAIxC,EAAc,CACnB,gBACA,iBACA,sBACA,uBACA,YACA,aACA,qBACA,sBACA,CAEGC,EAEJ,IAAK,IAAM,KAAQ,EAClB,GAAI,CACH,OAAO,EAAQ,EAAK,OACZC,EAAQ,CAMhB,GALA,EAAY,EAKR,EAAE,OAAS,mBAAoB,CAClC,IAAMC,EAAM,EAAE,SAAW,GAQzB,IALEA,EAAI,SAAS,YAAY,EACzBA,EAAI,SAAS,YAAY,EACzBA,EAAI,SAAS,+BAA+B,GAC7C,CAACA,EAAI,SAAS,EAAK,CAGnB,OAQJ,IAAM,EAAM,GAAW,SAAW,GAoBlC,MAhBC,GAAW,OAAS,qBACnB,EAAI,SAAS,YAAY,EACzB,EAAI,SAAS,YAAY,EACzB,EAAI,SAAS,+BAA+B,GAC7C,CAAC,EAAI,SAAS,YAAY,EAC1B,CAAC,EAAI,SAAS,aAAa,CAGjB,MACT,6OAGA,CAII,ECgCP,SAAgB,EACf,EACA,EAAuB,EAAE,CAC6B,CAGtD,IAFa,EAAO,WAAa,aAEpB,WAAY,CAExB,GAAI,CAAC,GAAO,OAAO,GAAQ,UAAY,MAAM,QAAQ,EAAI,CACxD,MAAM,IAAI,EAAY,CACrB,CACC,KAAM,GACN,QACC,iEACD,CACD,CAAC,CAIH,IAAK,IAAM,KAAO,EAAK,CACtB,IAAM,EAAa,EAAgC,GAGnD,GAAI,OAAO,GAAc,SACxB,MAAM,IAAI,EAAY,CACrB,CACC,KAAM,EACN,QACC,8IACD,CACD,CAAC,CAIH,GACC,CAAC,GACD,OAAO,GAAc,UACrB,EAAE,cAAe,GAEjB,MAAM,IAAI,EAAY,CACrB,CACC,KAAM,EACN,QACC,uMACD,CACD,CAAC,CAIJ,OAAO,EAAc,EAAgC,EAAO,CAI7D,GAAM,CAAE,SADU,GAAsB,CAGxC,OAAO,EAAM,EAAK,EAAO,CClJ1B,IAAA,EADe"}
package/package.json CHANGED
@@ -1,15 +1,22 @@
1
1
  {
2
2
  "name": "arkenv",
3
3
  "type": "module",
4
- "version": "0.8.3",
4
+ "version": "0.9.1",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "description": "Typesafe environment variables parsing and validation with ArkType",
9
9
  "exports": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js",
12
- "require": "./dist/index.cjs"
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./arktype": {
16
+ "types": "./dist/arktype/index.d.ts",
17
+ "import": "./dist/arktype/index.js",
18
+ "require": "./dist/arktype/index.cjs"
19
+ }
13
20
  },
14
21
  "files": [
15
22
  "dist"
@@ -33,33 +40,38 @@
33
40
  "devDependencies": {
34
41
  "@size-limit/esbuild-why": "12.0.0",
35
42
  "@size-limit/preset-small-lib": "12.0.0",
36
- "@types/node": "24.10.4",
43
+ "@types/node": "24.10.9",
37
44
  "arktype": "2.1.29",
38
45
  "rimraf": "6.1.2",
39
46
  "size-limit": "12.0.0",
40
47
  "tsdown": "0.18.4",
41
48
  "typescript": "5.9.3",
42
- "vitest": "4.0.16",
43
- "@repo/keywords": "0.2.1",
44
- "@repo/scope": "0.1.2",
45
- "@repo/types": "0.0.6"
49
+ "vitest": "4.0.17",
50
+ "@repo/scope": "0.1.3",
51
+ "@repo/types": "0.1.0"
46
52
  },
47
53
  "peerDependencies": {
48
54
  "arktype": "^2.1.22"
49
55
  },
56
+ "peerDependenciesMeta": {
57
+ "arktype": {
58
+ "optional": true
59
+ }
60
+ },
50
61
  "size-limit": [
51
62
  {
52
63
  "path": "dist/index.js",
53
- "limit": "2 kB",
64
+ "limit": "3 kB",
54
65
  "import": "*",
55
66
  "ignore": [
56
- "arktype"
67
+ "arktype",
68
+ "node:module"
57
69
  ]
58
70
  }
59
71
  ],
60
72
  "scripts": {
61
73
  "build": "tsdown",
62
- "size": "size-limit",
74
+ "size": "size-limit --json > .size-limit.json",
63
75
  "test:once": "pnpm test",
64
76
  "typecheck": "tsc --noEmit",
65
77
  "clean": "rimraf dist node_modules",