@astrale-os/kernel-dsl 1.0.0-beta.21 → 1.0.0-beta.23

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.
Files changed (35) hide show
  1. package/dist/v1/builder/index.d.ts +2 -0
  2. package/dist/v1/builder/index.js +1 -0
  3. package/dist/v1/builder/lowering/value/compile.js +5 -1
  4. package/dist/v1/builder/lowering/value/file.d.ts +7 -0
  5. package/dist/v1/builder/lowering/value/file.js +14 -0
  6. package/dist/v1/builder/lowering/value/zod.js +30 -0
  7. package/dist/v1/builder/schema/diagnostic.d.ts +1 -1
  8. package/dist/v1/builder/value/file.d.ts +34 -0
  9. package/dist/v1/builder/value/file.js +77 -0
  10. package/dist/v1/index.d.ts +2 -2
  11. package/dist/v1/index.js +1 -1
  12. package/dist/v1/language/.spec/schemas/value-schema.schema.json +2 -1
  13. package/dist/v1/language/validation/rule.js +2 -2
  14. package/dist/v1/language/value/files.d.ts +44 -0
  15. package/dist/v1/language/value/files.js +150 -0
  16. package/dist/v1/language/value/inclusion/evidence.js +2 -0
  17. package/dist/v1/language/value/inclusion/types.js +23 -0
  18. package/dist/v1/language/value/model/file.d.ts +41 -0
  19. package/dist/v1/language/value/model/file.js +122 -0
  20. package/dist/v1/language/value/profile/meta-schema.compiled.d.ts +1 -0
  21. package/dist/v1/language/value/profile/meta-schema.compiled.js +18 -5
  22. package/dist/v1/language/value/profile/rules.js +10 -1
  23. package/dist/v1/language/value/profile/vocabulary.d.ts +7 -6
  24. package/dist/v1/language/value/profile/vocabulary.js +7 -1
  25. package/dist/v1/language/value/regexp/unicode.d.ts +1 -1
  26. package/dist/v1/language/value/regexp/unicode.js +1 -1
  27. package/dist/v1/schema/.spec/schemas/domain-schema.schema.json +48 -7
  28. package/dist/v1/schema/validation/domain.json-schema.js +27 -2
  29. package/dist/v1/schema/validation/domain.structure.d.ts +49 -46
  30. package/dist/v1/schema/validation/domain.structure.js +140 -50
  31. package/dist/v1/schema/validation/value-api.d.ts +4 -0
  32. package/dist/v1/schema/validation/value-api.js +2 -0
  33. package/dist/v1/schema/validation/value.json-schema.d.ts +5 -0
  34. package/dist/v1/schema/validation/value.json-schema.js +30 -4
  35. package/package.json +3 -3
@@ -2,6 +2,7 @@ export { func, input, method, output } from './callable/authoring.js';
2
2
  export { core } from './core/authoring.js';
3
3
  export { defineClass, edgeClass, nodeClass } from './class/authoring.js';
4
4
  export { fullMatch } from './value/full-match.js';
5
+ export { file } from './value/file.js';
5
6
  export { path } from './value/path.js';
6
7
  export { policy } from './policy/authoring.js';
7
8
  export { auto, property, stateProperty } from './class/property.js';
@@ -18,6 +19,7 @@ export type { Class, DirectedEdgeClass, EdgeClass, NodeClass, UndirectedEdgeClas
18
19
  export type { ClassReferenceInput as ClassReference, ClassRuleBuilder, ClassRuleContext, CreateRuleBuilder, CreateRuleContext, DirectedEdgeInput, DirectedSourceInput, DirectedTargetInput, EdgeClassCommon, EdgeClassInput, EdgeClassPoliciesInput, EdgeClassPolicyInput, EdgeClassReferenceInput as EdgeClassReference, EdgeRuleBuilder, EdgeRuleContext, EdgeUniqueFieldInput, EdgeUniqueTupleInput, IncidentEndpointInput, NodeClassCreatePolicyInput, NodeClassInput, NodeClassPoliciesInput, NodeClassPolicyInput, NodeClassReferenceInput as NodeClassReference, NodeUniqueTupleInput, UndirectedEdgeInput, } from './class/input.js';
19
20
  export type { ClassRuleChecks, CreateRuleChecks, EdgeRuleChecks, } from '../language/policy/model/policy.js';
20
21
  export type { AuthoredPropertyProjection, AuthoredMethodProjection, ClassIdentityProjection, ClassOwnerProjection, ClassReferenceProjection, } from './class/projection.js';
22
+ export type { FileAuthoring, FileSource } from './value/file.js';
21
23
  export type { PathAuthoring } from './value/path.js';
22
24
  export type { Lazy } from './schema/lazy.js';
23
25
  export type { EdgeRolesOf, MatchPolicyInput, Policy, PolicyBuilder as PolicyFactory, PolicyEdgeClassInput, PolicyEdgeEnds, PolicyEdgeOptions, PolicyEdgeRepeat, PolicyExistsContext, PolicyInput, PolicyNodeBinder, PolicyPatternContext, } from './policy/authoring.js';
@@ -2,6 +2,7 @@ export { func, input, method, output } from './callable/authoring.js';
2
2
  export { core } from './core/authoring.js';
3
3
  export { defineClass, edgeClass, nodeClass } from './class/authoring.js';
4
4
  export { fullMatch } from './value/full-match.js';
5
+ export { file } from './value/file.js';
5
6
  export { path } from './value/path.js';
6
7
  export { policy } from './policy/authoring.js';
7
8
  export { auto, property, stateProperty } from './class/property.js';
@@ -7,6 +7,7 @@ import { autoPropertyAuthoringInput, propertyAuthoringInput } from '../../class/
7
7
  import { BuilderError } from '../../schema/diagnostic.js';
8
8
  import { escapeToken, fail } from '../../schema/diagnostic.js';
9
9
  import { isAuthoringValue } from '../../schema/handle.js';
10
+ import { lowerFileSchema } from './file.js';
10
11
  import { lowerPathSchema } from './path.js';
11
12
  import { convertZodToValueSchema, zodObjectPropertyIsOptional } from './zod.js';
12
13
  export class BuilderValueSchemas {
@@ -61,7 +62,10 @@ export class BuilderValueSchemas {
61
62
  const converted = convertZodToValueSchema(input, conversionContext, this.registry, pointer, {
62
63
  position: zodPosition,
63
64
  validate: false,
64
- override: (context) => lowerPathSchema(context, (accepts, markerPointer) => this.resolvePathAccepts(accepts, markerPointer), pointer),
65
+ override: (context) => {
66
+ lowerFileSchema(context);
67
+ lowerPathSchema(context, (accepts, markerPointer) => this.resolvePathAccepts(accepts, markerPointer), pointer);
68
+ },
65
69
  });
66
70
  if (!converted.ok)
67
71
  throw new BuilderError(converted.diagnostics);
@@ -0,0 +1,7 @@
1
+ import type { ZodValueSchemaOverrideContext } from './zod.js';
2
+ /**
3
+ * Lower an authored `file(...)` field to its `schema.values.file` shape. Every other keyword the
4
+ * Zod schema wrote stays: an annotation is kept, and a constraint makes the field non-canonical,
5
+ * which admission refuses.
6
+ */
7
+ export declare function lowerFileSchema(context: ZodValueSchemaOverrideContext): void;
@@ -0,0 +1,14 @@
1
+ import { file } from '../../../language/value/model/file.js';
2
+ import { fileOptionsOfAuthoring } from '../../value/file.js';
3
+ /**
4
+ * Lower an authored `file(...)` field to its `schema.values.file` shape. Every other keyword the
5
+ * Zod schema wrote stays: an annotation is kept, and a constraint makes the field non-canonical,
6
+ * which admission refuses.
7
+ */
8
+ export function lowerFileSchema(context) {
9
+ const options = fileOptionsOfAuthoring(context.zodSchema);
10
+ if (options === undefined)
11
+ return;
12
+ delete context.jsonSchema.type;
13
+ Object.assign(context.jsonSchema, file(options));
14
+ }
@@ -35,6 +35,7 @@ export function convertZodToValueSchema(zodSchema, context, registry, pointer =
35
35
  path,
36
36
  zodSchema: source,
37
37
  });
38
+ keepLoweredShape(source, jsonSchema);
38
39
  }
39
40
  },
40
41
  });
@@ -62,6 +63,28 @@ export function convertZodToValueSchema(zodSchema, context, registry, pointer =
62
63
  diagnostics: [],
63
64
  };
64
65
  }
66
+ /**
67
+ * The lowering keeps one spelling per contract, whatever Zod version renders it, so that a Domain
68
+ * built from unchanged source keeps its schema digest. Every node lowers as its own Zod schema: a
69
+ * union by `anyOf`, an intersection by `allOf`, a tuple by its `prefixItems` and rest alone. Zod
70
+ * 4.6 compacts bare-type unions into a `type` array, folds object intersections, and closes tuples;
71
+ * the marker leaves no node bare, so the first two do not apply, and the tuple bounds are removed.
72
+ * `copyZodJson` drops the marker.
73
+ */
74
+ function keepLoweredShape(schema, jsonSchema) {
75
+ const def = getSchemaDefinition(schema);
76
+ if (def?.type === 'tuple' && Array.isArray(def.items)) {
77
+ if (jsonSchema.items === false)
78
+ delete jsonSchema.items;
79
+ if (jsonSchema.maxItems === def.items.length)
80
+ delete jsonSchema.maxItems;
81
+ if (typeof jsonSchema.minItems === 'number' && jsonSchema.minItems <= def.items.length) {
82
+ delete jsonSchema.minItems;
83
+ }
84
+ }
85
+ jsonSchema[LOWERED_NODE] = true;
86
+ }
87
+ const LOWERED_NODE = '~astrale-lowered-node';
65
88
  function copyZodJson(value) {
66
89
  if (value === null || ['boolean', 'number', 'string'].includes(typeof value))
67
90
  return value;
@@ -74,6 +97,8 @@ function copyZodJson(value) {
74
97
  for (const key of Reflect.ownKeys(value)) {
75
98
  if (typeof key === 'symbol')
76
99
  throw new TypeError('Zod emitted symbol-keyed schema metadata.');
100
+ if (key === LOWERED_NODE)
101
+ continue;
77
102
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
78
103
  if (descriptor === undefined)
79
104
  continue;
@@ -117,6 +142,11 @@ function inspectZodSchema(root, pointer, position) {
117
142
  if (def.coerce === true) {
118
143
  diagnostics.push(diagnostic('ZOD_SCHEMA_NOT_LOSSLESS', schemaPointer, 'Zod coercion changes the accepted input domain and is not serializable as JSON Schema.'));
119
144
  }
145
+ if (type === 'record' && isZodType(def.keyType)) {
146
+ if (getSchemaDefinition(def.keyType)?.type === 'number') {
147
+ diagnostics.push(diagnostic('ZOD_SCHEMA_NOT_LOSSLESS', `${schemaPointer}/propertyNames`, 'Zod number record keys accept the member names that spell a number, which V1 states by no portable pattern.'));
148
+ }
149
+ }
120
150
  inspectCheck(def, schemaPointer, diagnostics);
121
151
  if (Array.isArray(def.checks)) {
122
152
  def.checks.forEach((check, index) => {
@@ -1,7 +1,7 @@
1
1
  import type { DiagnosticCode as LanguageDiagnosticCode } from '../../language/validation/diagnostic.js';
2
2
  import { escapePointerToken as escapeToken } from '../../language/value/syntax/pointer.js';
3
3
  export { escapeToken };
4
- export type BuilderDiagnosticCode = LanguageDiagnosticCode | 'BUILDER_ABSTRACT_POLICY' | 'BUILDER_AMBIGUOUS_OWNERSHIP' | 'BUILDER_AUTO_EVENT_INVALID' | 'BUILDER_AUTO_IMMUTABLE' | 'BUILDER_AUTO_NESTED' | 'BUILDER_AUTO_SET_INVALID' | 'BUILDER_CALLABLE_AUTH' | 'BUILDER_CALLABLE_PLACEMENT' | 'BUILDER_CALLABLE_POLICY_AUTH' | 'BUILDER_CLASS_INHERITANCE' | 'BUILDER_CORE_CLASS' | 'BUILDER_CORE_EDGE' | 'BUILDER_CORE_NODE' | 'BUILDER_CORE_PROPERTY' | 'BUILDER_CORE_REF' | 'BUILDER_DEFINITION' | 'BUILDER_DEPENDENCY_CONFLICT' | 'BUILDER_DEPENDENCY_ALIAS' | 'BUILDER_DEPENDENCY_DIRECT' | 'BUILDER_DUPLICATE_MEMBER' | 'BUILDER_EDGE_LIFETIME' | 'BUILDER_FOREIGN_POLICY' | 'BUILDER_FULL_MATCH_INVALID' | 'BUILDER_FUNCTION' | 'BUILDER_METHOD' | 'BUILDER_PATH_DUPLICATE' | 'BUILDER_PATH_EMPTY' | 'BUILDER_POLICY' | 'BUILDER_POLICY_COMPOSITION' | 'BUILDER_POLICY_CYCLE' | 'BUILDER_POLICY_EMPTY_COMPOSITION' | 'BUILDER_POLICY_EMPTY_EXISTS' | 'BUILDER_POLICY_INPUT' | 'BUILDER_POLICY_REF' | 'BUILDER_POLICY_SELF' | 'BUILDER_PROPERTY_IMMUTABLE_INVALID' | 'BUILDER_REFERENCE_CYCLE' | 'BUILDER_REFERENCE_KIND' | 'BUILDER_REFERENCE_MISSING' | 'BUILDER_UNIQUE_PROPERTY' | 'BUILDER_UNKNOWN_FIELD' | 'BUILDER_UNOWNED_REFERENCE' | 'BUILDER_VIEW' | 'ZOD_SCHEMA_NOT_LOSSLESS';
4
+ export type BuilderDiagnosticCode = LanguageDiagnosticCode | 'BUILDER_ABSTRACT_POLICY' | 'BUILDER_AMBIGUOUS_OWNERSHIP' | 'BUILDER_AUTO_EVENT_INVALID' | 'BUILDER_AUTO_IMMUTABLE' | 'BUILDER_AUTO_NESTED' | 'BUILDER_AUTO_SET_INVALID' | 'BUILDER_CALLABLE_AUTH' | 'BUILDER_CALLABLE_PLACEMENT' | 'BUILDER_CALLABLE_POLICY_AUTH' | 'BUILDER_CLASS_INHERITANCE' | 'BUILDER_CORE_CLASS' | 'BUILDER_CORE_EDGE' | 'BUILDER_CORE_NODE' | 'BUILDER_CORE_PROPERTY' | 'BUILDER_CORE_REF' | 'BUILDER_DEFINITION' | 'BUILDER_DEPENDENCY_CONFLICT' | 'BUILDER_DEPENDENCY_ALIAS' | 'BUILDER_DEPENDENCY_DIRECT' | 'BUILDER_DUPLICATE_MEMBER' | 'BUILDER_EDGE_LIFETIME' | 'BUILDER_FILE_INVALID' | 'BUILDER_FOREIGN_POLICY' | 'BUILDER_FULL_MATCH_INVALID' | 'BUILDER_FUNCTION' | 'BUILDER_METHOD' | 'BUILDER_PATH_DUPLICATE' | 'BUILDER_PATH_EMPTY' | 'BUILDER_POLICY' | 'BUILDER_POLICY_COMPOSITION' | 'BUILDER_POLICY_CYCLE' | 'BUILDER_POLICY_EMPTY_COMPOSITION' | 'BUILDER_POLICY_EMPTY_EXISTS' | 'BUILDER_POLICY_INPUT' | 'BUILDER_POLICY_REF' | 'BUILDER_POLICY_SELF' | 'BUILDER_PROPERTY_IMMUTABLE_INVALID' | 'BUILDER_REFERENCE_CYCLE' | 'BUILDER_REFERENCE_KIND' | 'BUILDER_REFERENCE_MISSING' | 'BUILDER_UNIQUE_PROPERTY' | 'BUILDER_UNKNOWN_FIELD' | 'BUILDER_UNOWNED_REFERENCE' | 'BUILDER_VIEW' | 'ZOD_SCHEMA_NOT_LOSSLESS';
5
5
  export interface BuilderDiagnostic<out Code extends BuilderDiagnosticCode = BuilderDiagnosticCode> {
6
6
  readonly code: Code;
7
7
  readonly pointer: string;
@@ -0,0 +1,34 @@
1
+ import { type z } from 'zod';
2
+ import type { BlobReceipt } from '../../language/value/model/blob.js';
3
+ import type { FileOptions } from '../../language/value/model/file.js';
4
+ declare const FILE_AUTHORING: unique symbol;
5
+ /**
6
+ * A file field of a callable input: an upload receipt on the wire, typed as the receipt an upload
7
+ * returns. Its schema is `schema.values.file(...)`.
8
+ */
9
+ export type FileAuthoring = z.ZodType<BlobReceipt, BlobReceipt> & {
10
+ readonly [FILE_AUTHORING]: true;
11
+ };
12
+ /**
13
+ * The blob Property whose constraints a file field copies: its schema (`schema.values.blob(...)`),
14
+ * the authored `property(...)`, any value carrying that schema as `schema`, as a DomainSchema
15
+ * Property definition does, or a function returning one, read when the schema is built.
16
+ */
17
+ export type FileSource = {
18
+ readonly 'x-astrale-value-kind': 'blob';
19
+ } | {
20
+ readonly schema: unknown;
21
+ } | object | (() => unknown);
22
+ /** A file field with no constraint, or with its own `maxBytes` and `mediaTypes`. */
23
+ export declare function file(options?: FileOptions): FileAuthoring;
24
+ /**
25
+ * A file field stating the constraints of one blob Property, copied when the schema is built;
26
+ * `tighten` may lower its `maxBytes` and narrow its `mediaTypes`, never loosen them.
27
+ */
28
+ export declare function file(source: FileSource, tighten?: FileOptions): FileAuthoring;
29
+ /**
30
+ * The constraints of an authored file field, resolved now; undefined for any other schema. A Zod
31
+ * clone of a file field, as `.describe()` or `.optional()` inner schemas make, is still one.
32
+ */
33
+ export declare function fileOptionsOfAuthoring(schema: z.ZodType): FileOptions | undefined;
34
+ export {};
@@ -0,0 +1,77 @@
1
+ import { string } from 'zod';
2
+ import { isBlobValueSchema } from '../../language/value/model/blob.js';
3
+ import { acceptFileOptions, blobFileOptions, tightenFileOptions, } from '../../language/value/model/file.js';
4
+ import { propertyAuthoringInput } from '../class/property.js';
5
+ import { fail } from '../schema/diagnostic.js';
6
+ import { isAuthoringValue } from '../schema/handle.js';
7
+ const fileInputs = new WeakMap();
8
+ export function file(input, tighten) {
9
+ const schema = string();
10
+ if (input === undefined || isFileOptions(input)) {
11
+ if (tighten !== undefined) {
12
+ fail('BUILDER_FILE_INVALID', '', 'file(options) takes no second argument.');
13
+ }
14
+ const options = admit(() => acceptFileOptions(input ?? {}));
15
+ fileInputs.set(schema, () => options);
16
+ }
17
+ else {
18
+ const narrowed = tighten === undefined ? undefined : admit(() => acceptFileOptions(tighten));
19
+ let resolved;
20
+ fileInputs.set(schema, () => {
21
+ resolved ??= admit(() => {
22
+ const base = blobFileOptions(blobSchemaOf(input));
23
+ return narrowed === undefined ? base : tightenFileOptions(base, narrowed);
24
+ });
25
+ return resolved;
26
+ });
27
+ }
28
+ return schema;
29
+ }
30
+ /**
31
+ * The constraints of an authored file field, resolved now; undefined for any other schema. A Zod
32
+ * clone of a file field, as `.describe()` or `.optional()` inner schemas make, is still one.
33
+ */
34
+ export function fileOptionsOfAuthoring(schema) {
35
+ for (let current = schema; current !== undefined; current = current._zod?.parent) {
36
+ const options = fileInputs.get(current);
37
+ if (options !== undefined)
38
+ return options();
39
+ }
40
+ return undefined;
41
+ }
42
+ function blobSchemaOf(input, depth = 0) {
43
+ if (typeof input === 'function' && depth === 0) {
44
+ return blobSchemaOf(input(), depth + 1);
45
+ }
46
+ if (isBlobValueSchema(input))
47
+ return input;
48
+ if (isAuthoringValue(input, 'property')) {
49
+ const authored = propertyAuthoringInput(input).schema;
50
+ if (isBlobValueSchema(authored))
51
+ return authored;
52
+ }
53
+ else if (input !== null && typeof input === 'object' && 'schema' in input) {
54
+ const schema = input.schema;
55
+ if (isBlobValueSchema(schema))
56
+ return schema;
57
+ }
58
+ throw new TypeError('file(source) requires a blob Property or its schema.');
59
+ }
60
+ function isFileOptions(input) {
61
+ return (typeof input === 'object' &&
62
+ input !== null &&
63
+ !isAuthoringValue(input, 'property') &&
64
+ !isBlobValueSchema(input) &&
65
+ !Object.hasOwn(input, 'schema') &&
66
+ Object.keys(input).every((key) => key === 'maxBytes' || key === 'mediaTypes'));
67
+ }
68
+ function admit(read) {
69
+ try {
70
+ return read();
71
+ }
72
+ catch (cause) {
73
+ if (!(cause instanceof TypeError))
74
+ throw cause;
75
+ fail('BUILDER_FILE_INVALID', '', `file(...): ${cause.message}`);
76
+ }
77
+ }
@@ -1,5 +1,5 @@
1
1
  /** Stable aggregate facade for the V1 language. */
2
- export { auto, core, defineClass, defineSchema, edgeClass, func, fullMatch, input, method, nodeClass, output, path, policy, property, stateProperty, valueSchema, view, } from './builder/index.js';
2
+ export { auto, core, defineClass, defineSchema, edgeClass, file, func, fullMatch, input, method, nodeClass, output, path, policy, property, stateProperty, valueSchema, view, } from './builder/index.js';
3
3
  export { stateMachine } from './language/state/index.js';
4
4
  export { isBinaryInput } from './language/callable/model/callable.js';
5
5
  export type { EventOf, StateMachine, StateOf } from './language/state/index.js';
@@ -12,7 +12,7 @@ export type { Definition } from './language/index.js';
12
12
  export type { Domain, MethodOwnerOf, SourceDomain } from './domain/index.js';
13
13
  export { isDomain } from './domain/index.js';
14
14
  export type * as builder from './builder/index.js';
15
- export type { PathAuthoring, TypedValueSchema } from './builder/index.js';
15
+ export type { FileAuthoring, PathAuthoring, TypedValueSchema } from './builder/index.js';
16
16
  export type { PropertyValues as PropertyValuesValue } from './language/index.js';
17
17
  export type { BlobReceipt, BlobRef } from './language/value/model/blob.js';
18
18
  export type { CompiledSchema } from './compiled/index.js';
package/dist/v1/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Stable aggregate facade for the V1 language. */
2
- export { auto, core, defineClass, defineSchema, edgeClass, func, fullMatch, input, method, nodeClass, output, path, policy, property, stateProperty, valueSchema, view, } from './builder/index.js';
2
+ export { auto, core, defineClass, defineSchema, edgeClass, file, func, fullMatch, input, method, nodeClass, output, path, policy, property, stateProperty, valueSchema, view, } from './builder/index.js';
3
3
  export { stateMachine } from './language/state/index.js';
4
4
  export { isBinaryInput } from './language/callable/model/callable.js';
5
5
  export { PropertyValues } from './language/index.js';
@@ -13,10 +13,11 @@
13
13
  "https://schemas.astrale.ai/dsl/v1/value-schema/vocabulary": true
14
14
  },
15
15
  "title": "Astrale V1 value schema",
16
- "$comment": "The meta-schema of the V1 value-schema dialect: Draft 2020-12 and the required Astrale vocabulary (fullMatch, x-astrale-path, x-astrale-value-kind). Its $dynamicAnchor extends Draft 2020-12 at every subschema, not only the root. The rules of the profile beyond it are published as schema.values.RULES.",
16
+ "$comment": "The meta-schema of the V1 value-schema dialect: Draft 2020-12 and the required Astrale vocabulary (fullMatch, x-astrale-file, x-astrale-path, x-astrale-value-kind). Its $dynamicAnchor extends Draft 2020-12 at every subschema, not only the root. The rules of the profile beyond it are published as schema.values.RULES.",
17
17
  "allOf": [{ "$ref": "https://json-schema.org/draft/2020-12/schema" }],
18
18
  "properties": {
19
19
  "fullMatch": { "type": "string" },
20
+ "x-astrale-file": { "type": "object" },
20
21
  "x-astrale-path": { "type": "object" }
21
22
  }
22
23
  }
@@ -97,8 +97,8 @@ export const VALUE_RULES = deepFreeze({
97
97
  },
98
98
  VS_VALUE_KIND: {
99
99
  stage: 'schema',
100
- positions: ['{/path*}/x-astrale-value-kind'],
101
- statement: 'x-astrale-value-kind declares instant beside type string at any location, or blob as the whole schema of a Property, exactly as values.blob writes it.',
100
+ positions: ['{/path*}/x-astrale-value-kind', '{/path*}/x-astrale-file'],
101
+ statement: 'x-astrale-value-kind declares instant beside type string at any location, blob as the whole schema of a Property, exactly as values.blob writes it, or file at any location of a callable input, exactly as values.file writes it, the only place x-astrale-file stands.',
102
102
  conditions: ['#/$defs/value-location/anyOf/1/if'],
103
103
  },
104
104
  VS_VALUE_KIND_JSON: {
@@ -0,0 +1,44 @@
1
+ import type { FileOptions } from './model/file.js';
2
+ import type { JsonSchema } from './model/schema.js';
3
+ /**
4
+ * One step from a value to a value it holds: a named member, an item of an array (every item, or
5
+ * the one at `index`), or an entry of an object that its declared members do not name (every such
6
+ * entry, or those whose name `pattern` matches as a JSON Schema `patternProperties` name does).
7
+ */
8
+ export type FileSegment = {
9
+ readonly kind: 'property';
10
+ readonly name: string;
11
+ } | {
12
+ readonly kind: 'item';
13
+ readonly index?: number;
14
+ } | {
15
+ readonly kind: 'entry';
16
+ /** Member names the entry is not: the declared members beside it. */
17
+ readonly except?: readonly string[];
18
+ /** For an additional member: the `patternProperties` names it does not match. */
19
+ readonly exceptPatterns?: readonly string[];
20
+ /** For a pattern member: the `patternProperties` name it matches. */
21
+ readonly pattern?: string;
22
+ };
23
+ /** Where a callable input holds a file field, and what that field states about its file. */
24
+ export interface FilePosition extends FileOptions {
25
+ readonly path: readonly FileSegment[];
26
+ }
27
+ /** One file field of a concrete input value: where it is, which position it fills, its value. */
28
+ export interface LocatedFile {
29
+ /** RFC 6901 JSON Pointer of the value inside the input. */
30
+ readonly pointer: string;
31
+ readonly position: FilePosition;
32
+ readonly value: unknown;
33
+ }
34
+ /**
35
+ * Every position at which a value admitted by `schema` may hold a file field, in schema order and
36
+ * without duplicates. Local `$ref`s are followed once per path: a file below a recursive reference
37
+ * is listed where the recursion first reaches it. Pure and total on an admitted value schema.
38
+ */
39
+ export declare function filePositions(schema: JsonSchema): readonly FilePosition[];
40
+ /**
41
+ * The values of `input` that fill one of `positions`, in position order, each with its JSON
42
+ * Pointer. A position the input does not reach yields nothing; nothing is validated.
43
+ */
44
+ export declare function locateFiles(positions: readonly FilePosition[], input: unknown): readonly LocatedFile[];
@@ -0,0 +1,150 @@
1
+ import { fileOptionsOf, isFileValueSchema } from './model/file.js';
2
+ import { isValueObject as isJsonObject } from './model/object.js';
3
+ import { escapePointerToken, parseJsonPointerFragment, resolvePointer } from './syntax/pointer.js';
4
+ const SAME_VALUE = ['allOf', 'anyOf', 'oneOf'];
5
+ // `not` admits no value through its subschema, so no file field lies below it.
6
+ const SAME_VALUE_SINGLE = ['if', 'then', 'else'];
7
+ /**
8
+ * Every position at which a value admitted by `schema` may hold a file field, in schema order and
9
+ * without duplicates. Local `$ref`s are followed once per path: a file below a recursive reference
10
+ * is listed where the recursion first reaches it. Pure and total on an admitted value schema.
11
+ */
12
+ export function filePositions(schema) {
13
+ const positions = [];
14
+ const seen = new Set();
15
+ const visit = (location, path, references) => {
16
+ if (!isJsonObject(location))
17
+ return;
18
+ if (isFileValueSchema(location)) {
19
+ const position = Object.freeze({ path: Object.freeze([...path]), ...fileOptionsOf(location) });
20
+ const key = JSON.stringify(position);
21
+ if (!seen.has(key)) {
22
+ seen.add(key);
23
+ positions.push(position);
24
+ }
25
+ return;
26
+ }
27
+ const reference = location.$ref;
28
+ if (typeof reference === 'string' && reference.startsWith('#') && !references.has(reference)) {
29
+ const target = resolveLocal(schema, reference);
30
+ if (target !== undefined)
31
+ visit(target, path, new Set([...references, reference]));
32
+ }
33
+ for (const keyword of SAME_VALUE) {
34
+ const branches = location[keyword];
35
+ if (Array.isArray(branches)) {
36
+ for (const branch of branches)
37
+ visit(branch, path, references);
38
+ }
39
+ }
40
+ for (const keyword of SAME_VALUE_SINGLE) {
41
+ if (Object.hasOwn(location, keyword)) {
42
+ visit(location[keyword], path, references);
43
+ }
44
+ }
45
+ if (isJsonObject(location.dependentSchemas)) {
46
+ for (const entry of Object.values(location.dependentSchemas)) {
47
+ visit(entry, path, references);
48
+ }
49
+ }
50
+ const declared = isJsonObject(location.properties) ? Object.keys(location.properties) : [];
51
+ if (isJsonObject(location.properties)) {
52
+ for (const [name, member] of Object.entries(location.properties)) {
53
+ visit(member, [...path, { kind: 'property', name }], references);
54
+ }
55
+ }
56
+ const patterns = isJsonObject(location.patternProperties)
57
+ ? Object.keys(location.patternProperties)
58
+ : [];
59
+ if (isJsonObject(location.patternProperties)) {
60
+ for (const [pattern, member] of Object.entries(location.patternProperties)) {
61
+ visit(member, [
62
+ ...path,
63
+ { kind: 'entry', ...(declared.length === 0 ? {} : { except: declared }), pattern },
64
+ ], references);
65
+ }
66
+ }
67
+ for (const keyword of ['additionalProperties', 'unevaluatedProperties']) {
68
+ if (!Object.hasOwn(location, keyword))
69
+ continue;
70
+ // An additional member is named neither by a declared member nor by a pattern.
71
+ const entry = {
72
+ kind: 'entry',
73
+ ...(declared.length === 0 ? {} : { except: declared }),
74
+ ...(patterns.length === 0 ? {} : { exceptPatterns: patterns }),
75
+ };
76
+ visit(location[keyword], [...path, entry], references);
77
+ }
78
+ if (Array.isArray(location.prefixItems)) {
79
+ location.prefixItems.forEach((item, index) => visit(item, [...path, { kind: 'item', index }], references));
80
+ }
81
+ for (const keyword of ['items', 'unevaluatedItems', 'contains']) {
82
+ if (Object.hasOwn(location, keyword)) {
83
+ visit(location[keyword], [...path, { kind: 'item' }], references);
84
+ }
85
+ }
86
+ };
87
+ visit(schema, [], new Set());
88
+ return Object.freeze(positions);
89
+ }
90
+ /**
91
+ * The values of `input` that fill one of `positions`, in position order, each with its JSON
92
+ * Pointer. A position the input does not reach yields nothing; nothing is validated.
93
+ */
94
+ export function locateFiles(positions, input) {
95
+ const located = [];
96
+ const seen = new Set();
97
+ for (const position of positions) {
98
+ const walk = (value, depth, pointer) => {
99
+ if (depth === position.path.length) {
100
+ if (!seen.has(pointer)) {
101
+ seen.add(pointer);
102
+ located.push(Object.freeze({ pointer, position, value }));
103
+ }
104
+ return;
105
+ }
106
+ const segment = position.path[depth];
107
+ if (segment.kind === 'property') {
108
+ if (isPlainObject(value) && Object.hasOwn(value, segment.name)) {
109
+ walk(value[segment.name], depth + 1, `${pointer}/${escapePointerToken(segment.name)}`);
110
+ }
111
+ return;
112
+ }
113
+ if (segment.kind === 'item') {
114
+ if (!Array.isArray(value))
115
+ return;
116
+ if (segment.index !== undefined) {
117
+ if (segment.index < value.length) {
118
+ walk(value[segment.index], depth + 1, `${pointer}/${segment.index}`);
119
+ }
120
+ return;
121
+ }
122
+ value.forEach((item, index) => walk(item, depth + 1, `${pointer}/${index}`));
123
+ return;
124
+ }
125
+ if (!isPlainObject(value))
126
+ return;
127
+ const matcher = segment.pattern === undefined ? undefined : new RegExp(segment.pattern, 'u');
128
+ const excluded = (segment.exceptPatterns ?? []).map((pattern) => new RegExp(pattern, 'u'));
129
+ for (const [name, member] of Object.entries(value)) {
130
+ if (segment.except?.includes(name))
131
+ continue;
132
+ if (matcher !== undefined && !matcher.test(name))
133
+ continue;
134
+ if (excluded.some((pattern) => pattern.test(name)))
135
+ continue;
136
+ walk(member, depth + 1, `${pointer}/${escapePointerToken(name)}`);
137
+ }
138
+ };
139
+ walk(input, 0, '');
140
+ }
141
+ return Object.freeze(located);
142
+ }
143
+ function resolveLocal(root, reference) {
144
+ const tokens = parseJsonPointerFragment(reference);
145
+ const target = tokens === undefined ? undefined : resolvePointer(root, tokens);
146
+ return typeof target === 'boolean' || isJsonObject(target) ? target : undefined;
147
+ }
148
+ function isPlainObject(value) {
149
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
150
+ }
@@ -54,6 +54,8 @@ export function evidenceOf(location) {
54
54
  kinds &= STRING;
55
55
  if (valueKind === 'blob')
56
56
  kinds &= OBJECT;
57
+ if (valueKind === 'file')
58
+ kinds &= STRING;
57
59
  }
58
60
  upper = tighter(upper, schema.maximum, false, (a, b) => a < b);
59
61
  upper = tighter(upper, schema.exclusiveMaximum, true, (a, b) => a < b);
@@ -1,4 +1,7 @@
1
+ import { fileOptionsOf } from '../model/file.js';
2
+ import { isValueObject as isJsonObject } from '../model/object.js';
1
3
  import { typeMask } from './kinds.js';
4
+ import { schemaOf } from './location.js';
2
5
  /** Rules for the keywords that restrict the kind or the exact value. */
3
6
  export const typeRules = new Map([
4
7
  ['type', ({ value, evidence }) => (evidence.kinds & ~typeMask(value)) === 0],
@@ -8,4 +11,24 @@ export const typeRules = new Map([
8
11
  'x-astrale-value-kind',
9
12
  ({ value, evidence }) => typeof value === 'string' && evidence.valueKinds.has(value),
10
13
  ],
14
+ // A file field admits the files of another whose constraints are at least as tight.
15
+ [
16
+ 'x-astrale-file',
17
+ ({ value, evidence }) => {
18
+ if (!isJsonObject(value))
19
+ return false;
20
+ const outer = fileOptionsOf({ 'x-astrale-file': value });
21
+ return evidence.conjuncts.some((conjunct) => {
22
+ const schema = schemaOf(conjunct);
23
+ if (!isJsonObject(schema) || !isJsonObject(schema['x-astrale-file']))
24
+ return false;
25
+ const inner = fileOptionsOf(schema);
26
+ return ((outer.maxBytes === undefined ||
27
+ (inner.maxBytes !== undefined && inner.maxBytes <= outer.maxBytes)) &&
28
+ (outer.mediaTypes === undefined ||
29
+ (inner.mediaTypes !== undefined &&
30
+ inner.mediaTypes.every((mediaType) => outer.mediaTypes.includes(mediaType)))));
31
+ });
32
+ },
33
+ ],
11
34
  ]);
@@ -0,0 +1,41 @@
1
+ import type { JsonSchemaObject } from './schema.js';
2
+ declare const FILE_SCHEMA: unique symbol;
3
+ /** Type-only marker; the serialized schema remains ordinary JSON. */
4
+ export interface FileSchema extends JsonSchemaObject {
5
+ readonly [FILE_SCHEMA]: true;
6
+ }
7
+ /**
8
+ * What a file field states about the file its receipt names. The Kernel never checks it against a
9
+ * receipt: a client and the SDK check a file before they upload it, and a blob Property the Domain
10
+ * attaches it to applies its own constraints.
11
+ */
12
+ export interface FileOptions {
13
+ /** Upper bound in bytes, 1 or more. */
14
+ readonly maxBytes?: number;
15
+ /** Non-empty canonical media types; omission admits any. */
16
+ readonly mediaTypes?: readonly string[];
17
+ }
18
+ export declare const FILE_VALUE_KIND: 'file';
19
+ /** The keyword that carries a file field's constraints, beside `x-astrale-value-kind: file`. */
20
+ export declare const FILE_KEYWORD: 'x-astrale-file';
21
+ /**
22
+ * The one canonical V1 schema of a file field: an upload receipt on the wire, with the constraints
23
+ * of the file it names under `x-astrale-file` when there are any.
24
+ */
25
+ export declare function file(options?: FileOptions): FileSchema;
26
+ /** Marker recognition on an already admitted V1 value schema. */
27
+ export declare function isFileValueSchema(input: unknown): input is FileSchema;
28
+ /** The constraints a file field states. */
29
+ export declare function fileOptionsOf(schema: FileSchema | JsonSchemaObject): FileOptions;
30
+ /** The constraints of a blob Property, as a file field that feeds it states them. */
31
+ export declare function blobFileOptions(schema: JsonSchemaObject): FileOptions;
32
+ /**
33
+ * `base` tightened by `tighter`: a lower `maxBytes`, a subset of `mediaTypes`. A constraint
34
+ * `tighter` would loosen is refused.
35
+ */
36
+ export declare function tightenFileOptions(base: FileOptions, tighter: FileOptions): FileOptions;
37
+ /** Whether `schema` is exactly one `file(...)` output, plus annotation keywords. */
38
+ export declare function isCanonicalFileSchema(schema: Readonly<Record<string, unknown>>): boolean;
39
+ /** Canonical file options: positive safe-integer bound, sorted unique canonical media types. */
40
+ export declare function acceptFileOptions(options: FileOptions): FileOptions;
41
+ export {};