@atscript/typescript 0.2.8 → 0.2.10

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/utils.d.ts CHANGED
@@ -322,7 +322,10 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
322
322
  private builtin;
323
323
  /** {@link fail} of a type mismatch of `def`: its `@expect.message` replaces the message. */
324
324
  private mismatch;
325
- /** The `@meta.required` error of `def` (custom message or the type's default). */
325
+ /**
326
+ * The `@meta.required` error of `def`: its message, else its `@expect.message`, else the code's
327
+ * default.
328
+ */
326
329
  private required;
327
330
  /**
328
331
  * Adds `error`, already made, to the errors of the current level (as {@link error} does);
@@ -351,6 +354,12 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
351
354
  private get shortcuts();
352
355
  /** Validates `value` against `def` (after `replace`, `optional` and the plugins). */
353
356
  protected validateSafe(def: TAtscriptAnnotatedType, value: any): boolean;
357
+ /**
358
+ * A missing value (`undefined`, or `null`) of a `@meta.required` `def`: when `def` rejects it,
359
+ * the `@meta.required` error replaces the type error the walk reports (the same verdict). A
360
+ * bare `@meta.required` keeps the `@expect.message` text the type error had.
361
+ */
362
+ private missing;
354
363
  /**
355
364
  * What {@link validateSafe} decides of `def` (replaced) before its own validation: an
356
365
  * optional `def` passes `undefined` / `null`, a plugin may decide — `undefined` to go on.
@@ -671,12 +680,18 @@ declare function isAnnotatedTypeOfPrimitive(t: TAtscriptAnnotatedType): boolean;
671
680
  * backtracking). A scalar branch takes what it parses; an object (tuple)
672
681
  * branch takes a plain object (an array of its length) unless a literal
673
682
  * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
674
- * does not coerce to it, a string compared after the normalizers of the
675
- * literal and of the unions it is in. An object takes the branch its
676
- * discriminator names (as the validator does: the literal itself first, else
677
- * `"2"` names a `2` literal), else the first whose shape it has (required
678
- * props present, no undeclared key), else the first that takes it. When no
679
- * branch takes the value, it is returned untouched.
683
+ * does not coerce to it (`"2"` coerces to a `2` literal), a string compared
684
+ * after the normalizers of the literal and of the unions it is in. A scalar
685
+ * takes the first branch that takes it. An object or array takes the only
686
+ * branch that takes it, else the one it fits best, judged in this order
687
+ * (never looking deeper than its own keys and items): its props (items) hold
688
+ * values of their kinds (a string that parses for a `number` prop, `null`
689
+ * where `null` is allowed); it has no undeclared key; it has every required
690
+ * prop (the last two can be waived by `partial` / `unknownProps`, a wrong
691
+ * kind cannot); a nested union's branches count as the union's own. Ties go
692
+ * to the branch an object's discriminator names by the literal itself, then
693
+ * to declared order. When no branch takes the value, it is returned
694
+ * untouched.
680
695
  * - Objects recurse into props when the input is a plain object (covers
681
696
  * `@Query()` DTOs where every field arrives as a string), whatever their
682
697
  * literal props hold unless tried as a union branch.
@@ -741,6 +756,56 @@ declare function normalizeForType<T = unknown>(def: TAtscriptAnnotatedType, valu
741
756
  */
742
757
  declare function typeHasNormalizers(def: TAtscriptAnnotatedType): boolean;
743
758
 
759
+ /**
760
+ * What a strict tool / structured-output schema of an LLM provider accepts (the `strict` option
761
+ * of {@link buildJsonSchema}): the schema is built closed (`additionalProperties: false` on every
762
+ * object), then rewritten to the profile. Constraints the profile drops are not enforced by the
763
+ * provider: validate the model's output with the atscript validator.
764
+ */
765
+ interface TStrictProfile {
766
+ /** The provider's name, in the errors of a shape it can't take. */
767
+ name: string;
768
+ /**
769
+ * The keywords the provider accepts (an allow-list): `true`, or a check of the keyword's value
770
+ * (`false`: the keyword is dropped there). Every other keyword is dropped.
771
+ */
772
+ keywords: Readonly<Record<string, true | ((value: unknown) => boolean)>>;
773
+ /**
774
+ * Every property in `required`, the optional ones nullable: the model sends `null` for an
775
+ * optional field it leaves out. The validator rejects `null` on an optional `@meta.required`
776
+ * field: drop those values first (see `dropOptionalNulls`).
777
+ */
778
+ requireAll: boolean;
779
+ /**
780
+ * Rewrites the `allOf` the schema builder writes: a `$ref` with notes beside it (a field's
781
+ * title, description, key counts) → the referenced schema inlined with them; several patterns
782
+ * → the first one (the rest dropped) when `allOf` itself is not allowed. Any other `allOf`
783
+ * the profile does not allow throws.
784
+ */
785
+ collapseAllOf: boolean;
786
+ /** Appends each dropped constraint to the schema's `description`, in plain words. */
787
+ describeDropped: boolean;
788
+ /** Recursive types (a `$defs` entry that refers to itself); `false`: throws. */
789
+ allowRecursion: boolean;
790
+ /** The root must be an object schema; else throws. */
791
+ objectRoot: boolean;
792
+ }
793
+ /**
794
+ * OpenAI Structured Outputs / `strict: true` function calling: every property required
795
+ * (optional ones nullable), objects closed, an object root, no `allOf`; patterns without
796
+ * lookaround, backreferences or modifier groups, numeric bounds and `minItems` / `maxItems`
797
+ * kept; string lengths, `uniqueItems` and key counts dropped. Recursion is allowed.
798
+ */
799
+ declare const OPENAI_STRICT: TStrictProfile;
800
+ /**
801
+ * Anthropic strict tool use / structured outputs: objects closed, an object root (a tool's
802
+ * `input_schema`), no recursion; simple patterns kept (no lookaround, backreferences, word
803
+ * boundaries or large `{n,m}`), `minItems` only `0` / `1`; numeric bounds, string lengths,
804
+ * `maxItems`, `uniqueItems` and key counts dropped. `allOf` is allowed
805
+ * except with a `$ref` (collapsed). Optional properties stay optional.
806
+ */
807
+ declare const ANTHROPIC_STRICT: TStrictProfile;
808
+
744
809
  /** A JSON Schema object (draft-compatible). */
745
810
  type TJsonSchema = Record<string, any>;
746
811
  /** Options of {@link buildJsonSchema} (and of the `jsonSchemaOptions` plugin option). */
@@ -761,6 +826,14 @@ interface TJsonSchemaOptions {
761
826
  * `anyOf` of `const` schemas. *(default: `true`)*
762
827
  */
763
828
  enums?: boolean;
829
+ /**
830
+ * Targets a strict LLM tool / structured-output schema: `OPENAI_STRICT`, `ANTHROPIC_STRICT` or
831
+ * a profile of your own (see {@link TStrictProfile}). The schema is built `closed`, then keeps
832
+ * only the keywords the profile allows (the dropped constraints described in `description`);
833
+ * a shape the profile can't take throws. The provider does not enforce what was dropped:
834
+ * validate the model's output with the type's validator. Runtime only (not a plugin option).
835
+ */
836
+ strict?: TStrictProfile;
764
837
  }
765
838
  /**
766
839
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
@@ -821,6 +894,22 @@ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[], opts?: TJsonS
821
894
  $defs: Record<string, TJsonSchema>;
822
895
  };
823
896
 
897
+ /**
898
+ * What `value` looks like without the `null` values the model sends for fields it leaves out under
899
+ * a `requireAll` profile (`OPENAI_STRICT`), before it goes to the validator. The validator
900
+ * takes a missing optional field, but not `null` on an optional `@meta.required` one.
901
+ *
902
+ * A `null` is dropped only from an optional field whose type does not accept `null`: for
903
+ * `x?: string | null` it stays (`null` and a missing field mean different things, e.g. "clear"
904
+ * and "keep" in a patch). In a union, the branch its discriminator picks applies; else every
905
+ * branch does, and a key is dropped only when every branch (and, in an intersection, every part)
906
+ * that declares it has it optional and not accepting `null`: one that needs the `null` keeps it.
907
+ *
908
+ * Copy-on-change: `value` is never mutated (a frozen one works); the same reference comes back
909
+ * when nothing is dropped, else a copy with the changed objects and arrays rebuilt.
910
+ */
911
+ declare function dropOptionalNulls<T>(type: TAtscriptAnnotatedType, value: T): T;
912
+
824
913
  /**
825
914
  * Describes a discriminator property shared by all variants of a union.
826
915
  *
@@ -1322,6 +1411,24 @@ declare function translateServed<T>(json: T, t: (text: string) => string | undef
1322
1411
  value: T;
1323
1412
  texts: Record<string, string>;
1324
1413
  };
1414
+ /**
1415
+ * Translates the value of one metadata key (live, as a compiled type holds it — not serialized)
1416
+ * with `t`, by the rules {@link translateServed} applies to serialized metadata, so a client
1417
+ * translating compiled types reads one catalogue with the server: a text key's string (each item
1418
+ * of a `multiple` list; the named fields of a value object, e.g. `message` of `meta.required`) is
1419
+ * replaced by `t(text)` — except a primitive's built-in format message, which is reported by its
1420
+ * code. Returns `value` itself when the key holds no user text or nothing is translated; it is
1421
+ * never changed.
1422
+ *
1423
+ * Expressions are left as they are: their string literals are translated in a served type's
1424
+ * `texts`, and a client translates what an expression returns (by exact match), not its source.
1425
+ *
1426
+ * @example
1427
+ * ```ts
1428
+ * const label = translateUserText('meta.label', 'Street', text => dict[text]) // dict['Street']
1429
+ * ```
1430
+ */
1431
+ declare function translateUserText(key: string, value: unknown, t: (text: string) => string | undefined): unknown;
1325
1432
 
1326
1433
  /**
1327
1434
  * Metadata layers: the runtime's one metadata mechanism.
@@ -1545,5 +1652,5 @@ type NavPropsOf<T> = T extends {
1545
1652
  __navProps: infer N extends Record<string, unknown>;
1546
1653
  } ? N : Record<string, never>;
1547
1654
 
1548
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, LayerMap, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
1549
- export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TError, TErrorInfo, TFlattenOptions, TJsonSchema, TJsonSchemaOptions, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TUserTextFields, TValidatorDiscriminator, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, TValueResolver };
1655
+ export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, ANTHROPIC_STRICT, LayerMap, OPENAI_STRICT, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, dropOptionalNulls, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, translateUserText, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
1656
+ export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TError, TErrorInfo, TFlattenOptions, TJsonSchema, TJsonSchemaOptions, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TStrictProfile, TUnionDiscriminator, TUserTextFields, TValidatorDiscriminator, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, TValueResolver };