is-kit 1.15.2 → 1.16.0

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/README.md CHANGED
@@ -386,6 +386,10 @@ Use `struct(schema, { exact: true })` when extra own enumerable string keys
386
386
  should be rejected. Exact mode follows `Object.keys(...)` semantics, so symbol
387
387
  keys and non-enumerable properties are outside its key matching.
388
388
 
389
+ Schemas themselves must use own enumerable string keys. `struct` rejects
390
+ symbol-keyed, non-enumerable, and inherited schema fields so its runtime checks
391
+ match the inferred type.
392
+
389
393
  If the property must exist but the value may be `undefined`, use `optional(guard)` instead.
390
394
 
391
395
  ### 5. Validate arrays, tuples, maps, sets, and records
@@ -579,7 +583,13 @@ Use `discriminatedUnion<T>()` with `typedStruct` to keep both the branch
579
583
  fields and the union coverage aligned with an existing TypeScript type.
580
584
 
581
585
  ```ts
582
- import { discriminatedUnion, isNumber, oneOfValues, typedStruct } from 'is-kit';
586
+ import {
587
+ discriminatedUnion,
588
+ discriminatedUnionWithFallback,
589
+ isNumber,
590
+ oneOfValues,
591
+ typedStruct
592
+ } from 'is-kit';
583
593
 
584
594
  type Event =
585
595
  { kind: 'click'; x: number; y: number } | { kind: 'scroll'; delta: number };
@@ -611,6 +621,55 @@ For a `__proto__` discriminant, write the branch as `['__proto__']: guard` (or
611
621
  use a null-prototype map); the uncomputed object-literal form changes the
612
622
  object's prototype instead of creating a branch entry.
613
623
 
624
+ #### Classify explicit fallback variants
625
+
626
+ Use `discriminatedUnionWithFallback<T>()` when an input may contain future
627
+ discriminant values. Known branches remain exhaustive. An undeclared own
628
+ primitive discriminant instead calls `fallback.create`, which returns payload
629
+ for one canonical fallback tag or `undefined` to mark the input invalid. The
630
+ payload must be an own data-field plain record with an `Object.prototype` or
631
+ null prototype; arrays, dates, functions, class instances, custom prototypes,
632
+ accessor fields, and function fields are rejected so the decoded value always
633
+ matches its object shape. Dictionary
634
+ payload _types_ with broad or patterned index signatures are also unsupported;
635
+ use a finite object shape for each fallback variant.
636
+
637
+ ```ts
638
+ const classifyEvent = discriminatedUnionWithFallback<Event>()(
639
+ 'kind',
640
+ ['click', 'scroll'],
641
+ {
642
+ click: typedStruct<Extract<Event, { kind: 'click' }>>()({
643
+ kind: oneOfValues('click'),
644
+ x: isNumber,
645
+ y: isNumber
646
+ }),
647
+ scroll: typedStruct<Extract<Event, { kind: 'scroll' }>>()({
648
+ kind: oneOfValues('scroll'),
649
+ delta: isNumber
650
+ })
651
+ },
652
+ {
653
+ tag: 'unknown',
654
+ create: (input, originalKind) => ({ input, originalKind })
655
+ }
656
+ );
657
+
658
+ const result = classifyEvent(value);
659
+ if (result.valid) {
660
+ const event = result.value;
661
+ // Event member | { kind: 'unknown'; input: unknown; originalKind: PropertyKey | boolean }
662
+ }
663
+ ```
664
+
665
+ The fallback tag must be one literal with a distinct runtime key from every
666
+ known discriminant, so a known `1` also reserves the tag `'1'` (and `true`
667
+ reserves `'true'`). The classifier determines whether a raw discriminant is
668
+ known before converting it to a branch key, then writes the fallback tag after
669
+ creating its payload. A malformed known branch, missing or inherited
670
+ discriminant, non-primitive discriminant, or non-plain fallback payload returns
671
+ `{ valid: false }` without producing a fallback variant.
672
+
614
673
  ### 12. Narrow object keys
615
674
 
616
675
  Use key helpers when the important part of a value is one property.
@@ -785,6 +844,12 @@ For detailed API pages and more examples, see:
785
844
  Start with [How to safely filter null and undefined from arrays in
786
845
  TypeScript](https://is-kit.dev/guides/filter-null-and-undefined).
787
846
 
847
+ ## Compatibility
848
+
849
+ is-kit requires Node.js 22 or later. CI validates the packed npm artifact on
850
+ Node.js 22.x and 24.x with native ESM, CommonJS, and strict TypeScript
851
+ NodeNext consumers.
852
+
788
853
  ## 👨‍💻 Development
789
854
 
790
855
  Requires Node 22.22.0 and pnpm 11.2.2.
package/dist/index.d.mts CHANGED
@@ -674,9 +674,10 @@ export declare const isDataView: Guard$1<DataView<ArrayBufferLike>>;
674
674
  */
675
675
  export declare const isTypedArray: Predicate<ArrayBufferView<ArrayBufferLike>>;
676
676
  /**
677
- * Checks whether a value is an `Error` (instance of Error or plain Error object tag).
677
+ * Checks whether a value is an `Error`.
678
678
  *
679
679
  * @returns Predicate narrowing to `Error`.
680
+ * @see https://github.com/nyaomaru/is-kit/issues/325
680
681
  */
681
682
  export declare const isError: Predicate<Error>;
682
683
  /**
@@ -738,6 +739,22 @@ type MatchingDiscriminantMember<T extends object, K extends DiscriminantKey<T>,
738
739
  type DiscriminatedUnionGuardMap<T extends object, K extends DiscriminantKey<T>, Values extends DiscriminantValue> = { readonly [Value in Values as DiscriminantMapKey<Value>]: Predicate<MatchingDiscriminantMember<T, K, Value>>; };
739
740
  type InvalidGuardDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = { [Value in Values as DiscriminantMapKey<Value>]: G extends Record<DiscriminantMapKey<Value>, infer Guard> ? GuardedOf<Guard> extends Record<K, DiscriminantValue> ? Value extends GuardedOf<Guard>[K] ? never : Value : Value : Value; }[DiscriminantMapKey<Values>];
740
741
  type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = [InvalidGuardDiscriminantValues<K, Values, G>] extends [never] ? unknown : never;
742
+ type FallbackDiscriminant<Values extends DiscriminantValue, Value extends DiscriminantValue> = IsFiniteDiscriminantValue<Value> extends true ? IsUnion<Value> extends false ? DiscriminantRuntimeKey<Value> extends DiscriminantRuntimeKey<Values> ? never : unknown : never : never;
743
+ type RuntimePropertyKey<Key extends PropertyKey> = Key extends symbol ? Key : Key extends string | number ? `${Key}` : never;
744
+ type OmitRuntimeKey<Data extends object, Key extends PropertyKey> = { [Property in keyof Data as RuntimePropertyKey<Property> extends RuntimePropertyKey<Key> ? never : Property]: Data[Property]; };
745
+ type InvalidFallbackKey<Key extends PropertyKey> = Key extends unknown ? SinglePropertyKey<Key> extends never ? Key : never : never;
746
+ type InvalidFallbackData<Data extends object> = Data extends unknown ? [InvalidFallbackKey<keyof Data & PropertyKey>] extends [never] ? never : Data : never;
747
+ type FiniteFallbackData<Data extends object> = [InvalidFallbackData<Data>] extends [never] ? unknown : never;
748
+ type FallbackVariant<K extends PropertyKey, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = Data extends unknown ? OmitRuntimeKey<Data, K> & Record<K, Value> : never;
749
+ type FallbackVariantConfig<Values extends DiscriminantValue, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = {
750
+ readonly tag: Value & FallbackDiscriminant<Values, Value>;
751
+ readonly create: (this: void, input: unknown, discriminant: DiscriminantValue) => Data | undefined;
752
+ };
753
+ type Decoder<Output> = (input: unknown) => ParseResult<Output>;
754
+ declare const invalidFallbackClassifier: unique symbol;
755
+ type InvalidFallbackClassifier = {
756
+ readonly [invalidFallbackClassifier]: 'Fallback payloads must have finite property keys.';
757
+ };
741
758
  /**
742
759
  * Creates an exhaustive guard for a union whose members share a literal discriminant.
743
760
  * A tuple of every discriminant value keeps finite coverage explicit at runtime
@@ -751,6 +768,16 @@ type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends Discrim
751
768
  * @returns Predicate narrowing to the union accepted by the branch guards.
752
769
  */
753
770
  export declare function discriminatedUnion<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>>(discriminant: K, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>) => Predicate<GuardedOf<G[keyof G]>>;
771
+ /**
772
+ * Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
773
+ * Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
774
+ * @param discriminant Required property that identifies each known union member.
775
+ * @param values Finite tuple containing every known discriminant value.
776
+ * @param guards Branch guards keyed by the known discriminant values.
777
+ * @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
778
+ * @returns Decoder that returns a guarded known member or fallback variant when valid.
779
+ */
780
+ export declare function discriminatedUnionWithFallback<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>, const FallbackValue extends DiscriminantValue, const FallbackData extends Record<PropertyKey, unknown>>(discriminant: K & SinglePropertyKey<K>, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>, fallback: FallbackVariantConfig<Values[number], FallbackValue, FallbackData>) => FiniteFallbackData<FallbackData> extends never ? InvalidFallbackClassifier : Decoder<GuardedOf<G[keyof G]> | FallbackVariant<K, FallbackValue, FallbackData>>;
754
781
  //#endregion
755
782
  //#region src/core/combinators/map.d.ts
756
783
  /**
@@ -787,14 +814,18 @@ export declare function oneOfValues<const T extends ReadonlyArray<Primitive>>(va
787
814
  export declare function oneOfValues<const T extends ReadonlyArray<Primitive>>(...valuesOrArray: T | [T]): Predicate<T[number]>;
788
815
  //#endregion
789
816
  //#region src/core/combinators/record.d.ts
817
+ type RecordOfResult<K extends string, V> = string extends K ? Readonly<Record<string, V>> : Readonly<Partial<Record<K, V>>>;
790
818
  /**
791
819
  * Validates a record-like object by guarding both keys and values.
792
820
  *
793
- * @param keyFunction Guard for string keys (e.g., specific literal keys pattern).
821
+ * The key guard restricts which string keys may be present; it does not require
822
+ * every key represented by the guarded key type.
823
+ *
824
+ * @param keyFunction Guard for string keys (for example, a literal-key pattern).
794
825
  * @param valueFunction Guard applied to each value in the record.
795
826
  * @returns Predicate narrowing to a readonly record with guarded key/value types.
796
827
  */
797
- export declare function recordOf<KF extends Predicate<string>, VF extends Predicate<unknown>>(keyFunction: KF, valueFunction: VF): Predicate<Readonly<Record<GuardedOf<KF>, GuardedOf<VF>>>>;
828
+ export declare function recordOf<KF extends Predicate<string>, VF extends Predicate<unknown>>(keyFunction: KF, valueFunction: VF): Predicate<RecordOfResult<GuardedOf<KF>, GuardedOf<VF>>>;
798
829
  //#endregion
799
830
  //#region src/core/combinators/set.d.ts
800
831
  /**
@@ -817,16 +848,17 @@ export declare function setOf<VF extends Predicate<unknown>>(valueGuard: VF): Pr
817
848
  */
818
849
  export declare function optionalKey<G extends Predicate<unknown>>(guard: G): OptionalSchemaField<G>;
819
850
  /**
820
- * Validates an object against a field-to-guard schema with string runtime keys.
821
- * Numeric schema keys are normalized to strings by JavaScript; symbol-keyed fields
822
- * are not supported. Keys are required unless wrapped with `optionalKey`; optionally
823
- * rejects extra keys when `exact: true`.
851
+ * Validates an object against a field-to-guard schema with own enumerable string
852
+ * keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
853
+ * non-enumerable, and inherited fields are not supported. Keys are required unless
854
+ * wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
824
855
  *
825
856
  * @param schema Record of string- or numeric-keyed property guards.
826
857
  * @param options When `{ exact: true }`, disallows own enumerable string-key
827
858
  * properties not in `schema`.
828
859
  * @returns Predicate that narrows to the inferred struct type.
829
- * @throws {TypeError} If `schema` has own symbol-keyed fields.
860
+ * @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
861
+ * string-keyed fields.
830
862
  */
831
863
  export declare function struct<const S extends SchemaShape<S>>(schema: StructSchemaShape<S>, options?: StructOptions): Predicate<InferSchema<S>>;
832
864
  //#endregion
package/dist/index.d.ts CHANGED
@@ -674,9 +674,10 @@ export declare const isDataView: Guard$1<DataView<ArrayBufferLike>>;
674
674
  */
675
675
  export declare const isTypedArray: Predicate<ArrayBufferView<ArrayBufferLike>>;
676
676
  /**
677
- * Checks whether a value is an `Error` (instance of Error or plain Error object tag).
677
+ * Checks whether a value is an `Error`.
678
678
  *
679
679
  * @returns Predicate narrowing to `Error`.
680
+ * @see https://github.com/nyaomaru/is-kit/issues/325
680
681
  */
681
682
  export declare const isError: Predicate<Error>;
682
683
  /**
@@ -738,6 +739,22 @@ type MatchingDiscriminantMember<T extends object, K extends DiscriminantKey<T>,
738
739
  type DiscriminatedUnionGuardMap<T extends object, K extends DiscriminantKey<T>, Values extends DiscriminantValue> = { readonly [Value in Values as DiscriminantMapKey<Value>]: Predicate<MatchingDiscriminantMember<T, K, Value>>; };
739
740
  type InvalidGuardDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = { [Value in Values as DiscriminantMapKey<Value>]: G extends Record<DiscriminantMapKey<Value>, infer Guard> ? GuardedOf<Guard> extends Record<K, DiscriminantValue> ? Value extends GuardedOf<Guard>[K] ? never : Value : Value : Value; }[DiscriminantMapKey<Values>];
740
741
  type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends DiscriminantValue, G extends object> = [InvalidGuardDiscriminantValues<K, Values, G>] extends [never] ? unknown : never;
742
+ type FallbackDiscriminant<Values extends DiscriminantValue, Value extends DiscriminantValue> = IsFiniteDiscriminantValue<Value> extends true ? IsUnion<Value> extends false ? DiscriminantRuntimeKey<Value> extends DiscriminantRuntimeKey<Values> ? never : unknown : never : never;
743
+ type RuntimePropertyKey<Key extends PropertyKey> = Key extends symbol ? Key : Key extends string | number ? `${Key}` : never;
744
+ type OmitRuntimeKey<Data extends object, Key extends PropertyKey> = { [Property in keyof Data as RuntimePropertyKey<Property> extends RuntimePropertyKey<Key> ? never : Property]: Data[Property]; };
745
+ type InvalidFallbackKey<Key extends PropertyKey> = Key extends unknown ? SinglePropertyKey<Key> extends never ? Key : never : never;
746
+ type InvalidFallbackData<Data extends object> = Data extends unknown ? [InvalidFallbackKey<keyof Data & PropertyKey>] extends [never] ? never : Data : never;
747
+ type FiniteFallbackData<Data extends object> = [InvalidFallbackData<Data>] extends [never] ? unknown : never;
748
+ type FallbackVariant<K extends PropertyKey, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = Data extends unknown ? OmitRuntimeKey<Data, K> & Record<K, Value> : never;
749
+ type FallbackVariantConfig<Values extends DiscriminantValue, Value extends DiscriminantValue, Data extends Record<PropertyKey, unknown>> = {
750
+ readonly tag: Value & FallbackDiscriminant<Values, Value>;
751
+ readonly create: (this: void, input: unknown, discriminant: DiscriminantValue) => Data | undefined;
752
+ };
753
+ type Decoder<Output> = (input: unknown) => ParseResult<Output>;
754
+ declare const invalidFallbackClassifier: unique symbol;
755
+ type InvalidFallbackClassifier = {
756
+ readonly [invalidFallbackClassifier]: 'Fallback payloads must have finite property keys.';
757
+ };
741
758
  /**
742
759
  * Creates an exhaustive guard for a union whose members share a literal discriminant.
743
760
  * A tuple of every discriminant value keeps finite coverage explicit at runtime
@@ -751,6 +768,16 @@ type GuardsMatchDiscriminantValues<K extends PropertyKey, Values extends Discrim
751
768
  * @returns Predicate narrowing to the union accepted by the branch guards.
752
769
  */
753
770
  export declare function discriminatedUnion<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>>(discriminant: K, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>) => Predicate<GuardedOf<G[keyof G]>>;
771
+ /**
772
+ * Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
773
+ * Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
774
+ * @param discriminant Required property that identifies each known union member.
775
+ * @param values Finite tuple containing every known discriminant value.
776
+ * @param guards Branch guards keyed by the known discriminant values.
777
+ * @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
778
+ * @returns Decoder that returns a guarded known member or fallback variant when valid.
779
+ */
780
+ export declare function discriminatedUnionWithFallback<T extends object>(): <const K extends DiscriminantKey<T>, const Values extends readonly DiscriminantValue[], const G extends DiscriminatedUnionGuardMap<T, K, Values[number]>, const FallbackValue extends DiscriminantValue, const FallbackData extends Record<PropertyKey, unknown>>(discriminant: K & SinglePropertyKey<K>, values: Values & ExactDiscriminantValues<T, K, Values>, guards: NoExtraKeys<G, DiscriminatedUnionGuardMap<T, K, Values[number]>> & NonCollidingDiscriminants<T, K> & GuardsMatchDiscriminantValues<K, Values[number], G>, fallback: FallbackVariantConfig<Values[number], FallbackValue, FallbackData>) => FiniteFallbackData<FallbackData> extends never ? InvalidFallbackClassifier : Decoder<GuardedOf<G[keyof G]> | FallbackVariant<K, FallbackValue, FallbackData>>;
754
781
  //#endregion
755
782
  //#region src/core/combinators/map.d.ts
756
783
  /**
@@ -787,14 +814,18 @@ export declare function oneOfValues<const T extends ReadonlyArray<Primitive>>(va
787
814
  export declare function oneOfValues<const T extends ReadonlyArray<Primitive>>(...valuesOrArray: T | [T]): Predicate<T[number]>;
788
815
  //#endregion
789
816
  //#region src/core/combinators/record.d.ts
817
+ type RecordOfResult<K extends string, V> = string extends K ? Readonly<Record<string, V>> : Readonly<Partial<Record<K, V>>>;
790
818
  /**
791
819
  * Validates a record-like object by guarding both keys and values.
792
820
  *
793
- * @param keyFunction Guard for string keys (e.g., specific literal keys pattern).
821
+ * The key guard restricts which string keys may be present; it does not require
822
+ * every key represented by the guarded key type.
823
+ *
824
+ * @param keyFunction Guard for string keys (for example, a literal-key pattern).
794
825
  * @param valueFunction Guard applied to each value in the record.
795
826
  * @returns Predicate narrowing to a readonly record with guarded key/value types.
796
827
  */
797
- export declare function recordOf<KF extends Predicate<string>, VF extends Predicate<unknown>>(keyFunction: KF, valueFunction: VF): Predicate<Readonly<Record<GuardedOf<KF>, GuardedOf<VF>>>>;
828
+ export declare function recordOf<KF extends Predicate<string>, VF extends Predicate<unknown>>(keyFunction: KF, valueFunction: VF): Predicate<RecordOfResult<GuardedOf<KF>, GuardedOf<VF>>>;
798
829
  //#endregion
799
830
  //#region src/core/combinators/set.d.ts
800
831
  /**
@@ -817,16 +848,17 @@ export declare function setOf<VF extends Predicate<unknown>>(valueGuard: VF): Pr
817
848
  */
818
849
  export declare function optionalKey<G extends Predicate<unknown>>(guard: G): OptionalSchemaField<G>;
819
850
  /**
820
- * Validates an object against a field-to-guard schema with string runtime keys.
821
- * Numeric schema keys are normalized to strings by JavaScript; symbol-keyed fields
822
- * are not supported. Keys are required unless wrapped with `optionalKey`; optionally
823
- * rejects extra keys when `exact: true`.
851
+ * Validates an object against a field-to-guard schema with own enumerable string
852
+ * keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
853
+ * non-enumerable, and inherited fields are not supported. Keys are required unless
854
+ * wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
824
855
  *
825
856
  * @param schema Record of string- or numeric-keyed property guards.
826
857
  * @param options When `{ exact: true }`, disallows own enumerable string-key
827
858
  * properties not in `schema`.
828
859
  * @returns Predicate that narrows to the inferred struct type.
829
- * @throws {TypeError} If `schema` has own symbol-keyed fields.
860
+ * @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
861
+ * string-keyed fields.
830
862
  */
831
863
  export declare function struct<const S extends SchemaShape<S>>(schema: StructSchemaShape<S>, options?: StructOptions): Predicate<InferSchema<S>>;
832
864
  //#endregion
package/dist/index.js CHANGED
@@ -41,6 +41,7 @@ const getTag = (value) => objectToString.call(value);
41
41
  //#endregion
42
42
  //#region src/core/object.ts
43
43
  const BUILTIN_BRAND_SENTINEL = Object.freeze({});
44
+ const nativeIsError = Error.isError;
44
45
  const getIntrinsicGetter = (prototype, key) => {
45
46
  return Object.getOwnPropertyDescriptor(prototype, key)?.get ?? (() => {
46
47
  throw new TypeError(`Missing intrinsic getter: ${String(key)}`);
@@ -175,11 +176,18 @@ const isDataView = defineIntrinsicBrandGuard((value) => dataViewBuffer.call(valu
175
176
  */
176
177
  const isTypedArray = define((value) => typedArrayName?.call(value) !== void 0);
177
178
  /**
178
- * Checks whether a value is an `Error` (instance of Error or plain Error object tag).
179
+ * Checks whether a value is an `Error`.
179
180
  *
180
181
  * @returns Predicate narrowing to `Error`.
182
+ * @see https://github.com/nyaomaru/is-kit/issues/325
181
183
  */
182
- const isError = define((value) => value instanceof Error || getTag(value) === "[object Error]");
184
+ const isError = define((value) => {
185
+ try {
186
+ return typeof nativeIsError === "function" ? nativeIsError(value) : value instanceof Error || getTag(value) === "[object Error]";
187
+ } catch {
188
+ return false;
189
+ }
190
+ });
183
191
  /**
184
192
  * Checks whether a value is a `URL` (in environments with URL available).
185
193
  *
@@ -529,7 +537,6 @@ const isNotNil = (value) => value !== null && value !== void 0;
529
537
  const isPrimitive = or(isString, isNumberPrimitive, isBoolean, isBigInt, isSymbol, isUndefined, isNull);
530
538
  //#endregion
531
539
  //#region src/utils/guard-collections.ts
532
- const arrayValues = Array.prototype.values;
533
540
  const mapEntries = Map.prototype.entries;
534
541
  const setValues = Set.prototype.values;
535
542
  const everyIterableValue = (values, predicate) => {
@@ -552,9 +559,13 @@ const everyKeyValueEntry = (entries, predicate) => {
552
559
  const everyArrayValue = (values, predicate) => everyIterableValue(values, predicate);
553
560
  /**
554
561
  * Checks built-in Array data without invoking an instance-provided iterator.
555
- * WHY: An Array subclass or instance may override its public iterator and throw.
562
+ * WHY: Indexed reads preserve hole-as-undefined semantics while avoiding iterator
563
+ * allocation on this hot path. They also bypass iterator overrides on subclasses.
556
564
  */
557
- const everyBrandedArrayValue = (values, predicate) => everyIterableValue(arrayValues.call(values), predicate);
565
+ const everyBrandedArrayValue = (values, predicate) => {
566
+ for (let index = 0; index < values.length; index += 1) if (!predicate(values[index])) return false;
567
+ return true;
568
+ };
558
569
  /**
559
570
  * Checks whether a tuple matches the provided element predicates in order.
560
571
  *
@@ -637,8 +648,48 @@ function nonEmptyArrayOf(elementGuard) {
637
648
  }
638
649
  //#endregion
639
650
  //#region src/core/combinators/discriminated-union.ts
651
+ function defineFallbackClassifier(classifier) {
652
+ return classifier;
653
+ }
654
+ function createFallbackVariant(fallbackData, discriminant, tag) {
655
+ const fallbackVariant = {};
656
+ const discriminantKey = isSymbol(discriminant) ? discriminant : String(discriminant);
657
+ for (const key of Reflect.ownKeys(fallbackData)) {
658
+ if (key === discriminantKey) continue;
659
+ const descriptor = Object.getOwnPropertyDescriptor(fallbackData, key);
660
+ if (descriptor !== void 0) Object.defineProperty(fallbackVariant, key, descriptor);
661
+ }
662
+ Object.defineProperty(fallbackVariant, discriminantKey, {
663
+ configurable: true,
664
+ enumerable: true,
665
+ value: tag,
666
+ writable: true
667
+ });
668
+ return fallbackVariant;
669
+ }
640
670
  const isDiscriminantValue = (value) => isString(value) || isNumberPrimitive(value) || isSymbol(value) || isBoolean(value);
671
+ const isFallbackDataDescriptor = (descriptor) => descriptor !== void 0 && "value" in descriptor && !isFunction(descriptor.value);
672
+ const isFallbackPayload = (value) => {
673
+ if (!isPlainObject(value)) return false;
674
+ const prototype = Object.getPrototypeOf(value);
675
+ if (prototype !== null && prototype !== Object.prototype) return false;
676
+ for (const key of Reflect.ownKeys(value)) {
677
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
678
+ if (!isFallbackDataDescriptor(descriptor)) return false;
679
+ }
680
+ return true;
681
+ };
641
682
  const toRuntimeKey = (value) => isSymbol(value) ? value : String(value);
683
+ const assertSafeFallbackTag = (values, tag) => {
684
+ if (!isDiscriminantValue(tag)) throw new TypeError("discriminatedUnion fallback tag must be a string, number, symbol, or boolean.");
685
+ const fallbackKey = toRuntimeKey(tag);
686
+ if (values.some((value) => toRuntimeKey(value) === fallbackKey)) throw new TypeError(`Fallback discriminatedUnion tag collides with a branch value: ${String(tag)}.`);
687
+ };
688
+ const getOwnDiscriminantValue = (input, discriminant) => {
689
+ if (!isObject(input) && !isFunction(input) || !hasOwnPropertyKey(input, discriminant)) return;
690
+ const value = Reflect.get(input, discriminant);
691
+ return isDiscriminantValue(value) ? value : void 0;
692
+ };
642
693
  const assertSafeProtoBranch = (values, guards) => {
643
694
  if (!values.includes("__proto__")) return;
644
695
  if (hasOwnPropertyKey(guards, "__proto__")) return;
@@ -671,9 +722,8 @@ function discriminatedUnion() {
671
722
  assertSafeProtoBranch(values, guards);
672
723
  const declaredKeys = assertBranchKeys(values, guards);
673
724
  return define((input) => {
674
- if (!isObject(input) && !isFunction(input) || !hasOwnPropertyKey(input, discriminant)) return false;
675
- const value = Reflect.get(input, discriminant);
676
- if (!isDiscriminantValue(value)) return false;
725
+ const value = getOwnDiscriminantValue(input, discriminant);
726
+ if (value === void 0) return false;
677
727
  const key = toRuntimeKey(value);
678
728
  if (!declaredKeys.has(key) || !hasOwnPropertyKey(guards, key)) return false;
679
729
  const guard = guards[key];
@@ -681,6 +731,44 @@ function discriminatedUnion() {
681
731
  });
682
732
  };
683
733
  }
734
+ /**
735
+ * Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
736
+ * Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
737
+ * @param discriminant Required property that identifies each known union member.
738
+ * @param values Finite tuple containing every known discriminant value.
739
+ * @param guards Branch guards keyed by the known discriminant values.
740
+ * @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
741
+ * @returns Decoder that returns a guarded known member or fallback variant when valid.
742
+ */
743
+ function discriminatedUnionWithFallback() {
744
+ return (discriminant, values, guards, fallback) => {
745
+ assertSafeProtoBranch(values, guards);
746
+ const fallbackTag = fallback.tag;
747
+ const createFallback = fallback.create;
748
+ assertSafeFallbackTag(values, fallbackTag);
749
+ assertBranchKeys(values, guards);
750
+ const declaredValues = new Set(values);
751
+ return defineFallbackClassifier((input) => {
752
+ const value = getOwnDiscriminantValue(input, discriminant);
753
+ if (value === void 0) return { valid: false };
754
+ if (!declaredValues.has(value)) {
755
+ const fallbackData = createFallback(input, value);
756
+ if (fallbackData === void 0 || !isFallbackPayload(fallbackData)) return { valid: false };
757
+ return {
758
+ valid: true,
759
+ value: createFallbackVariant(fallbackData, discriminant, fallbackTag)
760
+ };
761
+ }
762
+ const key = toRuntimeKey(value);
763
+ if (!hasOwnPropertyKey(guards, key)) return { valid: false };
764
+ const guard = guards[key];
765
+ return guard(input) ? {
766
+ valid: true,
767
+ value: input
768
+ } : { valid: false };
769
+ });
770
+ };
771
+ }
684
772
  //#endregion
685
773
  //#region src/core/combinators/map.ts
686
774
  /**
@@ -730,7 +818,10 @@ function oneOfValues(...args) {
730
818
  /**
731
819
  * Validates a record-like object by guarding both keys and values.
732
820
  *
733
- * @param keyFunction Guard for string keys (e.g., specific literal keys pattern).
821
+ * The key guard restricts which string keys may be present; it does not require
822
+ * every key represented by the guarded key type.
823
+ *
824
+ * @param keyFunction Guard for string keys (for example, a literal-key pattern).
734
825
  * @param valueFunction Guard applied to each value in the record.
735
826
  * @returns Predicate narrowing to a readonly record with guarded key/value types.
736
827
  */
@@ -750,10 +841,44 @@ function setOf(valueGuard) {
750
841
  }
751
842
  //#endregion
752
843
  //#region src/core/combinators/struct.ts
844
+ const OBJECT_CONSTRUCTOR_SOURCE = Function.prototype.toString.call(Object);
845
+ const isObjectPrototype = (prototype) => {
846
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
847
+ return typeof constructor === "function" && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === OBJECT_CONSTRUCTOR_SOURCE;
848
+ };
849
+ const hasOnlyEnumerableOwnStringKeys = (schema) => Object.getOwnPropertyNames(schema).every((key) => Object.prototype.propertyIsEnumerable.call(schema, key));
850
+ const hasInheritedStringKeys = (schema) => {
851
+ let prototype = Object.getPrototypeOf(schema);
852
+ while (prototype !== null && !isObjectPrototype(prototype)) {
853
+ if (Object.getOwnPropertyNames(prototype).some((key) => {
854
+ if (key !== "constructor") return true;
855
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, key);
856
+ return !(typeof descriptor?.value === "function" && descriptor.value.prototype === prototype);
857
+ })) return true;
858
+ prototype = Object.getPrototypeOf(prototype);
859
+ }
860
+ return false;
861
+ };
862
+ const hasInheritedSymbolKeys = (schema) => {
863
+ let prototype = Object.getPrototypeOf(schema);
864
+ while (prototype !== null && !isObjectPrototype(prototype)) {
865
+ if (Object.getOwnPropertySymbols(prototype).length > 0) return true;
866
+ prototype = Object.getPrototypeOf(prototype);
867
+ }
868
+ return false;
869
+ };
870
+ const assertValidSchemaKeys = (schema) => {
871
+ if (Object.getOwnPropertySymbols(schema).length > 0 || hasInheritedSymbolKeys(schema)) throw new TypeError("struct schema fields cannot use symbol keys");
872
+ if (!hasOnlyEnumerableOwnStringKeys(schema) || hasInheritedStringKeys(schema)) throw new TypeError("struct schema fields must be own enumerable string keys");
873
+ };
753
874
  const isOptionalSchemaField = define((field) => isObject(field) && field.optional === true && isFunction(field.guard));
754
875
  const hasRequiredKeys = (obj, entries) => entries.every(([key, guard]) => hasOwnPropertyKey(obj, key) && guard(obj[key]));
755
876
  const hasValidOptionalKeys = (obj, entries) => entries.every(([key, guard]) => !hasOwnPropertyKey(obj, key) || guard(obj[key]));
756
877
  const hasOnlyAllowedKeys = (obj, allowed) => Object.keys(obj).every((key) => allowed.has(key));
878
+ const hasOnlyRequiredKeys = (obj, schemaKeys, allowed) => {
879
+ const keys = Object.keys(obj);
880
+ return keys.length <= schemaKeys.length && keys.every((key, index) => key === schemaKeys[index] || allowed.has(key));
881
+ };
757
882
  /**
758
883
  * Marks a struct schema field as optional at the key level.
759
884
  *
@@ -770,23 +895,24 @@ function optionalKey(guard) {
770
895
  };
771
896
  }
772
897
  /**
773
- * Validates an object against a field-to-guard schema with string runtime keys.
774
- * Numeric schema keys are normalized to strings by JavaScript; symbol-keyed fields
775
- * are not supported. Keys are required unless wrapped with `optionalKey`; optionally
776
- * rejects extra keys when `exact: true`.
898
+ * Validates an object against a field-to-guard schema with own enumerable string
899
+ * keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
900
+ * non-enumerable, and inherited fields are not supported. Keys are required unless
901
+ * wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
777
902
  *
778
903
  * @param schema Record of string- or numeric-keyed property guards.
779
904
  * @param options When `{ exact: true }`, disallows own enumerable string-key
780
905
  * properties not in `schema`.
781
906
  * @returns Predicate that narrows to the inferred struct type.
782
- * @throws {TypeError} If `schema` has own symbol-keyed fields.
907
+ * @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
908
+ * string-keyed fields.
783
909
  */
784
910
  function struct(schema, options) {
785
911
  return createStruct(schema, options);
786
912
  }
787
913
  /** @internal Shared implementation for string-keyed schema builders. */
788
914
  function createStruct(schema, options) {
789
- if (Object.getOwnPropertySymbols(schema).length > 0) throw new TypeError("struct schema fields cannot use symbol keys");
915
+ assertValidSchemaKeys(schema);
790
916
  const requiredEntries = [];
791
917
  const optionalEntries = [];
792
918
  const schemaKeys = [];
@@ -801,10 +927,12 @@ function createStruct(schema, options) {
801
927
  requiredEntries.push([key, field]);
802
928
  }
803
929
  const allowed = options?.exact ? new Set(schemaKeys) : null;
930
+ const requiredOnly = optionalEntries.length === 0;
804
931
  return define((input) => {
805
932
  if (!isPlainObject(input)) return false;
806
933
  const obj = input;
807
934
  if (!hasRequiredKeys(obj, requiredEntries)) return false;
935
+ if (allowed && requiredOnly) return hasOnlyRequiredKeys(obj, schemaKeys, allowed);
808
936
  if (!hasValidOptionalKeys(obj, optionalEntries)) return false;
809
937
  if (!allowed) return true;
810
938
  return hasOnlyAllowedKeys(obj, allowed);
@@ -856,6 +984,7 @@ exports.arrayOf = arrayOf;
856
984
  exports.assert = assert;
857
985
  exports.define = define;
858
986
  exports.discriminatedUnion = discriminatedUnion;
987
+ exports.discriminatedUnionWithFallback = discriminatedUnionWithFallback;
859
988
  exports.equals = equals;
860
989
  exports.equalsBy = equalsBy;
861
990
  exports.equalsKey = equalsKey;
package/dist/index.mjs CHANGED
@@ -40,6 +40,7 @@ const getTag = (value) => objectToString.call(value);
40
40
  //#endregion
41
41
  //#region src/core/object.ts
42
42
  const BUILTIN_BRAND_SENTINEL = Object.freeze({});
43
+ const nativeIsError = Error.isError;
43
44
  const getIntrinsicGetter = (prototype, key) => {
44
45
  return Object.getOwnPropertyDescriptor(prototype, key)?.get ?? (() => {
45
46
  throw new TypeError(`Missing intrinsic getter: ${String(key)}`);
@@ -174,11 +175,18 @@ const isDataView = defineIntrinsicBrandGuard((value) => dataViewBuffer.call(valu
174
175
  */
175
176
  const isTypedArray = define((value) => typedArrayName?.call(value) !== void 0);
176
177
  /**
177
- * Checks whether a value is an `Error` (instance of Error or plain Error object tag).
178
+ * Checks whether a value is an `Error`.
178
179
  *
179
180
  * @returns Predicate narrowing to `Error`.
181
+ * @see https://github.com/nyaomaru/is-kit/issues/325
180
182
  */
181
- const isError = define((value) => value instanceof Error || getTag(value) === "[object Error]");
183
+ const isError = define((value) => {
184
+ try {
185
+ return typeof nativeIsError === "function" ? nativeIsError(value) : value instanceof Error || getTag(value) === "[object Error]";
186
+ } catch {
187
+ return false;
188
+ }
189
+ });
182
190
  /**
183
191
  * Checks whether a value is a `URL` (in environments with URL available).
184
192
  *
@@ -528,7 +536,6 @@ const isNotNil = (value) => value !== null && value !== void 0;
528
536
  const isPrimitive = or(isString, isNumberPrimitive, isBoolean, isBigInt, isSymbol, isUndefined, isNull);
529
537
  //#endregion
530
538
  //#region src/utils/guard-collections.ts
531
- const arrayValues = Array.prototype.values;
532
539
  const mapEntries = Map.prototype.entries;
533
540
  const setValues = Set.prototype.values;
534
541
  const everyIterableValue = (values, predicate) => {
@@ -551,9 +558,13 @@ const everyKeyValueEntry = (entries, predicate) => {
551
558
  const everyArrayValue = (values, predicate) => everyIterableValue(values, predicate);
552
559
  /**
553
560
  * Checks built-in Array data without invoking an instance-provided iterator.
554
- * WHY: An Array subclass or instance may override its public iterator and throw.
561
+ * WHY: Indexed reads preserve hole-as-undefined semantics while avoiding iterator
562
+ * allocation on this hot path. They also bypass iterator overrides on subclasses.
555
563
  */
556
- const everyBrandedArrayValue = (values, predicate) => everyIterableValue(arrayValues.call(values), predicate);
564
+ const everyBrandedArrayValue = (values, predicate) => {
565
+ for (let index = 0; index < values.length; index += 1) if (!predicate(values[index])) return false;
566
+ return true;
567
+ };
557
568
  /**
558
569
  * Checks whether a tuple matches the provided element predicates in order.
559
570
  *
@@ -636,8 +647,48 @@ function nonEmptyArrayOf(elementGuard) {
636
647
  }
637
648
  //#endregion
638
649
  //#region src/core/combinators/discriminated-union.ts
650
+ function defineFallbackClassifier(classifier) {
651
+ return classifier;
652
+ }
653
+ function createFallbackVariant(fallbackData, discriminant, tag) {
654
+ const fallbackVariant = {};
655
+ const discriminantKey = isSymbol(discriminant) ? discriminant : String(discriminant);
656
+ for (const key of Reflect.ownKeys(fallbackData)) {
657
+ if (key === discriminantKey) continue;
658
+ const descriptor = Object.getOwnPropertyDescriptor(fallbackData, key);
659
+ if (descriptor !== void 0) Object.defineProperty(fallbackVariant, key, descriptor);
660
+ }
661
+ Object.defineProperty(fallbackVariant, discriminantKey, {
662
+ configurable: true,
663
+ enumerable: true,
664
+ value: tag,
665
+ writable: true
666
+ });
667
+ return fallbackVariant;
668
+ }
639
669
  const isDiscriminantValue = (value) => isString(value) || isNumberPrimitive(value) || isSymbol(value) || isBoolean(value);
670
+ const isFallbackDataDescriptor = (descriptor) => descriptor !== void 0 && "value" in descriptor && !isFunction(descriptor.value);
671
+ const isFallbackPayload = (value) => {
672
+ if (!isPlainObject(value)) return false;
673
+ const prototype = Object.getPrototypeOf(value);
674
+ if (prototype !== null && prototype !== Object.prototype) return false;
675
+ for (const key of Reflect.ownKeys(value)) {
676
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
677
+ if (!isFallbackDataDescriptor(descriptor)) return false;
678
+ }
679
+ return true;
680
+ };
640
681
  const toRuntimeKey = (value) => isSymbol(value) ? value : String(value);
682
+ const assertSafeFallbackTag = (values, tag) => {
683
+ if (!isDiscriminantValue(tag)) throw new TypeError("discriminatedUnion fallback tag must be a string, number, symbol, or boolean.");
684
+ const fallbackKey = toRuntimeKey(tag);
685
+ if (values.some((value) => toRuntimeKey(value) === fallbackKey)) throw new TypeError(`Fallback discriminatedUnion tag collides with a branch value: ${String(tag)}.`);
686
+ };
687
+ const getOwnDiscriminantValue = (input, discriminant) => {
688
+ if (!isObject(input) && !isFunction(input) || !hasOwnPropertyKey(input, discriminant)) return;
689
+ const value = Reflect.get(input, discriminant);
690
+ return isDiscriminantValue(value) ? value : void 0;
691
+ };
641
692
  const assertSafeProtoBranch = (values, guards) => {
642
693
  if (!values.includes("__proto__")) return;
643
694
  if (hasOwnPropertyKey(guards, "__proto__")) return;
@@ -670,9 +721,8 @@ function discriminatedUnion() {
670
721
  assertSafeProtoBranch(values, guards);
671
722
  const declaredKeys = assertBranchKeys(values, guards);
672
723
  return define((input) => {
673
- if (!isObject(input) && !isFunction(input) || !hasOwnPropertyKey(input, discriminant)) return false;
674
- const value = Reflect.get(input, discriminant);
675
- if (!isDiscriminantValue(value)) return false;
724
+ const value = getOwnDiscriminantValue(input, discriminant);
725
+ if (value === void 0) return false;
676
726
  const key = toRuntimeKey(value);
677
727
  if (!declaredKeys.has(key) || !hasOwnPropertyKey(guards, key)) return false;
678
728
  const guard = guards[key];
@@ -680,6 +730,44 @@ function discriminatedUnion() {
680
730
  });
681
731
  };
682
732
  }
733
+ /**
734
+ * Classifies a finite discriminated union and explicitly transforms undeclared values into one fallback variant.
735
+ * Known values remain exhaustive: a malformed known member fails instead of reaching the fallback.
736
+ * @param discriminant Required property that identifies each known union member.
737
+ * @param values Finite tuple containing every known discriminant value.
738
+ * @param guards Branch guards keyed by the known discriminant values.
739
+ * @param fallback Canonical fallback tag and receiver-free factory for an own non-function data-field payload; return `undefined` to reject the input.
740
+ * @returns Decoder that returns a guarded known member or fallback variant when valid.
741
+ */
742
+ function discriminatedUnionWithFallback() {
743
+ return (discriminant, values, guards, fallback) => {
744
+ assertSafeProtoBranch(values, guards);
745
+ const fallbackTag = fallback.tag;
746
+ const createFallback = fallback.create;
747
+ assertSafeFallbackTag(values, fallbackTag);
748
+ assertBranchKeys(values, guards);
749
+ const declaredValues = new Set(values);
750
+ return defineFallbackClassifier((input) => {
751
+ const value = getOwnDiscriminantValue(input, discriminant);
752
+ if (value === void 0) return { valid: false };
753
+ if (!declaredValues.has(value)) {
754
+ const fallbackData = createFallback(input, value);
755
+ if (fallbackData === void 0 || !isFallbackPayload(fallbackData)) return { valid: false };
756
+ return {
757
+ valid: true,
758
+ value: createFallbackVariant(fallbackData, discriminant, fallbackTag)
759
+ };
760
+ }
761
+ const key = toRuntimeKey(value);
762
+ if (!hasOwnPropertyKey(guards, key)) return { valid: false };
763
+ const guard = guards[key];
764
+ return guard(input) ? {
765
+ valid: true,
766
+ value: input
767
+ } : { valid: false };
768
+ });
769
+ };
770
+ }
683
771
  //#endregion
684
772
  //#region src/core/combinators/map.ts
685
773
  /**
@@ -729,7 +817,10 @@ function oneOfValues(...args) {
729
817
  /**
730
818
  * Validates a record-like object by guarding both keys and values.
731
819
  *
732
- * @param keyFunction Guard for string keys (e.g., specific literal keys pattern).
820
+ * The key guard restricts which string keys may be present; it does not require
821
+ * every key represented by the guarded key type.
822
+ *
823
+ * @param keyFunction Guard for string keys (for example, a literal-key pattern).
733
824
  * @param valueFunction Guard applied to each value in the record.
734
825
  * @returns Predicate narrowing to a readonly record with guarded key/value types.
735
826
  */
@@ -749,10 +840,44 @@ function setOf(valueGuard) {
749
840
  }
750
841
  //#endregion
751
842
  //#region src/core/combinators/struct.ts
843
+ const OBJECT_CONSTRUCTOR_SOURCE = Function.prototype.toString.call(Object);
844
+ const isObjectPrototype = (prototype) => {
845
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
846
+ return typeof constructor === "function" && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === OBJECT_CONSTRUCTOR_SOURCE;
847
+ };
848
+ const hasOnlyEnumerableOwnStringKeys = (schema) => Object.getOwnPropertyNames(schema).every((key) => Object.prototype.propertyIsEnumerable.call(schema, key));
849
+ const hasInheritedStringKeys = (schema) => {
850
+ let prototype = Object.getPrototypeOf(schema);
851
+ while (prototype !== null && !isObjectPrototype(prototype)) {
852
+ if (Object.getOwnPropertyNames(prototype).some((key) => {
853
+ if (key !== "constructor") return true;
854
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, key);
855
+ return !(typeof descriptor?.value === "function" && descriptor.value.prototype === prototype);
856
+ })) return true;
857
+ prototype = Object.getPrototypeOf(prototype);
858
+ }
859
+ return false;
860
+ };
861
+ const hasInheritedSymbolKeys = (schema) => {
862
+ let prototype = Object.getPrototypeOf(schema);
863
+ while (prototype !== null && !isObjectPrototype(prototype)) {
864
+ if (Object.getOwnPropertySymbols(prototype).length > 0) return true;
865
+ prototype = Object.getPrototypeOf(prototype);
866
+ }
867
+ return false;
868
+ };
869
+ const assertValidSchemaKeys = (schema) => {
870
+ if (Object.getOwnPropertySymbols(schema).length > 0 || hasInheritedSymbolKeys(schema)) throw new TypeError("struct schema fields cannot use symbol keys");
871
+ if (!hasOnlyEnumerableOwnStringKeys(schema) || hasInheritedStringKeys(schema)) throw new TypeError("struct schema fields must be own enumerable string keys");
872
+ };
752
873
  const isOptionalSchemaField = define((field) => isObject(field) && field.optional === true && isFunction(field.guard));
753
874
  const hasRequiredKeys = (obj, entries) => entries.every(([key, guard]) => hasOwnPropertyKey(obj, key) && guard(obj[key]));
754
875
  const hasValidOptionalKeys = (obj, entries) => entries.every(([key, guard]) => !hasOwnPropertyKey(obj, key) || guard(obj[key]));
755
876
  const hasOnlyAllowedKeys = (obj, allowed) => Object.keys(obj).every((key) => allowed.has(key));
877
+ const hasOnlyRequiredKeys = (obj, schemaKeys, allowed) => {
878
+ const keys = Object.keys(obj);
879
+ return keys.length <= schemaKeys.length && keys.every((key, index) => key === schemaKeys[index] || allowed.has(key));
880
+ };
756
881
  /**
757
882
  * Marks a struct schema field as optional at the key level.
758
883
  *
@@ -769,23 +894,24 @@ function optionalKey(guard) {
769
894
  };
770
895
  }
771
896
  /**
772
- * Validates an object against a field-to-guard schema with string runtime keys.
773
- * Numeric schema keys are normalized to strings by JavaScript; symbol-keyed fields
774
- * are not supported. Keys are required unless wrapped with `optionalKey`; optionally
775
- * rejects extra keys when `exact: true`.
897
+ * Validates an object against a field-to-guard schema with own enumerable string
898
+ * keys. Numeric schema keys are normalized to strings by JavaScript; symbol,
899
+ * non-enumerable, and inherited fields are not supported. Keys are required unless
900
+ * wrapped with `optionalKey`; optionally rejects extra keys when `exact: true`.
776
901
  *
777
902
  * @param schema Record of string- or numeric-keyed property guards.
778
903
  * @param options When `{ exact: true }`, disallows own enumerable string-key
779
904
  * properties not in `schema`.
780
905
  * @returns Predicate that narrows to the inferred struct type.
781
- * @throws {TypeError} If `schema` has own symbol-keyed fields.
906
+ * @throws {TypeError} If `schema` has symbol-keyed, non-enumerable, or inherited
907
+ * string-keyed fields.
782
908
  */
783
909
  function struct(schema, options) {
784
910
  return createStruct(schema, options);
785
911
  }
786
912
  /** @internal Shared implementation for string-keyed schema builders. */
787
913
  function createStruct(schema, options) {
788
- if (Object.getOwnPropertySymbols(schema).length > 0) throw new TypeError("struct schema fields cannot use symbol keys");
914
+ assertValidSchemaKeys(schema);
789
915
  const requiredEntries = [];
790
916
  const optionalEntries = [];
791
917
  const schemaKeys = [];
@@ -800,10 +926,12 @@ function createStruct(schema, options) {
800
926
  requiredEntries.push([key, field]);
801
927
  }
802
928
  const allowed = options?.exact ? new Set(schemaKeys) : null;
929
+ const requiredOnly = optionalEntries.length === 0;
803
930
  return define((input) => {
804
931
  if (!isPlainObject(input)) return false;
805
932
  const obj = input;
806
933
  if (!hasRequiredKeys(obj, requiredEntries)) return false;
934
+ if (allowed && requiredOnly) return hasOnlyRequiredKeys(obj, schemaKeys, allowed);
807
935
  if (!hasValidOptionalKeys(obj, optionalEntries)) return false;
808
936
  if (!allowed) return true;
809
937
  return hasOnlyAllowedKeys(obj, allowed);
@@ -849,4 +977,4 @@ function tupleOf(...guards) {
849
977
  */
850
978
  const toBooleanPredicates = (predicates) => predicates;
851
979
  //#endregion
852
- export { and, andAll, arrayOf, assert, define, discriminatedUnion, equals, equalsBy, equalsKey, everyArrayValue, everyMapEntry, everyOwnEnumerableEntry, everySetValue, everyTupleValue, guardIn, hasKey, hasKeys, isArray, isArrayBuffer, isAsyncIterable, isBigInt, isBlob, isBoolean, isDataView, isDate, isError, isFile, isFiniteNumber, isFunction, isInfiniteNumber, isInstanceOf, isInteger, isIterable, isMap, isNaN, isNegative, isNil, isNotNil, isNull, isNumber, isNumberPrimitive, isObject, isPlainObject, isPositive, isPrimitive, isPromiseLike, isRegExp, isSafeInteger, isSet, isString, isSymbol, isTypedArray, isURL, isUndefined, isWeakMap, isWeakSet, isZero, lazy, mapOf, narrowKeyTo, nonEmptyArrayOf, nonNull, not, nullable, nullish, oneOf, oneOfValues, optional, optionalKey, or, predicateToRefine, recordOf, refineDefinedKey, refineIndex, refineKey, required, safeJsonParse, safeParse, safeParseWith, setOf, struct, toBooleanPredicates, tupleOf, typedStruct };
980
+ export { and, andAll, arrayOf, assert, define, discriminatedUnion, discriminatedUnionWithFallback, equals, equalsBy, equalsKey, everyArrayValue, everyMapEntry, everyOwnEnumerableEntry, everySetValue, everyTupleValue, guardIn, hasKey, hasKeys, isArray, isArrayBuffer, isAsyncIterable, isBigInt, isBlob, isBoolean, isDataView, isDate, isError, isFile, isFiniteNumber, isFunction, isInfiniteNumber, isInstanceOf, isInteger, isIterable, isMap, isNaN, isNegative, isNil, isNotNil, isNull, isNumber, isNumberPrimitive, isObject, isPlainObject, isPositive, isPrimitive, isPromiseLike, isRegExp, isSafeInteger, isSet, isString, isSymbol, isTypedArray, isURL, isUndefined, isWeakMap, isWeakSet, isZero, lazy, mapOf, narrowKeyTo, nonEmptyArrayOf, nonNull, not, nullable, nullish, oneOf, oneOfValues, optional, optionalKey, or, predicateToRefine, recordOf, refineDefinedKey, refineIndex, refineKey, required, safeJsonParse, safeParse, safeParseWith, setOf, struct, toBooleanPredicates, tupleOf, typedStruct };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "is-kit",
3
- "version": "1.15.2",
3
+ "version": "1.16.0",
4
4
  "description": "Zero-dependency TypeScript runtime validation toolkit for composable type guards and natural type narrowing.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -22,6 +22,7 @@
22
22
  "test:package": "node tests/package-smoke.mjs",
23
23
  "test:package:vlt": "node tests/vlt-package-smoke.mjs",
24
24
  "bench:core": "node bench/core-workloads.mjs",
25
+ "bench:array-traversal": "node bench/array-traversal.mjs",
25
26
  "lint": "oxlint .",
26
27
  "format": "oxfmt .",
27
28
  "format:check": "oxfmt --check .",
@@ -59,6 +60,9 @@
59
60
  "homepage": "https://is-kit.dev/",
60
61
  "author": "nyaomaru",
61
62
  "license": "MIT",
63
+ "engines": {
64
+ "node": ">=22"
65
+ },
62
66
  "packageManager": "pnpm@11.2.2",
63
67
  "devDependencies": {
64
68
  "@types/jest": "^30.0.0",