@schema-engine/registry 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/dist/base-registry.d.ts +73 -0
- package/dist/base-registry.js +1 -0
- package/dist/base-registry.js.map +7 -0
- package/dist/create-registry.d.ts +46 -0
- package/dist/create-registry.js +1 -0
- package/dist/create-registry.js.map +7 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +7 -0
- package/dist/standard-schema.d.ts +23 -0
- package/dist/standard-schema.js +1 -0
- package/dist/standard-schema.js.map +7 -0
- package/dist/types.d.ts +55 -0
- package/dist/types.js +0 -0
- package/dist/types.js.map +7 -0
- package/dist/yaml/index.d.ts +4 -0
- package/dist/yaml/index.js +4 -0
- package/dist/yaml/index.js.map +7 -0
- package/dist/yaml/parse.d.ts +90 -0
- package/dist/yaml/parse.js +2 -0
- package/dist/yaml/parse.js.map +7 -0
- package/dist/yaml/stringify.d.ts +16 -0
- package/dist/yaml/stringify.js +3 -0
- package/dist/yaml/stringify.js.map +7 -0
- package/package.json +72 -3
- package/skill/SKILL.md +79 -0
- package/skill/reference/registry.md +63 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-present Andrea Zanenghi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,63 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @schema-engine/registry
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The registration contract and the read-only registries that hold registrations by `$type`. It is the base of Schema Engine's common language: a document names registrations by `$type`, a registry resolves each one, and the registration's schema validates its configuration. It has no UI and no schema-library dependency.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @schema-engine/registry zod
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Install the [Standard Schema](https://standardschema.dev/) validator you prefer. The example uses `zod/mini`.
|
|
12
|
+
|
|
13
|
+
## Example
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import * as z from 'zod/mini';
|
|
17
|
+
import { createRegistry, safeParseStandardSchema, type BaseRegistration } from '@schema-engine/registry';
|
|
18
|
+
|
|
19
|
+
z.config(z.locales.en());
|
|
20
|
+
|
|
21
|
+
interface Badge extends BaseRegistration {
|
|
22
|
+
render(config: unknown): string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const badgeSchema = z.object({ $type: z.literal('badge'), label: z.string() });
|
|
26
|
+
|
|
27
|
+
const badge: Badge = {
|
|
28
|
+
$type: 'badge',
|
|
29
|
+
schema: badgeSchema,
|
|
30
|
+
metadata: { name: 'Badge', description: 'A short status label.' },
|
|
31
|
+
render: ({ label }: z.output<typeof badgeSchema>) => `<span class="badge">${label}</span>`,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const badges = createRegistry('Badge', [badge]);
|
|
35
|
+
|
|
36
|
+
export function resolve(node: { $type: string }): string {
|
|
37
|
+
const registration = badges.get(node.$type);
|
|
38
|
+
if (!registration) return `No registration for $type '${node.$type}'.`;
|
|
39
|
+
const parsed = safeParseStandardSchema(registration.schema, node);
|
|
40
|
+
return parsed.success
|
|
41
|
+
? registration.render(parsed.data)
|
|
42
|
+
: parsed.error.issues.map((issue) => issue.message).join('; ');
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Entry points
|
|
47
|
+
|
|
48
|
+
| Import | Holds |
|
|
49
|
+
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
|
|
50
|
+
| `@schema-engine/registry` | `createRegistry`, `BaseRegistry`, the registration types, `safeParseStandardSchema` and `assertStandardSchema` |
|
|
51
|
+
| `@schema-engine/registry/yaml` | `parseYaml`, `safeParseYaml` and `stringifyYaml`, which report errors by line and column. Needs the optional peer dependency `yaml` |
|
|
52
|
+
|
|
53
|
+
## Documentation
|
|
54
|
+
|
|
55
|
+
- [Registry](https://schema-engine.com/docs/registry/overview): install, build a registry and resolve a JSON node.
|
|
56
|
+
- [Read-only and mutable registries](https://schema-engine.com/docs/registry/registries): `createRegistry` and `BaseRegistry`.
|
|
57
|
+
- [Resolve a document](https://schema-engine.com/docs/registry/resolve-a-document): walk a tree of nodes through registries.
|
|
58
|
+
- [API reference](https://schema-engine.com/docs/registry/api-reference): every export.
|
|
59
|
+
- [For AI agents](https://schema-engine.com/docs/schema-engine/agent-skill): the package ships its part of the agent skill.
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
MIT
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { BaseRegistration } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Base Registry - Abstract class for all registries
|
|
4
|
+
*
|
|
5
|
+
* Provides common registration, retrieval, and management functionality.
|
|
6
|
+
* Each registry extends this to add type-specific behavior.
|
|
7
|
+
*
|
|
8
|
+
* All registrations must extend BaseRegistration which provides the unified `$type` field.
|
|
9
|
+
*
|
|
10
|
+
* @template TKey - The key type (typically string)
|
|
11
|
+
* @template TValue - The value type (registration object extending BaseRegistration)
|
|
12
|
+
*/
|
|
13
|
+
export declare abstract class BaseRegistry<TKey extends string, TValue extends BaseRegistration> {
|
|
14
|
+
protected items: Map<TKey, TValue>;
|
|
15
|
+
/**
|
|
16
|
+
* Get the registry name for logging purposes.
|
|
17
|
+
*/
|
|
18
|
+
abstract get registryName(): string;
|
|
19
|
+
/**
|
|
20
|
+
* Extract the key from an item.
|
|
21
|
+
* Uses the unified `$type` field from BaseRegistration.
|
|
22
|
+
* @param item - The item to extract the key from
|
|
23
|
+
*/
|
|
24
|
+
protected getItemKey(item: TValue): TKey;
|
|
25
|
+
/**
|
|
26
|
+
* Extract the name from an item for logging.
|
|
27
|
+
* Uses the `name` field from metadata.
|
|
28
|
+
* @param item - The item to extract the name from
|
|
29
|
+
*/
|
|
30
|
+
protected getItemName(item: TValue): string;
|
|
31
|
+
/**
|
|
32
|
+
* Register an item.
|
|
33
|
+
*
|
|
34
|
+
* @param item - The item to register
|
|
35
|
+
*/
|
|
36
|
+
register(item: TValue): void;
|
|
37
|
+
/**
|
|
38
|
+
* Check if an item is registered.
|
|
39
|
+
*
|
|
40
|
+
* @param key - The key to check
|
|
41
|
+
* @returns True if the item is registered
|
|
42
|
+
*/
|
|
43
|
+
has(key: TKey): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Get a registered item.
|
|
46
|
+
*
|
|
47
|
+
* @param key - The key to retrieve
|
|
48
|
+
* @returns The item or undefined if not found
|
|
49
|
+
*/
|
|
50
|
+
get(key: TKey): TValue | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Get all registered items.
|
|
53
|
+
*
|
|
54
|
+
* @returns Array of all registered items
|
|
55
|
+
*/
|
|
56
|
+
getAll(): TValue[];
|
|
57
|
+
/**
|
|
58
|
+
* Get all registered keys.
|
|
59
|
+
*
|
|
60
|
+
* @returns Array of all registered keys
|
|
61
|
+
*/
|
|
62
|
+
getAllKeys(): TKey[];
|
|
63
|
+
/**
|
|
64
|
+
* Get the number of registered items.
|
|
65
|
+
*
|
|
66
|
+
* @returns The number of items in the registry
|
|
67
|
+
*/
|
|
68
|
+
get size(): number;
|
|
69
|
+
/**
|
|
70
|
+
* Clear all registered items. Primarily for testing.
|
|
71
|
+
*/
|
|
72
|
+
clear(): void;
|
|
73
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Logger as m}from"@ecopages/logger";var s=new m("[@schema-engine/registry]"),a=class{items=new Map;getItemKey(e){return e.$type}getItemName(e){return e.metadata.name}register(e){let t=this.getItemKey(e),r=this.getItemName(e);if(this.items.has(t)){let i=this.items.get(t),n=i?this.getItemName(i):"unknown";s.warn(`Overriding ${this.registryName}: ${t}`,{previousName:n,newName:r})}this.items.set(t,e),s.debug(`Registered ${this.registryName}: ${t}`,{name:r})}has(e){return this.items.has(e)}get(e){return this.items.get(e)}getAll(){return Array.from(this.items.values())}getAllKeys(){return Array.from(this.items.keys())}get size(){return this.items.size}clear(){this.items.clear(),s.debug(`${this.registryName} cleared`)}};export{a as BaseRegistry};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/base-registry.ts"],
|
|
4
|
+
"sourcesContent": ["import { Logger } from '@ecopages/logger';\nimport type { BaseRegistration } from './types.js';\n\nconst logger = new Logger('[@schema-engine/registry]');\n\n/**\n * Base Registry - Abstract class for all registries\n *\n * Provides common registration, retrieval, and management functionality.\n * Each registry extends this to add type-specific behavior.\n *\n * All registrations must extend BaseRegistration which provides the unified `$type` field.\n *\n * @template TKey - The key type (typically string)\n * @template TValue - The value type (registration object extending BaseRegistration)\n */\nexport abstract class BaseRegistry<TKey extends string, TValue extends BaseRegistration> {\n\tprotected items = new Map<TKey, TValue>();\n\n\t/**\n\t * Get the registry name for logging purposes.\n\t */\n\tabstract get registryName(): string;\n\n\t/**\n\t * Extract the key from an item.\n\t * Uses the unified `$type` field from BaseRegistration.\n\t * @param item - The item to extract the key from\n\t */\n\tprotected getItemKey(item: TValue): TKey {\n\t\treturn item.$type as TKey;\n\t}\n\n\t/**\n\t * Extract the name from an item for logging.\n\t * Uses the `name` field from metadata.\n\t * @param item - The item to extract the name from\n\t */\n\tprotected getItemName(item: TValue): string {\n\t\treturn item.metadata.name;\n\t}\n\n\t/**\n\t * Register an item.\n\t *\n\t * @param item - The item to register\n\t */\n\tregister(item: TValue): void {\n\t\tconst key = this.getItemKey(item);\n\t\tconst name = this.getItemName(item);\n\n\t\tif (this.items.has(key)) {\n\t\t\tconst existing = this.items.get(key);\n\t\t\tconst existingName = existing ? this.getItemName(existing) : 'unknown';\n\t\t\tlogger.warn(`Overriding ${this.registryName}: ${key}`, {\n\t\t\t\tpreviousName: existingName,\n\t\t\t\tnewName: name,\n\t\t\t});\n\t\t}\n\n\t\tthis.items.set(key, item);\n\t\tlogger.debug(`Registered ${this.registryName}: ${key}`, {\n\t\t\tname,\n\t\t});\n\t}\n\n\t/**\n\t * Check if an item is registered.\n\t *\n\t * @param key - The key to check\n\t * @returns True if the item is registered\n\t */\n\thas(key: TKey): boolean {\n\t\treturn this.items.has(key);\n\t}\n\n\t/**\n\t * Get a registered item.\n\t *\n\t * @param key - The key to retrieve\n\t * @returns The item or undefined if not found\n\t */\n\tget(key: TKey): TValue | undefined {\n\t\treturn this.items.get(key);\n\t}\n\n\t/**\n\t * Get all registered items.\n\t *\n\t * @returns Array of all registered items\n\t */\n\tgetAll(): TValue[] {\n\t\treturn Array.from(this.items.values());\n\t}\n\n\t/**\n\t * Get all registered keys.\n\t *\n\t * @returns Array of all registered keys\n\t */\n\tgetAllKeys(): TKey[] {\n\t\treturn Array.from(this.items.keys());\n\t}\n\n\t/**\n\t * Get the number of registered items.\n\t *\n\t * @returns The number of items in the registry\n\t */\n\tget size(): number {\n\t\treturn this.items.size;\n\t}\n\n\t/**\n\t * Clear all registered items. Primarily for testing.\n\t */\n\tclear(): void {\n\t\tthis.items.clear();\n\t\tlogger.debug(`${this.registryName} cleared`);\n\t}\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,UAAAA,MAAc,mBAGvB,IAAMC,EAAS,IAAID,EAAO,2BAA2B,EAa/BE,EAAf,KAAkF,CAC9E,MAAQ,IAAI,IAYZ,WAAWC,EAAoB,CACxC,OAAOA,EAAK,KACb,CAOU,YAAYA,EAAsB,CAC3C,OAAOA,EAAK,SAAS,IACtB,CAOA,SAASA,EAAoB,CAC5B,IAAMC,EAAM,KAAK,WAAWD,CAAI,EAC1BE,EAAO,KAAK,YAAYF,CAAI,EAElC,GAAI,KAAK,MAAM,IAAIC,CAAG,EAAG,CACxB,IAAME,EAAW,KAAK,MAAM,IAAIF,CAAG,EAC7BG,EAAeD,EAAW,KAAK,YAAYA,CAAQ,EAAI,UAC7DL,EAAO,KAAK,cAAc,KAAK,YAAY,KAAKG,CAAG,GAAI,CACtD,aAAcG,EACd,QAASF,CACV,CAAC,CACF,CAEA,KAAK,MAAM,IAAID,EAAKD,CAAI,EACxBF,EAAO,MAAM,cAAc,KAAK,YAAY,KAAKG,CAAG,GAAI,CACvD,KAAAC,CACD,CAAC,CACF,CAQA,IAAID,EAAoB,CACvB,OAAO,KAAK,MAAM,IAAIA,CAAG,CAC1B,CAQA,IAAIA,EAA+B,CAClC,OAAO,KAAK,MAAM,IAAIA,CAAG,CAC1B,CAOA,QAAmB,CAClB,OAAO,MAAM,KAAK,KAAK,MAAM,OAAO,CAAC,CACtC,CAOA,YAAqB,CACpB,OAAO,MAAM,KAAK,KAAK,MAAM,KAAK,CAAC,CACpC,CAOA,IAAI,MAAe,CAClB,OAAO,KAAK,MAAM,IACnB,CAKA,OAAc,CACb,KAAK,MAAM,MAAM,EACjBH,EAAO,MAAM,GAAG,KAAK,YAAY,UAAU,CAC5C,CACD",
|
|
6
|
+
"names": ["Logger", "logger", "BaseRegistry", "item", "key", "name", "existing", "existingName"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import type { BaseRegistration } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A registry built once from a list of registrations. It has no `register` or
|
|
5
|
+
* `clear`; to change its contents, build another registry from a new list.
|
|
6
|
+
*/
|
|
7
|
+
export interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseRegistration> {
|
|
8
|
+
/** Label used in build errors, for example `Element`. */
|
|
9
|
+
readonly kind: string;
|
|
10
|
+
/** Number of distinct `$type` keys. */
|
|
11
|
+
readonly size: number;
|
|
12
|
+
get(key: string): TRegistration | undefined;
|
|
13
|
+
has(key: string): boolean;
|
|
14
|
+
/** Registrations in first-registration order. The array is frozen. */
|
|
15
|
+
all(): readonly TRegistration[];
|
|
16
|
+
/** `$type` keys in first-registration order. The array is frozen. */
|
|
17
|
+
keys(): readonly string[];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Require a registration schema to implement Standard Schema.
|
|
21
|
+
*
|
|
22
|
+
* @param schema - Value to check
|
|
23
|
+
* @param context - Subject of the error message, for example `Element 'text' schema`
|
|
24
|
+
* @throws {Error} When `schema` has no `~standard.validate` function
|
|
25
|
+
*/
|
|
26
|
+
export declare function assertStandardSchema(schema: unknown, context?: string): StandardSchemaV1;
|
|
27
|
+
/**
|
|
28
|
+
* Build a frozen, read-only registry from a list of registrations.
|
|
29
|
+
*
|
|
30
|
+
* @param kind - Label for errors, for example `Element`
|
|
31
|
+
* @param registrations - Registrations to store, keyed by `$type`
|
|
32
|
+
* @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema
|
|
33
|
+
*
|
|
34
|
+
* @remarks
|
|
35
|
+
* A later registration with the same `$type` replaces the earlier one without a
|
|
36
|
+
* warning, so `[...defaults, custom]` is the way to override. A replaced key
|
|
37
|
+
* keeps its first position. Only the winning registration of each key is
|
|
38
|
+
* checked. The registry stores a frozen shallow copy of each winner, taken at
|
|
39
|
+
* build, and leaves the objects you passed untouched. Later assignments to or
|
|
40
|
+
* spies on those objects do not reach the registry, so patch before building or
|
|
41
|
+
* build a new registry. The copy shares nested values such as `schema` with the
|
|
42
|
+
* original.
|
|
43
|
+
*
|
|
44
|
+
* Use {@link BaseRegistry} instead when registrations arrive at runtime.
|
|
45
|
+
*/
|
|
46
|
+
export declare function createRegistry<TRegistration extends BaseRegistration>(kind: string, registrations: readonly TRegistration[]): ReadOnlyRegistry<TRegistration>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function d(t,a="Registration schema"){if(typeof(t!==null&&(typeof t=="object"||typeof t=="function")?t["~standard"]:void 0)?.validate!="function")throw new Error(`${a} must implement Standard Schema (~standard.validate).`);return t}function g(t,a){let r=new Map;for(let e of a)r.set(e.$type,e);let n=new Map;for(let[e,s]of r)d(s.schema,`${t} '${e}' schema`),n.set(e,Object.freeze({...s}));let i=Object.freeze([...n.values()]),o=Object.freeze([...n.keys()]);return Object.freeze({kind:t,size:n.size,get:e=>n.get(e),has:e=>n.has(e),all:()=>i,keys:()=>o})}export{d as assertStandardSchema,g as createRegistry};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/create-registry.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * A registry built once from a list of registrations. It has no `register` or\n * `clear`; to change its contents, build another registry from a new list.\n */\nexport interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseRegistration> {\n\t/** Label used in build errors, for example `Element`. */\n\treadonly kind: string;\n\t/** Number of distinct `$type` keys. */\n\treadonly size: number;\n\tget(key: string): TRegistration | undefined;\n\thas(key: string): boolean;\n\t/** Registrations in first-registration order. The array is frozen. */\n\tall(): readonly TRegistration[];\n\t/** `$type` keys in first-registration order. The array is frozen. */\n\tkeys(): readonly string[];\n}\n\n/**\n * Require a registration schema to implement Standard Schema.\n *\n * @param schema - Value to check\n * @param context - Subject of the error message, for example `Element 'text' schema`\n * @throws {Error} When `schema` has no `~standard.validate` function\n */\nexport function assertStandardSchema(schema: unknown, context = 'Registration schema'): StandardSchemaV1 {\n\tconst standard =\n\t\tschema !== null && (typeof schema === 'object' || typeof schema === 'function')\n\t\t\t? (schema as Partial<StandardSchemaV1>)['~standard']\n\t\t\t: undefined;\n\tif (typeof standard?.validate !== 'function') {\n\t\tthrow new Error(`${context} must implement Standard Schema (~standard.validate).`);\n\t}\n\treturn schema as StandardSchemaV1;\n}\n\n/**\n * Build a frozen, read-only registry from a list of registrations.\n *\n * @param kind - Label for errors, for example `Element`\n * @param registrations - Registrations to store, keyed by `$type`\n * @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema\n *\n * @remarks\n * A later registration with the same `$type` replaces the earlier one without a\n * warning, so `[...defaults, custom]` is the way to override. A replaced key\n * keeps its first position. Only the winning registration of each key is\n * checked. The registry stores a frozen shallow copy of each winner, taken at\n * build, and leaves the objects you passed untouched. Later assignments to or\n * spies on those objects do not reach the registry, so patch before building or\n * build a new registry. The copy shares nested values such as `schema` with the\n * original.\n *\n * Use {@link BaseRegistry} instead when registrations arrive at runtime.\n */\nexport function createRegistry<TRegistration extends BaseRegistration>(\n\tkind: string,\n\tregistrations: readonly TRegistration[],\n): ReadOnlyRegistry<TRegistration> {\n\tconst winners = new Map<string, TRegistration>();\n\tfor (const registration of registrations) {\n\t\twinners.set(registration.$type, registration);\n\t}\n\tconst entries = new Map<string, Readonly<TRegistration>>();\n\tfor (const [key, registration] of winners) {\n\t\tassertStandardSchema(registration.schema, `${kind} '${key}' schema`);\n\t\tentries.set(key, Object.freeze({ ...registration }));\n\t}\n\tconst all = Object.freeze([...entries.values()]);\n\tconst keys = Object.freeze([...entries.keys()]);\n\n\treturn Object.freeze({\n\t\tkind,\n\t\tsize: entries.size,\n\t\tget: (key: string) => entries.get(key),\n\t\thas: (key: string) => entries.has(key),\n\t\tall: () => all,\n\t\tkeys: () => keys,\n\t});\n}\n"],
|
|
5
|
+
"mappings": "AA2BO,SAASA,EAAqBC,EAAiBC,EAAU,sBAAyC,CAKxG,GAAI,OAHHD,IAAW,OAAS,OAAOA,GAAW,UAAY,OAAOA,GAAW,YAChEA,EAAqC,WAAW,EACjD,SACiB,UAAa,WACjC,MAAM,IAAI,MAAM,GAAGC,CAAO,uDAAuD,EAElF,OAAOD,CACR,CAqBO,SAASE,EACfC,EACAC,EACkC,CAClC,IAAMC,EAAU,IAAI,IACpB,QAAWC,KAAgBF,EAC1BC,EAAQ,IAAIC,EAAa,MAAOA,CAAY,EAE7C,IAAMC,EAAU,IAAI,IACpB,OAAW,CAACC,EAAKF,CAAY,IAAKD,EACjCN,EAAqBO,EAAa,OAAQ,GAAGH,CAAI,KAAKK,CAAG,UAAU,EACnED,EAAQ,IAAIC,EAAK,OAAO,OAAO,CAAE,GAAGF,CAAa,CAAC,CAAC,EAEpD,IAAMG,EAAM,OAAO,OAAO,CAAC,GAAGF,EAAQ,OAAO,CAAC,CAAC,EACzCG,EAAO,OAAO,OAAO,CAAC,GAAGH,EAAQ,KAAK,CAAC,CAAC,EAE9C,OAAO,OAAO,OAAO,CACpB,KAAAJ,EACA,KAAMI,EAAQ,KACd,IAAMC,GAAgBD,EAAQ,IAAIC,CAAG,EACrC,IAAMA,GAAgBD,EAAQ,IAAIC,CAAG,EACrC,IAAK,IAAMC,EACX,KAAM,IAAMC,CACb,CAAC,CACF",
|
|
6
|
+
"names": ["assertStandardSchema", "schema", "context", "createRegistry", "kind", "registrations", "winners", "registration", "entries", "key", "all", "keys"]
|
|
7
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Logger as c}from"@ecopages/logger";var o=new c("[@schema-engine/registry]"),u=class{items=new Map;getItemKey(e){return e.$type}getItemName(e){return e.metadata.name}register(e){let t=this.getItemKey(e),s=this.getItemName(e);if(this.items.has(t)){let n=this.items.get(t),i=n?this.getItemName(n):"unknown";o.warn(`Overriding ${this.registryName}: ${t}`,{previousName:i,newName:s})}this.items.set(t,e),o.debug(`Registered ${this.registryName}: ${t}`,{name:s})}has(e){return this.items.has(e)}get(e){return this.items.get(e)}getAll(){return Array.from(this.items.values())}getAllKeys(){return Array.from(this.items.keys())}get size(){return this.items.size}clear(){this.items.clear(),o.debug(`${this.registryName} cleared`)}};function m(r,e="Registration schema"){if(typeof(r!==null&&(typeof r=="object"||typeof r=="function")?r["~standard"]:void 0)?.validate!="function")throw new Error(`${e} must implement Standard Schema (~standard.validate).`);return r}function y(r,e){let t=new Map;for(let a of e)t.set(a.$type,a);let s=new Map;for(let[a,d]of t)m(d.schema,`${r} '${a}' schema`),s.set(a,Object.freeze({...d}));let n=Object.freeze([...s.values()]),i=Object.freeze([...s.keys()]);return Object.freeze({kind:r,size:s.size,get:a=>s.get(a),has:a=>s.has(a),all:()=>n,keys:()=>i})}function f(r,e){let t=r["~standard"].validate(e);if(t&&typeof t.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(t===null||typeof t!="object")throw new Error("Standard Schema validation returned an invalid result");let s=t;return s.issues!==void 0?{success:!1,error:{issues:[...s.issues]}}:{success:!0,data:s.value}}export{u as BaseRegistry,m as assertStandardSchema,y as createRegistry,f as safeParseStandardSchema};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/base-registry.ts", "../src/create-registry.ts", "../src/standard-schema.ts"],
|
|
4
|
+
"sourcesContent": ["import { Logger } from '@ecopages/logger';\nimport type { BaseRegistration } from './types.js';\n\nconst logger = new Logger('[@schema-engine/registry]');\n\n/**\n * Base Registry - Abstract class for all registries\n *\n * Provides common registration, retrieval, and management functionality.\n * Each registry extends this to add type-specific behavior.\n *\n * All registrations must extend BaseRegistration which provides the unified `$type` field.\n *\n * @template TKey - The key type (typically string)\n * @template TValue - The value type (registration object extending BaseRegistration)\n */\nexport abstract class BaseRegistry<TKey extends string, TValue extends BaseRegistration> {\n\tprotected items = new Map<TKey, TValue>();\n\n\t/**\n\t * Get the registry name for logging purposes.\n\t */\n\tabstract get registryName(): string;\n\n\t/**\n\t * Extract the key from an item.\n\t * Uses the unified `$type` field from BaseRegistration.\n\t * @param item - The item to extract the key from\n\t */\n\tprotected getItemKey(item: TValue): TKey {\n\t\treturn item.$type as TKey;\n\t}\n\n\t/**\n\t * Extract the name from an item for logging.\n\t * Uses the `name` field from metadata.\n\t * @param item - The item to extract the name from\n\t */\n\tprotected getItemName(item: TValue): string {\n\t\treturn item.metadata.name;\n\t}\n\n\t/**\n\t * Register an item.\n\t *\n\t * @param item - The item to register\n\t */\n\tregister(item: TValue): void {\n\t\tconst key = this.getItemKey(item);\n\t\tconst name = this.getItemName(item);\n\n\t\tif (this.items.has(key)) {\n\t\t\tconst existing = this.items.get(key);\n\t\t\tconst existingName = existing ? this.getItemName(existing) : 'unknown';\n\t\t\tlogger.warn(`Overriding ${this.registryName}: ${key}`, {\n\t\t\t\tpreviousName: existingName,\n\t\t\t\tnewName: name,\n\t\t\t});\n\t\t}\n\n\t\tthis.items.set(key, item);\n\t\tlogger.debug(`Registered ${this.registryName}: ${key}`, {\n\t\t\tname,\n\t\t});\n\t}\n\n\t/**\n\t * Check if an item is registered.\n\t *\n\t * @param key - The key to check\n\t * @returns True if the item is registered\n\t */\n\thas(key: TKey): boolean {\n\t\treturn this.items.has(key);\n\t}\n\n\t/**\n\t * Get a registered item.\n\t *\n\t * @param key - The key to retrieve\n\t * @returns The item or undefined if not found\n\t */\n\tget(key: TKey): TValue | undefined {\n\t\treturn this.items.get(key);\n\t}\n\n\t/**\n\t * Get all registered items.\n\t *\n\t * @returns Array of all registered items\n\t */\n\tgetAll(): TValue[] {\n\t\treturn Array.from(this.items.values());\n\t}\n\n\t/**\n\t * Get all registered keys.\n\t *\n\t * @returns Array of all registered keys\n\t */\n\tgetAllKeys(): TKey[] {\n\t\treturn Array.from(this.items.keys());\n\t}\n\n\t/**\n\t * Get the number of registered items.\n\t *\n\t * @returns The number of items in the registry\n\t */\n\tget size(): number {\n\t\treturn this.items.size;\n\t}\n\n\t/**\n\t * Clear all registered items. Primarily for testing.\n\t */\n\tclear(): void {\n\t\tthis.items.clear();\n\t\tlogger.debug(`${this.registryName} cleared`);\n\t}\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * A registry built once from a list of registrations. It has no `register` or\n * `clear`; to change its contents, build another registry from a new list.\n */\nexport interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseRegistration> {\n\t/** Label used in build errors, for example `Element`. */\n\treadonly kind: string;\n\t/** Number of distinct `$type` keys. */\n\treadonly size: number;\n\tget(key: string): TRegistration | undefined;\n\thas(key: string): boolean;\n\t/** Registrations in first-registration order. The array is frozen. */\n\tall(): readonly TRegistration[];\n\t/** `$type` keys in first-registration order. The array is frozen. */\n\tkeys(): readonly string[];\n}\n\n/**\n * Require a registration schema to implement Standard Schema.\n *\n * @param schema - Value to check\n * @param context - Subject of the error message, for example `Element 'text' schema`\n * @throws {Error} When `schema` has no `~standard.validate` function\n */\nexport function assertStandardSchema(schema: unknown, context = 'Registration schema'): StandardSchemaV1 {\n\tconst standard =\n\t\tschema !== null && (typeof schema === 'object' || typeof schema === 'function')\n\t\t\t? (schema as Partial<StandardSchemaV1>)['~standard']\n\t\t\t: undefined;\n\tif (typeof standard?.validate !== 'function') {\n\t\tthrow new Error(`${context} must implement Standard Schema (~standard.validate).`);\n\t}\n\treturn schema as StandardSchemaV1;\n}\n\n/**\n * Build a frozen, read-only registry from a list of registrations.\n *\n * @param kind - Label for errors, for example `Element`\n * @param registrations - Registrations to store, keyed by `$type`\n * @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema\n *\n * @remarks\n * A later registration with the same `$type` replaces the earlier one without a\n * warning, so `[...defaults, custom]` is the way to override. A replaced key\n * keeps its first position. Only the winning registration of each key is\n * checked. The registry stores a frozen shallow copy of each winner, taken at\n * build, and leaves the objects you passed untouched. Later assignments to or\n * spies on those objects do not reach the registry, so patch before building or\n * build a new registry. The copy shares nested values such as `schema` with the\n * original.\n *\n * Use {@link BaseRegistry} instead when registrations arrive at runtime.\n */\nexport function createRegistry<TRegistration extends BaseRegistration>(\n\tkind: string,\n\tregistrations: readonly TRegistration[],\n): ReadOnlyRegistry<TRegistration> {\n\tconst winners = new Map<string, TRegistration>();\n\tfor (const registration of registrations) {\n\t\twinners.set(registration.$type, registration);\n\t}\n\tconst entries = new Map<string, Readonly<TRegistration>>();\n\tfor (const [key, registration] of winners) {\n\t\tassertStandardSchema(registration.schema, `${kind} '${key}' schema`);\n\t\tentries.set(key, Object.freeze({ ...registration }));\n\t}\n\tconst all = Object.freeze([...entries.values()]);\n\tconst keys = Object.freeze([...entries.keys()]);\n\n\treturn Object.freeze({\n\t\tkind,\n\t\tsize: entries.size,\n\t\tget: (key: string) => entries.get(key),\n\t\thas: (key: string) => entries.has(key),\n\t\tall: () => all,\n\t\tkeys: () => keys,\n\t});\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport type StandardSchemaIssue = StandardSchemaV1.Issue;\n\nexport type StandardSchemaSafeParseResult<T> =\n\t{ success: true; data: T } | { success: false; error: { issues: StandardSchemaIssue[] } };\n\n/**\n * Validate `value` with a Standard Schema without throwing.\n *\n * @param schema - Standard Schema to run\n * @param value - Input to validate\n * @throws {Error} When the schema validates asynchronously or returns a malformed result\n *\n * @remarks\n * Only synchronous validation is supported, because the callers (registry lookups, form validation,\n * action parsing) need an immediate result.\n */\nexport function safeParseStandardSchema<TInput, TOutput>(\n\tschema: StandardSchemaV1<TInput, TOutput>,\n\tvalue: TInput,\n): StandardSchemaSafeParseResult<TOutput> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\n\tconst syncResult = result as StandardSchemaV1.Result<TOutput>;\n\n\tif (syncResult.issues !== undefined) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tissues: [...syncResult.issues],\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { success: true, data: syncResult.value };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,UAAAA,MAAc,mBAGvB,IAAMC,EAAS,IAAID,EAAO,2BAA2B,EAa/BE,EAAf,KAAkF,CAC9E,MAAQ,IAAI,IAYZ,WAAWC,EAAoB,CACxC,OAAOA,EAAK,KACb,CAOU,YAAYA,EAAsB,CAC3C,OAAOA,EAAK,SAAS,IACtB,CAOA,SAASA,EAAoB,CAC5B,IAAMC,EAAM,KAAK,WAAWD,CAAI,EAC1BE,EAAO,KAAK,YAAYF,CAAI,EAElC,GAAI,KAAK,MAAM,IAAIC,CAAG,EAAG,CACxB,IAAME,EAAW,KAAK,MAAM,IAAIF,CAAG,EAC7BG,EAAeD,EAAW,KAAK,YAAYA,CAAQ,EAAI,UAC7DL,EAAO,KAAK,cAAc,KAAK,YAAY,KAAKG,CAAG,GAAI,CACtD,aAAcG,EACd,QAASF,CACV,CAAC,CACF,CAEA,KAAK,MAAM,IAAID,EAAKD,CAAI,EACxBF,EAAO,MAAM,cAAc,KAAK,YAAY,KAAKG,CAAG,GAAI,CACvD,KAAAC,CACD,CAAC,CACF,CAQA,IAAID,EAAoB,CACvB,OAAO,KAAK,MAAM,IAAIA,CAAG,CAC1B,CAQA,IAAI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ASF,EAAO,WAAW,EAAE,SAASC,CAAK,EACjD,GAAIC,GAAU,OAAQA,EAA4B,MAAS,WAC1D,MAAM,IAAI,MAAM,mEAAmE,EAEpF,GAAIA,IAAW,MAAQ,OAAOA,GAAW,SACxC,MAAM,IAAI,MAAM,uDAAuD,EAGxE,IAAMC,EAAaD,EAEnB,OAAIC,EAAW,SAAW,OAClB,CACN,QAAS,GACT,MAAO,CACN,OAAQ,CAAC,GAAGA,EAAW,MAAM,CAC9B,CACD,EAGM,CAAE,QAAS,GAAM,KAAMA,EAAW,KAAM,CAChD",
|
|
6
|
+
"names": ["Logger", "logger", "BaseRegistry", "item", "key", "name", "existing", "existingName", "assertStandardSchema", "schema", "context", "createRegistry", "kind", "registrations", "winners", "registration", "entries", "key", "all", "keys", "safeParseStandardSchema", "schema", "value", "result", "syncResult"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
export type StandardSchemaIssue = StandardSchemaV1.Issue;
|
|
3
|
+
export type StandardSchemaSafeParseResult<T> = {
|
|
4
|
+
success: true;
|
|
5
|
+
data: T;
|
|
6
|
+
} | {
|
|
7
|
+
success: false;
|
|
8
|
+
error: {
|
|
9
|
+
issues: StandardSchemaIssue[];
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Validate `value` with a Standard Schema without throwing.
|
|
14
|
+
*
|
|
15
|
+
* @param schema - Standard Schema to run
|
|
16
|
+
* @param value - Input to validate
|
|
17
|
+
* @throws {Error} When the schema validates asynchronously or returns a malformed result
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* Only synchronous validation is supported, because the callers (registry lookups, form validation,
|
|
21
|
+
* action parsing) need an immediate result.
|
|
22
|
+
*/
|
|
23
|
+
export declare function safeParseStandardSchema<TInput, TOutput>(schema: StandardSchemaV1<TInput, TOutput>, value: TInput): StandardSchemaSafeParseResult<TOutput>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function r(a,s){let e=a["~standard"].validate(s);if(e&&typeof e.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(e===null||typeof e!="object")throw new Error("Standard Schema validation returned an invalid result");let t=e;return t.issues!==void 0?{success:!1,error:{issues:[...t.issues]}}:{success:!0,data:t.value}}export{r as safeParseStandardSchema};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/standard-schema.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport type StandardSchemaIssue = StandardSchemaV1.Issue;\n\nexport type StandardSchemaSafeParseResult<T> =\n\t{ success: true; data: T } | { success: false; error: { issues: StandardSchemaIssue[] } };\n\n/**\n * Validate `value` with a Standard Schema without throwing.\n *\n * @param schema - Standard Schema to run\n * @param value - Input to validate\n * @throws {Error} When the schema validates asynchronously or returns a malformed result\n *\n * @remarks\n * Only synchronous validation is supported, because the callers (registry lookups, form validation,\n * action parsing) need an immediate result.\n */\nexport function safeParseStandardSchema<TInput, TOutput>(\n\tschema: StandardSchemaV1<TInput, TOutput>,\n\tvalue: TInput,\n): StandardSchemaSafeParseResult<TOutput> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\n\tconst syncResult = result as StandardSchemaV1.Result<TOutput>;\n\n\tif (syncResult.issues !== undefined) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tissues: [...syncResult.issues],\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { success: true, data: syncResult.value };\n}\n"],
|
|
5
|
+
"mappings": "AAkBO,SAASA,EACfC,EACAC,EACyC,CACzC,IAAMC,EAASF,EAAO,WAAW,EAAE,SAASC,CAAK,EACjD,GAAIC,GAAU,OAAQA,EAA4B,MAAS,WAC1D,MAAM,IAAI,MAAM,mEAAmE,EAEpF,GAAIA,IAAW,MAAQ,OAAOA,GAAW,SACxC,MAAM,IAAI,MAAM,uDAAuD,EAGxE,IAAMC,EAAaD,EAEnB,OAAIC,EAAW,SAAW,OAClB,CACN,QAAS,GACT,MAAO,CACN,OAAQ,CAAC,GAAGA,EAAW,MAAM,CAC9B,CACD,EAGM,CAAE,QAAS,GAAM,KAAMA,EAAW,KAAM,CAChD",
|
|
6
|
+
"names": ["safeParseStandardSchema", "schema", "value", "result", "syncResult"]
|
|
7
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
/**
|
|
3
|
+
* Universal metadata for all registrations.
|
|
4
|
+
*/
|
|
5
|
+
export interface RegistrationMetadata {
|
|
6
|
+
/** Human-readable display name */
|
|
7
|
+
name: string;
|
|
8
|
+
/** Detailed description of the component's purpose */
|
|
9
|
+
description?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Universal metadata for visual components.
|
|
13
|
+
*/
|
|
14
|
+
export interface ComponentMetadata extends RegistrationMetadata {
|
|
15
|
+
/** Icon identifier for UI display */
|
|
16
|
+
icon?: string;
|
|
17
|
+
/** Tags for filtering and searching */
|
|
18
|
+
tags?: string[];
|
|
19
|
+
/** Version of the component */
|
|
20
|
+
version?: string;
|
|
21
|
+
}
|
|
22
|
+
/** Brand symbol for compile-time type discrimination (erased at runtime) */
|
|
23
|
+
declare const __brand: unique symbol;
|
|
24
|
+
/**
|
|
25
|
+
* Phantom type brand - adds compile-time type identity without runtime cost.
|
|
26
|
+
*/
|
|
27
|
+
export type Brand<T, TBrand> = T & {
|
|
28
|
+
readonly [__brand]?: TBrand;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Base registration interface - common fields for all registration types.
|
|
32
|
+
*
|
|
33
|
+
* `schema` is the concrete Standard Schema value. Do not collapse it to
|
|
34
|
+
* `StandardSchemaV1<TConfig>`: that forces input and output to the same type
|
|
35
|
+
* and makes defaulted properties required at authoring time.
|
|
36
|
+
*/
|
|
37
|
+
export interface BaseRegistration<_TConfig = unknown, TMeta extends RegistrationMetadata = ComponentMetadata> {
|
|
38
|
+
/** Unique identifier - MUST be unique within its registry type. */
|
|
39
|
+
$type: string;
|
|
40
|
+
/** Standard Schema for config validation. Input and output remain distinct. */
|
|
41
|
+
schema: StandardSchemaV1;
|
|
42
|
+
/** Registration metadata (display name, description, and type-specific fields) */
|
|
43
|
+
metadata: TMeta;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Component registration interface.
|
|
47
|
+
* Foundation for all component registrations.
|
|
48
|
+
*/
|
|
49
|
+
export interface ComponentRegistration<TType extends string = string, TConfig = unknown, TProps = unknown, TMeta extends ComponentMetadata = ComponentMetadata> extends BaseRegistration<TConfig, TMeta> {
|
|
50
|
+
/** Framework-agnostic render function */
|
|
51
|
+
render: (props: TProps) => unknown;
|
|
52
|
+
/** Type identifier - enforced to match registry key */
|
|
53
|
+
$type: TType;
|
|
54
|
+
}
|
|
55
|
+
export {};
|
package/dist/types.js
ADDED
|
File without changes
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { YamlDocumentError, parseYaml, safeParseYaml } from './parse.js';
|
|
2
|
+
export type { YamlIssue, YamlParseOptions, YamlParseResult, YamlValidate } from './parse.js';
|
|
3
|
+
export { stringifyYaml } from './stringify.js';
|
|
4
|
+
export type { StringifyYamlOptions } from './stringify.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{LineCounter as P,isNode as I,parseDocument as L}from"yaml";var f=class extends Error{issues;constructor(n){super(n.length>0?n.map(M).join(`
|
|
2
|
+
`):"Invalid YAML document"),this.name="YamlDocumentError",this.issues=n}};function T(e){let n="";for(let t of e)typeof t=="number"?n+=`[${t}]`:n+=n?`.${String(t)}`:String(t);return n}function M(e){let n=e.filename?`${e.filename}:${e.line}:${e.column}`:`line ${e.line}, column ${e.column}`,t=T(e.path);return t?`${n} ${t}: ${e.message}`:`${n} ${e.message}`}function E(e){return typeof e=="object"?e.key:e}function A(e,n){for(let t=n.length;t>0;t--){let s=e.getIn(n.slice(0,t),!0);if(I(s)&&s.range)return s}return e.contents?.range?e.contents:null}var h=100;function v(e){return e.replace(/ at line \d+, column \d+:?[\s\S]*$/,"")}function x(e,n){return e!==void 0&&n!==void 0&&e.line===n.line&&e.col===n.col}function S(e){let n="tag:yaml.org,2002:";return e.startsWith(n)?`!!${e.slice(n.length)}`:e}function _(e){switch(e.code){case"MULTIPLE_DOCS":return"A file holds one document; remove the extra `---`.";case"MULTILINE_IMPLICIT_KEY":return"Bad indentation or a missing colon: line this up with the keys above it, or put the whole key on one line.";case"TAG_RESOLVE_FAILED":{let n=/Unresolved tag: (\S+)/.exec(e.message)?.[1];return`Tags are not supported: remove ${n?`${S(n)} `:""}and write the value plainly. Quote a string that looks like another type.`}default:return v(e.message)}}function $(e){let[n,t]=e.linePos??[];return(e.code==="MULTILINE_IMPLICIT_KEY"?t:n)??n??{line:1,col:1}}function k(e){let n=e.errors.filter(t=>t.code==="MULTILINE_IMPLICIT_KEY");return[...e.errors,...e.warnings].filter(t=>t.code!=="BLOCK_AS_IMPLICIT_KEY"||!n.some(s=>x(s.linePos?.[0],t.linePos?.[0]))).map(t=>({message:_(t),position:$(t)}))}function w(e){return e instanceof Error&&/alias count/i.test(e.message)?`The document has more than ${h} alias expansions (*name) in all. Write the repeated value out, or use fewer or smaller anchors.`:e instanceof Error?e.message:"The document could not be read"}function Y(e,n,t){let s=new P,l=e.charCodeAt(0)===65279?e.slice(1):e,i=L(l,{lineCounter:s,version:"1.2",schema:"core",resolveKnownTags:!1,merge:!0,stringKeys:!0}),r=(o,a,c,m)=>{let d={message:o,path:a,line:c,column:m};return t?.filename!==void 0&&(d.filename=t.filename),d},u=k(i);if(u.length>0)return{success:!1,issues:u.map(({message:o,position:a})=>r(o,[],a.line,a.col))};let y;try{y=i.toJS({maxAliasCount:h})}catch(o){return{success:!1,issues:[r(w(o),[],1,1)]}}let g=n(y);return g.success?{success:!0,data:g.data}:{success:!1,issues:g.issues.map(o=>{let a=(o.path??[]).map(E),c=A(i,a),m=c?.range?s.linePos(c.range[0]):{line:1,col:1};return r(o.message,a,m.line,m.col)})}}function O(e,n,t){let s=Y(e,n,t);if(!s.success)throw new f(s.issues);return s.data}import{Document as K,isPair as U,isScalar as p,visit as C}from"yaml";var D=3,b=48;function N(e){if(e.items.length===0||e.items.length>D)return!1;let n=0;for(let t of e.items){if(!p(t.key)||!p(t.value))return!1;let s=String(t.value.value);if(s.includes(`
|
|
3
|
+
`))return!1;n+=String(t.key.value).length+s.length+4}return n<=b}function W(e,n){let t=n?.schemaUrl;if(t!==void 0&&/[\r\n]/.test(t))throw new TypeError("schemaUrl must be a single line");let s=new K(e,{version:"1.2",aliasDuplicateObjects:!1});C(s,{Pair(i,r){p(r.key)&&r.key.value==="<<"&&(r.key.type="QUOTE_DOUBLE")},Map(i,r,u){U(u.at(-1))&&N(r)&&(r.flow=!0)}});let l=s.toString({lineWidth:0});return t===void 0?l:`# yaml-language-server: $schema=${t}
|
|
4
|
+
${l}`}export{f as YamlDocumentError,O as parseYaml,Y as safeParseYaml,W as stringifyYaml};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/yaml/parse.ts", "../../src/yaml/stringify.ts"],
|
|
4
|
+
"sourcesContent": ["import { LineCounter, isNode, parseDocument } from 'yaml';\nimport type { Document, Node, YAMLError, YAMLWarning } from 'yaml';\n\n/** One segment of a Standard Schema issue path: a key, or `{ key }` as Standard Schema allows. */\ntype PathSegment = PropertyKey | { readonly key: PropertyKey };\n\n/**\n * A validator for the parsed value, in the shape of Standard Schema issues. It must be synchronous.\n *\n * @remarks\n * `engine.safeValidateForm` from `@schema-engine/forms` fits as it is. For a Standard Schema\n * (`zod`, `valibot`, ...), wrap its `~standard.validate` and return `{ success: true, data }` or\n * `{ success: false, issues }`.\n */\nexport type YamlValidate<T> = (\n\tvalue: unknown,\n) =>\n\t| { success: true; data: T }\n\t| { success: false; issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<PathSegment> }> };\n\n/**\n * A problem found in a YAML document, placed in its source text.\n *\n * @remarks\n * `line` and `column` count from 1. For a validation issue they point at the start of the value the\n * `path` names; when the path names a key the document does not have, they point at the nearest\n * ancestor that exists. A syntax error has an empty `path` and the position the parser reports.\n */\nexport type YamlIssue = {\n\tmessage: string;\n\tpath: PropertyKey[];\n\tline: number;\n\tcolumn: number;\n\tfilename?: string;\n};\n\n/** What {@link safeParseYaml} returns: the validated data, or every issue found. */\nexport type YamlParseResult<T> = { success: true; data: T } | { success: false; issues: YamlIssue[] };\n\nexport type YamlParseOptions = {\n\t/** Name of the file the text came from; it prefixes error messages and is set on each issue. */\n\tfilename?: string;\n};\n\n/**\n * Thrown by {@link parseYaml} when the text is not valid YAML or its value does not validate.\n *\n * @remarks\n * `message` lists the issues one per line as `<file>:<line>:<column> <path>: <message>`, so a log\n * reads without parsing `issues`.\n */\nexport class YamlDocumentError extends Error {\n\treadonly issues: YamlIssue[];\n\n\tconstructor(issues: YamlIssue[]) {\n\t\tsuper(issues.length > 0 ? issues.map(formatIssue).join('\\n') : 'Invalid YAML document');\n\t\tthis.name = 'YamlDocumentError';\n\t\tthis.issues = issues;\n\t}\n}\n\n/** A path as it reads in an error message: `steps[0].elements[2].grid.width`. */\nfunction formatPath(path: PropertyKey[]): string {\n\tlet text = '';\n\tfor (const key of path) {\n\t\tif (typeof key === 'number') {\n\t\t\ttext += `[${key}]`;\n\t\t} else {\n\t\t\ttext += text ? `.${String(key)}` : String(key);\n\t\t}\n\t}\n\treturn text;\n}\n\nfunction formatIssue(issue: YamlIssue): string {\n\tconst location = issue.filename\n\t\t? `${issue.filename}:${issue.line}:${issue.column}`\n\t\t: `line ${issue.line}, column ${issue.column}`;\n\tconst path = formatPath(issue.path);\n\treturn path ? `${location} ${path}: ${issue.message}` : `${location} ${issue.message}`;\n}\n\nfunction toKey(segment: PathSegment): PropertyKey {\n\treturn typeof segment === 'object' ? segment.key : segment;\n}\n\n/**\n * The source node a path names, or the nearest ancestor that exists when the document lacks the\n * last keys of the path.\n */\nfunction nodeForPath(doc: Document.Parsed, path: PropertyKey[]): Node | null {\n\tfor (let length = path.length; length > 0; length--) {\n\t\tconst node = doc.getIn(path.slice(0, length), true);\n\t\tif (isNode(node) && node.range) {\n\t\t\treturn node;\n\t\t}\n\t}\n\treturn doc.contents?.range ? doc.contents : null;\n}\n\n/** The most alias expansions `toJS` allows before it gives up, which guards against alias bombs. */\nconst MAX_ALIAS_COUNT = 100;\n\n/** The parser's message without the ` at line N, column N:` suffix and the code frame it appends. */\nfunction syntaxMessage(message: string): string {\n\treturn message.replace(/ at line \\d+, column \\d+:?[\\s\\S]*$/, '');\n}\n\ntype Position = { line: number; col: number };\n\nfunction samePosition(a: Position | undefined, b: Position | undefined): boolean {\n\treturn a !== undefined && b !== undefined && a.line === b.line && a.col === b.col;\n}\n\n/** `tag:yaml.org,2002:float` as it is written in a document, `!!float`. */\nfunction shortTag(tag: string): string {\n\tconst prefix = 'tag:yaml.org,2002:';\n\treturn tag.startsWith(prefix) ? `!!${tag.slice(prefix.length)}` : tag;\n}\n\n/**\n * The message an author can act on. The parser's own text often advises changing a `yaml` API call,\n * which the author of a document cannot do.\n */\nfunction friendlyMessage(problem: YAMLError | YAMLWarning): string {\n\tswitch (problem.code) {\n\t\tcase 'MULTIPLE_DOCS':\n\t\t\treturn 'A file holds one document; remove the extra `---`.';\n\t\tcase 'MULTILINE_IMPLICIT_KEY':\n\t\t\treturn 'Bad indentation or a missing colon: line this up with the keys above it, or put the whole key on one line.';\n\t\tcase 'TAG_RESOLVE_FAILED': {\n\t\t\tconst tag = /Unresolved tag: (\\S+)/.exec(problem.message)?.[1];\n\t\t\tconst name = tag ? `${shortTag(tag)} ` : '';\n\t\t\treturn `Tags are not supported: remove ${name}and write the value plainly. Quote a string that looks like another type.`;\n\t\t}\n\t\tdefault:\n\t\t\treturn syntaxMessage(problem.message);\n\t}\n}\n\n/**\n * Where a parser problem is reported. A `MULTILINE_IMPLICIT_KEY` starts on the line above the\n * over-indented line that ends it, so it is reported at its end.\n */\nfunction positionOf(problem: YAMLError | YAMLWarning): Position {\n\tconst [start, end] = problem.linePos ?? [];\n\treturn (problem.code === 'MULTILINE_IMPLICIT_KEY' ? end : start) ?? start ?? { line: 1, col: 1 };\n}\n\n/**\n * Every parser error and warning. An over-indented line makes the parser report two errors from the\n * same place; the `BLOCK_AS_IMPLICIT_KEY` one is dropped.\n */\nfunction parserProblems(doc: Document.Parsed): Array<{ message: string; position: Position }> {\n\tconst multiline = doc.errors.filter((error) => error.code === 'MULTILINE_IMPLICIT_KEY');\n\treturn [...doc.errors, ...doc.warnings]\n\t\t.filter(\n\t\t\t(problem) =>\n\t\t\t\tproblem.code !== 'BLOCK_AS_IMPLICIT_KEY' ||\n\t\t\t\t!multiline.some((other) => samePosition(other.linePos?.[0], problem.linePos?.[0])),\n\t\t)\n\t\t.map((problem) => ({ message: friendlyMessage(problem), position: positionOf(problem) }));\n}\n\n/** The text of an error `toJS` throws, with the alias limit said in terms an author can use. */\nfunction conversionMessage(error: unknown): string {\n\tif (error instanceof Error && /alias count/i.test(error.message)) {\n\t\treturn `The document has more than ${MAX_ALIAS_COUNT} alias expansions (*name) in all. Write the repeated value out, or use fewer or smaller anchors.`;\n\t}\n\treturn error instanceof Error ? error.message : 'The document could not be read';\n}\n\n/**\n * Parse YAML text and validate the value, returning the issues instead of throwing.\n *\n * @param text A single YAML document, read as YAML 1.2 with the core schema: only `true`, `false`,\n * `null` and numbers are special, so `no`, `on` and `yes` stay strings. A leading byte order mark is\n * ignored.\n * @param validate Called with the parsed value, only when the text is valid YAML.\n * @returns `{ success: true, data }` with what `validate` returned, or `{ success: false, issues }`\n * with each syntax error or validation issue and its line and column.\n *\n * @remarks\n * An unquoted `1.10` is the number `1.1` in every YAML version; quote it (`\"1.10\"`) to keep a string.\n * Multiple documents in one text are a syntax error. Tags (`!!binary`, `!!set`, `!custom`) are\n * reported as issues, so what `validate` receives is always JSON-shaped. Mapping keys are read as\n * strings: `1: a` is `{ '1': 'a' }`.\n *\n * Anchors, aliases and merge keys (`<<: *defaults`) work within the text. A text with more than 100\n * alias expansions is reported as an issue at line 1, not thrown. An issue inside a merged value\n * points at the map that merges it, because the merged keys have no place of their own. A merge\n * source that is not a map (`<<: 5`) is reported at line 1, column 1.\n */\nexport function safeParseYaml<T>(\n\ttext: string,\n\tvalidate: YamlValidate<T>,\n\toptions?: YamlParseOptions,\n): YamlParseResult<T> {\n\tconst lineCounter = new LineCounter();\n\tconst source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n\tconst doc = parseDocument(source, {\n\t\tlineCounter,\n\t\tversion: '1.2',\n\t\tschema: 'core',\n\t\tresolveKnownTags: false,\n\t\tmerge: true,\n\t\tstringKeys: true,\n\t});\n\n\tconst issue = (message: string, path: PropertyKey[], line: number, column: number): YamlIssue => {\n\t\tconst found: YamlIssue = { message, path, line, column };\n\t\tif (options?.filename !== undefined) {\n\t\t\tfound.filename = options.filename;\n\t\t}\n\t\treturn found;\n\t};\n\n\tconst problems = parserProblems(doc);\n\tif (problems.length > 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: problems.map(({ message, position }) => issue(message, [], position.line, position.col)),\n\t\t};\n\t}\n\n\tlet value: unknown;\n\ttry {\n\t\tvalue = doc.toJS({ maxAliasCount: MAX_ALIAS_COUNT });\n\t} catch (error) {\n\t\treturn { success: false, issues: [issue(conversionMessage(error), [], 1, 1)] };\n\t}\n\n\tconst result = validate(value);\n\tif (result.success) {\n\t\treturn { success: true, data: result.data };\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\tissues: result.issues.map((found) => {\n\t\t\tconst path = (found.path ?? []).map(toKey);\n\t\t\tconst node = nodeForPath(doc, path);\n\t\t\tconst start = node?.range ? lineCounter.linePos(node.range[0]) : { line: 1, col: 1 };\n\t\t\treturn issue(found.message, path, start.line, start.col);\n\t\t}),\n\t};\n}\n\n/**\n * Parse YAML text and validate the value, throwing when either fails.\n *\n * @throws {YamlDocumentError} With each syntax error or validation issue and its line and column.\n * {@link safeParseYaml} returns them instead.\n */\nexport function parseYaml<T>(text: string, validate: YamlValidate<T>, options?: YamlParseOptions): T {\n\tconst result = safeParseYaml(text, validate, options);\n\tif (!result.success) {\n\t\tthrow new YamlDocumentError(result.issues);\n\t}\n\treturn result.data;\n}\n", "import { Document, isPair, isScalar, visit } from 'yaml';\nimport type { YAMLMap } from 'yaml';\n\n/**\n * Limits for a map written in flow style: scalar entries only, at most this many, and about this\n * many characters.\n *\n * @remarks\n * `grid: { width: half }` reads better inline; an element with many keys does not.\n */\nconst MAX_FLOW_ENTRIES = 3;\nconst MAX_FLOW_LENGTH = 48;\n\nexport type StringifyYamlOptions = {\n\t/** Adds a `# yaml-language-server: $schema=<url>` header, which editors read to offer completion. */\n\tschemaUrl?: string;\n};\n\nfunction isShortLeafMap(map: YAMLMap): boolean {\n\tif (map.items.length === 0 || map.items.length > MAX_FLOW_ENTRIES) {\n\t\treturn false;\n\t}\n\tlet length = 0;\n\tfor (const pair of map.items) {\n\t\tif (!isScalar(pair.key) || !isScalar(pair.value)) {\n\t\t\treturn false;\n\t\t}\n\t\tconst value = String(pair.value.value);\n\t\tif (value.includes('\\n')) {\n\t\t\treturn false;\n\t\t}\n\t\tlength += String(pair.key.value).length + value.length + 4;\n\t}\n\treturn length <= MAX_FLOW_LENGTH;\n}\n\n/**\n * Write a value as YAML text.\n *\n * @remarks\n * An object that appears twice is written out twice, not as an anchor and an alias. A short map of\n * scalars under a key is written in flow style (`grid: { width: half }`); every other collection,\n * including a sequence item, is written in block style. Lines are not folded.\n * Strings that would read as another type are quoted, so `\"1.10\"` stays a string when parsed back,\n * and so is a key named `<<`, which `parseYaml` would otherwise read as a merge key.\n * `no` and `on` are not quoted, because YAML 1.2 reads them as strings; a YAML 1.1 reader would not.\n */\nexport function stringifyYaml(value: unknown, options?: StringifyYamlOptions): string {\n\tconst schemaUrl = options?.schemaUrl;\n\tif (schemaUrl !== undefined && /[\\r\\n]/.test(schemaUrl)) {\n\t\tthrow new TypeError('schemaUrl must be a single line');\n\t}\n\tconst doc = new Document(value, { version: '1.2', aliasDuplicateObjects: false });\n\tvisit(doc, {\n\t\tPair(_key, pair) {\n\t\t\tif (isScalar(pair.key) && pair.key.value === '<<') {\n\t\t\t\tpair.key.type = 'QUOTE_DOUBLE';\n\t\t\t}\n\t\t},\n\t\tMap(_key, map, path) {\n\t\t\tif (isPair(path.at(-1)) && isShortLeafMap(map)) {\n\t\t\t\tmap.flow = true;\n\t\t\t}\n\t\t},\n\t});\n\tconst text = doc.toString({ lineWidth: 0 });\n\treturn schemaUrl === undefined ? text : `# yaml-language-server: $schema=${schemaUrl}\\n${text}`;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,eAAAA,EAAa,UAAAC,EAAQ,iBAAAC,MAAqB,OAmD5C,IAAMC,EAAN,cAAgC,KAAM,CACnC,OAET,YAAYC,EAAqB,CAChC,MAAMA,EAAO,OAAS,EAAIA,EAAO,IAAIC,CAAW,EAAE,KAAK;AAAA,CAAI,EAAI,uBAAuB,EACtF,KAAK,KAAO,oBACZ,KAAK,OAASD,CACf,CACD,EAGA,SAASE,EAAWC,EAA6B,CAChD,IAAIC,EAAO,GACX,QAAWC,KAAOF,EACb,OAAOE,GAAQ,SAClBD,GAAQ,IAAIC,CAAG,IAEfD,GAAQA,EAAO,IAAI,OAAOC,CAAG,CAAC,GAAK,OAAOA,CAAG,EAG/C,OAAOD,CACR,CAEA,SAASH,EAAYK,EAA0B,CAC9C,IAAMC,EAAWD,EAAM,SACpB,GAAGA,EAAM,QAAQ,IAAIA,EAAM,IAAI,IAAIA,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L,EAASO,EAAK,GAAG,GAAK,CAACP,EAASO,EAAK,KAAK,EAC9C,MAAO,GAER,IAAMC,EAAQ,OAAOD,EAAK,MAAM,KAAK,EACrC,GAAIC,EAAM,SAAS;AAAA,CAAI,EACtB,MAAO,GAERF,GAAU,OAAOC,EAAK,IAAI,KAAK,EAAE,OAASC,EAAM,OAAS,CAC1D,CACA,OAAOF,GAAUH,CAClB,CAaO,SAASM,EAAcD,EAAgBE,EAAwC,CACrF,IAAMC,EAAYD,GAAS,UAC3B,GAAIC,IAAc,QAAa,SAAS,KAAKA,CAAS,EACrD,MAAM,IAAI,UAAU,iCAAiC,EAEtD,IAAMC,EAAM,IAAId,EAASU,EAAO,CAAE,QAAS,MAAO,sBAAuB,EAAM,CAAC,EAChFP,EAAMW,EAAK,CACV,KAAKC,EAAMN,EAAM,CACZP,EAASO,EAAK,GAAG,GAAKA,EAAK,IAAI,QAAU,OAC5CA,EAAK,IAAI,KAAO,eAElB,EACA,IAAIM,EAAMR,EAAKS,EAAM,CAChBf,EAAOe,EAAK,GAAG,EAAE,CAAC,GAAKV,EAAeC,CAAG,IAC5CA,EAAI,KAAO,GAEb,CACD,CAAC,EACD,IAAMU,EAAOH,EAAI,SAAS,CAAE,UAAW,CAAE,CAAC,EAC1C,OAAOD,IAAc,OAAYI,EAAO,mCAAmCJ,CAAS;AAAA,EAAKI,CAAI,EAC9F",
|
|
6
|
+
"names": ["LineCounter", "isNode", "parseDocument", "YamlDocumentError", "issues", "formatIssue", "formatPath", "path", "text", "key", "issue", "location", "toKey", "segment", "nodeForPath", "doc", "length", "node", "MAX_ALIAS_COUNT", "syntaxMessage", "message", "samePosition", "a", "b", "shortTag", "tag", "prefix", "friendlyMessage", "problem", "positionOf", "start", "end", "parserProblems", "multiline", "error", "other", "conversionMessage", "safeParseYaml", "validate", "options", "lineCounter", "source", "line", "column", "found", "problems", "position", "value", "result", "parseYaml", "Document", "isPair", "isScalar", "visit", "MAX_FLOW_ENTRIES", "MAX_FLOW_LENGTH", "isShortLeafMap", "map", "length", "pair", "value", "stringifyYaml", "options", "schemaUrl", "doc", "_key", "path", "text"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** One segment of a Standard Schema issue path: a key, or `{ key }` as Standard Schema allows. */
|
|
2
|
+
type PathSegment = PropertyKey | {
|
|
3
|
+
readonly key: PropertyKey;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* A validator for the parsed value, in the shape of Standard Schema issues. It must be synchronous.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* `engine.safeValidateForm` from `@schema-engine/forms` fits as it is. For a Standard Schema
|
|
10
|
+
* (`zod`, `valibot`, ...), wrap its `~standard.validate` and return `{ success: true, data }` or
|
|
11
|
+
* `{ success: false, issues }`.
|
|
12
|
+
*/
|
|
13
|
+
export type YamlValidate<T> = (value: unknown) => {
|
|
14
|
+
success: true;
|
|
15
|
+
data: T;
|
|
16
|
+
} | {
|
|
17
|
+
success: false;
|
|
18
|
+
issues: ReadonlyArray<{
|
|
19
|
+
message: string;
|
|
20
|
+
path?: ReadonlyArray<PathSegment>;
|
|
21
|
+
}>;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A problem found in a YAML document, placed in its source text.
|
|
25
|
+
*
|
|
26
|
+
* @remarks
|
|
27
|
+
* `line` and `column` count from 1. For a validation issue they point at the start of the value the
|
|
28
|
+
* `path` names; when the path names a key the document does not have, they point at the nearest
|
|
29
|
+
* ancestor that exists. A syntax error has an empty `path` and the position the parser reports.
|
|
30
|
+
*/
|
|
31
|
+
export type YamlIssue = {
|
|
32
|
+
message: string;
|
|
33
|
+
path: PropertyKey[];
|
|
34
|
+
line: number;
|
|
35
|
+
column: number;
|
|
36
|
+
filename?: string;
|
|
37
|
+
};
|
|
38
|
+
/** What {@link safeParseYaml} returns: the validated data, or every issue found. */
|
|
39
|
+
export type YamlParseResult<T> = {
|
|
40
|
+
success: true;
|
|
41
|
+
data: T;
|
|
42
|
+
} | {
|
|
43
|
+
success: false;
|
|
44
|
+
issues: YamlIssue[];
|
|
45
|
+
};
|
|
46
|
+
export type YamlParseOptions = {
|
|
47
|
+
/** Name of the file the text came from; it prefixes error messages and is set on each issue. */
|
|
48
|
+
filename?: string;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Thrown by {@link parseYaml} when the text is not valid YAML or its value does not validate.
|
|
52
|
+
*
|
|
53
|
+
* @remarks
|
|
54
|
+
* `message` lists the issues one per line as `<file>:<line>:<column> <path>: <message>`, so a log
|
|
55
|
+
* reads without parsing `issues`.
|
|
56
|
+
*/
|
|
57
|
+
export declare class YamlDocumentError extends Error {
|
|
58
|
+
readonly issues: YamlIssue[];
|
|
59
|
+
constructor(issues: YamlIssue[]);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Parse YAML text and validate the value, returning the issues instead of throwing.
|
|
63
|
+
*
|
|
64
|
+
* @param text A single YAML document, read as YAML 1.2 with the core schema: only `true`, `false`,
|
|
65
|
+
* `null` and numbers are special, so `no`, `on` and `yes` stay strings. A leading byte order mark is
|
|
66
|
+
* ignored.
|
|
67
|
+
* @param validate Called with the parsed value, only when the text is valid YAML.
|
|
68
|
+
* @returns `{ success: true, data }` with what `validate` returned, or `{ success: false, issues }`
|
|
69
|
+
* with each syntax error or validation issue and its line and column.
|
|
70
|
+
*
|
|
71
|
+
* @remarks
|
|
72
|
+
* An unquoted `1.10` is the number `1.1` in every YAML version; quote it (`"1.10"`) to keep a string.
|
|
73
|
+
* Multiple documents in one text are a syntax error. Tags (`!!binary`, `!!set`, `!custom`) are
|
|
74
|
+
* reported as issues, so what `validate` receives is always JSON-shaped. Mapping keys are read as
|
|
75
|
+
* strings: `1: a` is `{ '1': 'a' }`.
|
|
76
|
+
*
|
|
77
|
+
* Anchors, aliases and merge keys (`<<: *defaults`) work within the text. A text with more than 100
|
|
78
|
+
* alias expansions is reported as an issue at line 1, not thrown. An issue inside a merged value
|
|
79
|
+
* points at the map that merges it, because the merged keys have no place of their own. A merge
|
|
80
|
+
* source that is not a map (`<<: 5`) is reported at line 1, column 1.
|
|
81
|
+
*/
|
|
82
|
+
export declare function safeParseYaml<T>(text: string, validate: YamlValidate<T>, options?: YamlParseOptions): YamlParseResult<T>;
|
|
83
|
+
/**
|
|
84
|
+
* Parse YAML text and validate the value, throwing when either fails.
|
|
85
|
+
*
|
|
86
|
+
* @throws {YamlDocumentError} With each syntax error or validation issue and its line and column.
|
|
87
|
+
* {@link safeParseYaml} returns them instead.
|
|
88
|
+
*/
|
|
89
|
+
export declare function parseYaml<T>(text: string, validate: YamlValidate<T>, options?: YamlParseOptions): T;
|
|
90
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LineCounter as h,isNode as P,parseDocument as I}from"yaml";var m=class extends Error{issues;constructor(n){super(n.length>0?n.map(T).join(`
|
|
2
|
+
`):"Invalid YAML document"),this.name="YamlDocumentError",this.issues=n}};function Y(e){let n="";for(let t of e)typeof t=="number"?n+=`[${t}]`:n+=n?`.${String(t)}`:String(t);return n}function T(e){let n=e.filename?`${e.filename}:${e.line}:${e.column}`:`line ${e.line}, column ${e.column}`,t=Y(e.path);return t?`${n} ${t}: ${e.message}`:`${n} ${e.message}`}function L(e){return typeof e=="object"?e.key:e}function A(e,n){for(let t=n.length;t>0;t--){let s=e.getIn(n.slice(0,t),!0);if(P(s)&&s.range)return s}return e.contents?.range?e.contents:null}var p=100;function M(e){return e.replace(/ at line \d+, column \d+:?[\s\S]*$/,"")}function E(e,n){return e!==void 0&&n!==void 0&&e.line===n.line&&e.col===n.col}function $(e){let n="tag:yaml.org,2002:";return e.startsWith(n)?`!!${e.slice(n.length)}`:e}function K(e){switch(e.code){case"MULTIPLE_DOCS":return"A file holds one document; remove the extra `---`.";case"MULTILINE_IMPLICIT_KEY":return"Bad indentation or a missing colon: line this up with the keys above it, or put the whole key on one line.";case"TAG_RESOLVE_FAILED":{let n=/Unresolved tag: (\S+)/.exec(e.message)?.[1];return`Tags are not supported: remove ${n?`${$(n)} `:""}and write the value plainly. Quote a string that looks like another type.`}default:return M(e.message)}}function x(e){let[n,t]=e.linePos??[];return(e.code==="MULTILINE_IMPLICIT_KEY"?t:n)??n??{line:1,col:1}}function _(e){let n=e.errors.filter(t=>t.code==="MULTILINE_IMPLICIT_KEY");return[...e.errors,...e.warnings].filter(t=>t.code!=="BLOCK_AS_IMPLICIT_KEY"||!n.some(s=>E(s.linePos?.[0],t.linePos?.[0]))).map(t=>({message:K(t),position:x(t)}))}function w(e){return e instanceof Error&&/alias count/i.test(e.message)?`The document has more than ${p} alias expansions (*name) in all. Write the repeated value out, or use fewer or smaller anchors.`:e instanceof Error?e.message:"The document could not be read"}function v(e,n,t){let s=new h,y=e.charCodeAt(0)===65279?e.slice(1):e,l=I(y,{lineCounter:s,version:"1.2",schema:"core",resolveKnownTags:!1,merge:!0,stringKeys:!0}),u=(r,o,a,i)=>{let d={message:r,path:o,line:a,column:i};return t?.filename!==void 0&&(d.filename=t.filename),d},f=_(l);if(f.length>0)return{success:!1,issues:f.map(({message:r,position:o})=>u(r,[],o.line,o.col))};let g;try{g=l.toJS({maxAliasCount:p})}catch(r){return{success:!1,issues:[u(w(r),[],1,1)]}}let c=n(g);return c.success?{success:!0,data:c.data}:{success:!1,issues:c.issues.map(r=>{let o=(r.path??[]).map(L),a=A(l,o),i=a?.range?s.linePos(a.range[0]):{line:1,col:1};return u(r.message,o,i.line,i.col)})}}function C(e,n,t){let s=v(e,n,t);if(!s.success)throw new m(s.issues);return s.data}export{m as YamlDocumentError,C as parseYaml,v as safeParseYaml};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/yaml/parse.ts"],
|
|
4
|
+
"sourcesContent": ["import { LineCounter, isNode, parseDocument } from 'yaml';\nimport type { Document, Node, YAMLError, YAMLWarning } from 'yaml';\n\n/** One segment of a Standard Schema issue path: a key, or `{ key }` as Standard Schema allows. */\ntype PathSegment = PropertyKey | { readonly key: PropertyKey };\n\n/**\n * A validator for the parsed value, in the shape of Standard Schema issues. It must be synchronous.\n *\n * @remarks\n * `engine.safeValidateForm` from `@schema-engine/forms` fits as it is. For a Standard Schema\n * (`zod`, `valibot`, ...), wrap its `~standard.validate` and return `{ success: true, data }` or\n * `{ success: false, issues }`.\n */\nexport type YamlValidate<T> = (\n\tvalue: unknown,\n) =>\n\t| { success: true; data: T }\n\t| { success: false; issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<PathSegment> }> };\n\n/**\n * A problem found in a YAML document, placed in its source text.\n *\n * @remarks\n * `line` and `column` count from 1. For a validation issue they point at the start of the value the\n * `path` names; when the path names a key the document does not have, they point at the nearest\n * ancestor that exists. A syntax error has an empty `path` and the position the parser reports.\n */\nexport type YamlIssue = {\n\tmessage: string;\n\tpath: PropertyKey[];\n\tline: number;\n\tcolumn: number;\n\tfilename?: string;\n};\n\n/** What {@link safeParseYaml} returns: the validated data, or every issue found. */\nexport type YamlParseResult<T> = { success: true; data: T } | { success: false; issues: YamlIssue[] };\n\nexport type YamlParseOptions = {\n\t/** Name of the file the text came from; it prefixes error messages and is set on each issue. */\n\tfilename?: string;\n};\n\n/**\n * Thrown by {@link parseYaml} when the text is not valid YAML or its value does not validate.\n *\n * @remarks\n * `message` lists the issues one per line as `<file>:<line>:<column> <path>: <message>`, so a log\n * reads without parsing `issues`.\n */\nexport class YamlDocumentError extends Error {\n\treadonly issues: YamlIssue[];\n\n\tconstructor(issues: YamlIssue[]) {\n\t\tsuper(issues.length > 0 ? issues.map(formatIssue).join('\\n') : 'Invalid YAML document');\n\t\tthis.name = 'YamlDocumentError';\n\t\tthis.issues = issues;\n\t}\n}\n\n/** A path as it reads in an error message: `steps[0].elements[2].grid.width`. */\nfunction formatPath(path: PropertyKey[]): string {\n\tlet text = '';\n\tfor (const key of path) {\n\t\tif (typeof key === 'number') {\n\t\t\ttext += `[${key}]`;\n\t\t} else {\n\t\t\ttext += text ? `.${String(key)}` : String(key);\n\t\t}\n\t}\n\treturn text;\n}\n\nfunction formatIssue(issue: YamlIssue): string {\n\tconst location = issue.filename\n\t\t? `${issue.filename}:${issue.line}:${issue.column}`\n\t\t: `line ${issue.line}, column ${issue.column}`;\n\tconst path = formatPath(issue.path);\n\treturn path ? `${location} ${path}: ${issue.message}` : `${location} ${issue.message}`;\n}\n\nfunction toKey(segment: PathSegment): PropertyKey {\n\treturn typeof segment === 'object' ? segment.key : segment;\n}\n\n/**\n * The source node a path names, or the nearest ancestor that exists when the document lacks the\n * last keys of the path.\n */\nfunction nodeForPath(doc: Document.Parsed, path: PropertyKey[]): Node | null {\n\tfor (let length = path.length; length > 0; length--) {\n\t\tconst node = doc.getIn(path.slice(0, length), true);\n\t\tif (isNode(node) && node.range) {\n\t\t\treturn node;\n\t\t}\n\t}\n\treturn doc.contents?.range ? doc.contents : null;\n}\n\n/** The most alias expansions `toJS` allows before it gives up, which guards against alias bombs. */\nconst MAX_ALIAS_COUNT = 100;\n\n/** The parser's message without the ` at line N, column N:` suffix and the code frame it appends. */\nfunction syntaxMessage(message: string): string {\n\treturn message.replace(/ at line \\d+, column \\d+:?[\\s\\S]*$/, '');\n}\n\ntype Position = { line: number; col: number };\n\nfunction samePosition(a: Position | undefined, b: Position | undefined): boolean {\n\treturn a !== undefined && b !== undefined && a.line === b.line && a.col === b.col;\n}\n\n/** `tag:yaml.org,2002:float` as it is written in a document, `!!float`. */\nfunction shortTag(tag: string): string {\n\tconst prefix = 'tag:yaml.org,2002:';\n\treturn tag.startsWith(prefix) ? `!!${tag.slice(prefix.length)}` : tag;\n}\n\n/**\n * The message an author can act on. The parser's own text often advises changing a `yaml` API call,\n * which the author of a document cannot do.\n */\nfunction friendlyMessage(problem: YAMLError | YAMLWarning): string {\n\tswitch (problem.code) {\n\t\tcase 'MULTIPLE_DOCS':\n\t\t\treturn 'A file holds one document; remove the extra `---`.';\n\t\tcase 'MULTILINE_IMPLICIT_KEY':\n\t\t\treturn 'Bad indentation or a missing colon: line this up with the keys above it, or put the whole key on one line.';\n\t\tcase 'TAG_RESOLVE_FAILED': {\n\t\t\tconst tag = /Unresolved tag: (\\S+)/.exec(problem.message)?.[1];\n\t\t\tconst name = tag ? `${shortTag(tag)} ` : '';\n\t\t\treturn `Tags are not supported: remove ${name}and write the value plainly. Quote a string that looks like another type.`;\n\t\t}\n\t\tdefault:\n\t\t\treturn syntaxMessage(problem.message);\n\t}\n}\n\n/**\n * Where a parser problem is reported. A `MULTILINE_IMPLICIT_KEY` starts on the line above the\n * over-indented line that ends it, so it is reported at its end.\n */\nfunction positionOf(problem: YAMLError | YAMLWarning): Position {\n\tconst [start, end] = problem.linePos ?? [];\n\treturn (problem.code === 'MULTILINE_IMPLICIT_KEY' ? end : start) ?? start ?? { line: 1, col: 1 };\n}\n\n/**\n * Every parser error and warning. An over-indented line makes the parser report two errors from the\n * same place; the `BLOCK_AS_IMPLICIT_KEY` one is dropped.\n */\nfunction parserProblems(doc: Document.Parsed): Array<{ message: string; position: Position }> {\n\tconst multiline = doc.errors.filter((error) => error.code === 'MULTILINE_IMPLICIT_KEY');\n\treturn [...doc.errors, ...doc.warnings]\n\t\t.filter(\n\t\t\t(problem) =>\n\t\t\t\tproblem.code !== 'BLOCK_AS_IMPLICIT_KEY' ||\n\t\t\t\t!multiline.some((other) => samePosition(other.linePos?.[0], problem.linePos?.[0])),\n\t\t)\n\t\t.map((problem) => ({ message: friendlyMessage(problem), position: positionOf(problem) }));\n}\n\n/** The text of an error `toJS` throws, with the alias limit said in terms an author can use. */\nfunction conversionMessage(error: unknown): string {\n\tif (error instanceof Error && /alias count/i.test(error.message)) {\n\t\treturn `The document has more than ${MAX_ALIAS_COUNT} alias expansions (*name) in all. Write the repeated value out, or use fewer or smaller anchors.`;\n\t}\n\treturn error instanceof Error ? error.message : 'The document could not be read';\n}\n\n/**\n * Parse YAML text and validate the value, returning the issues instead of throwing.\n *\n * @param text A single YAML document, read as YAML 1.2 with the core schema: only `true`, `false`,\n * `null` and numbers are special, so `no`, `on` and `yes` stay strings. A leading byte order mark is\n * ignored.\n * @param validate Called with the parsed value, only when the text is valid YAML.\n * @returns `{ success: true, data }` with what `validate` returned, or `{ success: false, issues }`\n * with each syntax error or validation issue and its line and column.\n *\n * @remarks\n * An unquoted `1.10` is the number `1.1` in every YAML version; quote it (`\"1.10\"`) to keep a string.\n * Multiple documents in one text are a syntax error. Tags (`!!binary`, `!!set`, `!custom`) are\n * reported as issues, so what `validate` receives is always JSON-shaped. Mapping keys are read as\n * strings: `1: a` is `{ '1': 'a' }`.\n *\n * Anchors, aliases and merge keys (`<<: *defaults`) work within the text. A text with more than 100\n * alias expansions is reported as an issue at line 1, not thrown. An issue inside a merged value\n * points at the map that merges it, because the merged keys have no place of their own. A merge\n * source that is not a map (`<<: 5`) is reported at line 1, column 1.\n */\nexport function safeParseYaml<T>(\n\ttext: string,\n\tvalidate: YamlValidate<T>,\n\toptions?: YamlParseOptions,\n): YamlParseResult<T> {\n\tconst lineCounter = new LineCounter();\n\tconst source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n\tconst doc = parseDocument(source, {\n\t\tlineCounter,\n\t\tversion: '1.2',\n\t\tschema: 'core',\n\t\tresolveKnownTags: false,\n\t\tmerge: true,\n\t\tstringKeys: true,\n\t});\n\n\tconst issue = (message: string, path: PropertyKey[], line: number, column: number): YamlIssue => {\n\t\tconst found: YamlIssue = { message, path, line, column };\n\t\tif (options?.filename !== undefined) {\n\t\t\tfound.filename = options.filename;\n\t\t}\n\t\treturn found;\n\t};\n\n\tconst problems = parserProblems(doc);\n\tif (problems.length > 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: problems.map(({ message, position }) => issue(message, [], position.line, position.col)),\n\t\t};\n\t}\n\n\tlet value: unknown;\n\ttry {\n\t\tvalue = doc.toJS({ maxAliasCount: MAX_ALIAS_COUNT });\n\t} catch (error) {\n\t\treturn { success: false, issues: [issue(conversionMessage(error), [], 1, 1)] };\n\t}\n\n\tconst result = validate(value);\n\tif (result.success) {\n\t\treturn { success: true, data: result.data };\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\tissues: result.issues.map((found) => {\n\t\t\tconst path = (found.path ?? []).map(toKey);\n\t\t\tconst node = nodeForPath(doc, path);\n\t\t\tconst start = node?.range ? lineCounter.linePos(node.range[0]) : { line: 1, col: 1 };\n\t\t\treturn issue(found.message, path, start.line, start.col);\n\t\t}),\n\t};\n}\n\n/**\n * Parse YAML text and validate the value, throwing when either fails.\n *\n * @throws {YamlDocumentError} With each syntax error or validation issue and its line and column.\n * {@link safeParseYaml} returns them instead.\n */\nexport function parseYaml<T>(text: string, validate: YamlValidate<T>, options?: YamlParseOptions): T {\n\tconst result = safeParseYaml(text, validate, options);\n\tif (!result.success) {\n\t\tthrow new YamlDocumentError(result.issues);\n\t}\n\treturn result.data;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,eAAAA,EAAa,UAAAC,EAAQ,iBAAAC,MAAqB,OAmD5C,IAAMC,EAAN,cAAgC,KAAM,CACnC,OAET,YAAYC,EAAqB,CAChC,MAAMA,EAAO,OAAS,EAAIA,EAAO,IAAIC,CAAW,EAAE,KAAK;AAAA,CAAI,EAAI,uBAAuB,EACtF,KAAK,KAAO,oBACZ,KAAK,OAASD,CACf,CACD,EAGA,SAASE,EAAWC,EAA6B,CAChD,IAAIC,EAAO,GACX,QAAWC,KAAOF,EACb,OAAOE,GAAQ,SAClBD,GAAQ,IAAIC,CAAG,IAEfD,GAAQA,EAAO,IAAI,OAAOC,CAAG,CAAC,GAAK,OAAOA,CAAG,EAG/C,OAAOD,CACR,CAEA,SAASH,EAAYK,EAA0B,CAC9C,IAAMC,EAAWD,EAAM,SACpB,GAAGA,EAAM,QAAQ,IAAIA,EAAM,IAAI,IAAIA,EAAM,MAAM,GAC/C,QAAQA,EAAM,IAAI,YAAYA,EAAM,MAAM,GACvCH,EAAOD,EAAWI,EAAM,IAAI,EAClC,OA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,EAAS,GAAG,CAAC,CAChG,EAGD,IAAIC,EACJ,GAAI,CACHA,EAAQhC,EAAI,KAAK,CAAE,cAAeG,CAAgB,CAAC,CACpD,OAASgB,EAAO,CACf,MAAO,CAAE,QAAS,GAAO,OAAQ,CAACxB,EAAM0B,EAAkBF,CAAK,EAAG,CAAC,EAAG,EAAG,CAAC,CAAC,CAAE,CAC9E,CAEA,IAAMc,EAASV,EAASS,CAAK,EAC7B,OAAIC,EAAO,QACH,CAAE,QAAS,GAAM,KAAMA,EAAO,IAAK,EAEpC,CACN,QAAS,GACT,OAAQA,EAAO,OAAO,IAAKJ,GAAU,CACpC,IAAMrC,GAAQqC,EAAM,MAAQ,CAAC,GAAG,IAAIhC,CAAK,EACnCK,EAAOH,EAAYC,EAAKR,CAAI,EAC5BuB,EAAQb,GAAM,MAAQuB,EAAY,QAAQvB,EAAK,MAAM,CAAC,CAAC,EAAI,CAAE,KAAM,EAAG,IAAK,CAAE,EACnF,OAAOP,EAAMkC,EAAM,QAASrC,EAAMuB,EAAM,KAAMA,EAAM,GAAG,CACxD,CAAC,CACF,CACD,CAQO,SAASmB,EAAazC,EAAc8B,EAA2BC,EAA+B,CACpG,IAAMS,EAASX,EAAc7B,EAAM8B,EAAUC,CAAO,EACpD,GAAI,CAACS,EAAO,QACX,MAAM,IAAI7C,EAAkB6C,EAAO,MAAM,EAE1C,OAAOA,EAAO,IACf",
|
|
6
|
+
"names": ["LineCounter", "isNode", "parseDocument", "YamlDocumentError", "issues", "formatIssue", "formatPath", "path", "text", "key", "issue", "location", "toKey", "segment", "nodeForPath", "doc", "length", "node", "MAX_ALIAS_COUNT", "syntaxMessage", "message", "samePosition", "a", "b", "shortTag", "tag", "prefix", "friendlyMessage", "problem", "positionOf", "start", "end", "parserProblems", "multiline", "error", "other", "conversionMessage", "safeParseYaml", "validate", "options", "lineCounter", "source", "line", "column", "found", "problems", "position", "value", "result", "parseYaml"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type StringifyYamlOptions = {
|
|
2
|
+
/** Adds a `# yaml-language-server: $schema=<url>` header, which editors read to offer completion. */
|
|
3
|
+
schemaUrl?: string;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* Write a value as YAML text.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* An object that appears twice is written out twice, not as an anchor and an alias. A short map of
|
|
10
|
+
* scalars under a key is written in flow style (`grid: { width: half }`); every other collection,
|
|
11
|
+
* including a sequence item, is written in block style. Lines are not folded.
|
|
12
|
+
* Strings that would read as another type are quoted, so `"1.10"` stays a string when parsed back,
|
|
13
|
+
* and so is a key named `<<`, which `parseYaml` would otherwise read as a merge key.
|
|
14
|
+
* `no` and `on` are not quoted, because YAML 1.2 reads them as strings; a YAML 1.1 reader would not.
|
|
15
|
+
*/
|
|
16
|
+
export declare function stringifyYaml(value: unknown, options?: StringifyYamlOptions): string;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Document as f,isPair as u,isScalar as s,visit as c}from"yaml";var g=3,m=48;function y(n){if(n.items.length===0||n.items.length>g)return!1;let r=0;for(let e of n.items){if(!s(e.key)||!s(e.value))return!1;let i=String(e.value.value);if(i.includes(`
|
|
2
|
+
`))return!1;r+=String(e.key.value).length+i.length+4}return r<=m}function p(n,r){let e=r?.schemaUrl;if(e!==void 0&&/[\r\n]/.test(e))throw new TypeError("schemaUrl must be a single line");let i=new f(n,{version:"1.2",aliasDuplicateObjects:!1});c(i,{Pair(a,t){s(t.key)&&t.key.value==="<<"&&(t.key.type="QUOTE_DOUBLE")},Map(a,t,o){u(o.at(-1))&&y(t)&&(t.flow=!0)}});let l=i.toString({lineWidth:0});return e===void 0?l:`# yaml-language-server: $schema=${e}
|
|
3
|
+
${l}`}export{p as stringifyYaml};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/yaml/stringify.ts"],
|
|
4
|
+
"sourcesContent": ["import { Document, isPair, isScalar, visit } from 'yaml';\nimport type { YAMLMap } from 'yaml';\n\n/**\n * Limits for a map written in flow style: scalar entries only, at most this many, and about this\n * many characters.\n *\n * @remarks\n * `grid: { width: half }` reads better inline; an element with many keys does not.\n */\nconst MAX_FLOW_ENTRIES = 3;\nconst MAX_FLOW_LENGTH = 48;\n\nexport type StringifyYamlOptions = {\n\t/** Adds a `# yaml-language-server: $schema=<url>` header, which editors read to offer completion. */\n\tschemaUrl?: string;\n};\n\nfunction isShortLeafMap(map: YAMLMap): boolean {\n\tif (map.items.length === 0 || map.items.length > MAX_FLOW_ENTRIES) {\n\t\treturn false;\n\t}\n\tlet length = 0;\n\tfor (const pair of map.items) {\n\t\tif (!isScalar(pair.key) || !isScalar(pair.value)) {\n\t\t\treturn false;\n\t\t}\n\t\tconst value = String(pair.value.value);\n\t\tif (value.includes('\\n')) {\n\t\t\treturn false;\n\t\t}\n\t\tlength += String(pair.key.value).length + value.length + 4;\n\t}\n\treturn length <= MAX_FLOW_LENGTH;\n}\n\n/**\n * Write a value as YAML text.\n *\n * @remarks\n * An object that appears twice is written out twice, not as an anchor and an alias. A short map of\n * scalars under a key is written in flow style (`grid: { width: half }`); every other collection,\n * including a sequence item, is written in block style. Lines are not folded.\n * Strings that would read as another type are quoted, so `\"1.10\"` stays a string when parsed back,\n * and so is a key named `<<`, which `parseYaml` would otherwise read as a merge key.\n * `no` and `on` are not quoted, because YAML 1.2 reads them as strings; a YAML 1.1 reader would not.\n */\nexport function stringifyYaml(value: unknown, options?: StringifyYamlOptions): string {\n\tconst schemaUrl = options?.schemaUrl;\n\tif (schemaUrl !== undefined && /[\\r\\n]/.test(schemaUrl)) {\n\t\tthrow new TypeError('schemaUrl must be a single line');\n\t}\n\tconst doc = new Document(value, { version: '1.2', aliasDuplicateObjects: false });\n\tvisit(doc, {\n\t\tPair(_key, pair) {\n\t\t\tif (isScalar(pair.key) && pair.key.value === '<<') {\n\t\t\t\tpair.key.type = 'QUOTE_DOUBLE';\n\t\t\t}\n\t\t},\n\t\tMap(_key, map, path) {\n\t\t\tif (isPair(path.at(-1)) && isShortLeafMap(map)) {\n\t\t\t\tmap.flow = true;\n\t\t\t}\n\t\t},\n\t});\n\tconst text = doc.toString({ lineWidth: 0 });\n\treturn schemaUrl === undefined ? text : `# yaml-language-server: $schema=${schemaUrl}\\n${text}`;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,YAAAA,EAAU,UAAAC,EAAQ,YAAAC,EAAU,SAAAC,MAAa,OAUlD,IAAMC,EAAmB,EACnBC,EAAkB,GAOxB,SAASC,EAAeC,EAAuB,CAC9C,GAAIA,EAAI,MAAM,SAAW,GAAKA,EAAI,MAAM,OAASH,EAChD,MAAO,GAER,IAAII,EAAS,EACb,QAAWC,KAAQF,EAAI,MAAO,CAC7B,GAAI,CAACL,EAASO,EAAK,GAAG,GAAK,CAACP,EAASO,EAAK,KAAK,EAC9C,MAAO,GAER,IAAMC,EAAQ,OAAOD,EAAK,MAAM,KAAK,EACrC,GAAIC,EAAM,SAAS;AAAA,CAAI,EACtB,MAAO,GAERF,GAAU,OAAOC,EAAK,IAAI,KAAK,EAAE,OAASC,EAAM,OAAS,CAC1D,CACA,OAAOF,GAAUH,CAClB,CAaO,SAASM,EAAcD,EAAgBE,EAAwC,CACrF,IAAMC,EAAYD,GAAS,UAC3B,GAAIC,IAAc,QAAa,SAAS,KAAKA,CAAS,EACrD,MAAM,IAAI,UAAU,iCAAiC,EAEtD,IAAMC,EAAM,IAAId,EAASU,EAAO,CAAE,QAAS,MAAO,sBAAuB,EAAM,CAAC,EAChFP,EAAMW,EAAK,CACV,KAAKC,EAAMN,EAAM,CACZP,EAASO,EAAK,GAAG,GAAKA,EAAK,IAAI,QAAU,OAC5CA,EAAK,IAAI,KAAO,eAElB,EACA,IAAIM,EAAMR,EAAKS,EAAM,CAChBf,EAAOe,EAAK,GAAG,EAAE,CAAC,GAAKV,EAAeC,CAAG,IAC5CA,EAAI,KAAO,GAEb,CACD,CAAC,EACD,IAAMU,EAAOH,EAAI,SAAS,CAAE,UAAW,CAAE,CAAC,EAC1C,OAAOD,IAAc,OAAYI,EAAO,mCAAmCJ,CAAS;AAAA,EAAKI,CAAI,EAC9F",
|
|
6
|
+
"names": ["Document", "isPair", "isScalar", "visit", "MAX_FLOW_ENTRIES", "MAX_FLOW_LENGTH", "isShortLeafMap", "map", "length", "pair", "value", "stringifyYaml", "options", "schemaUrl", "doc", "_key", "path", "text"]
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,75 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@schema-engine/registry",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.5.1",
|
|
5
|
+
"description": "The registration contract and registries of Schema Engine: documents name registrations by $type, and each registration validates its own configuration",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"schema-engine",
|
|
8
|
+
"registry",
|
|
9
|
+
"json",
|
|
10
|
+
"serialization",
|
|
11
|
+
"standard-schema"
|
|
12
|
+
],
|
|
13
|
+
"author": "Andrea Zanenghi",
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/schema-engine/schema-engine.git",
|
|
18
|
+
"directory": "packages/registry"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": "^24.22.0 || >=26.0.0"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://schema-engine.com/docs/registry/overview",
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"main": "dist/index.js",
|
|
29
|
+
"module": "dist/index.js",
|
|
30
|
+
"types": "dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"import": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./yaml": {
|
|
37
|
+
"types": "./dist/yaml/index.d.ts",
|
|
38
|
+
"import": "./dist/yaml/index.js"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"/dist/*",
|
|
43
|
+
"/skill"
|
|
44
|
+
],
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"@ecopages/logger": "^0.2.3",
|
|
47
|
+
"@standard-schema/spec": "^1.1.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"esbuild": "^0.27.0",
|
|
51
|
+
"tsc-alias": "^1.8.16",
|
|
52
|
+
"typescript": "^5.9.3",
|
|
53
|
+
"vitest": "^5.1.1",
|
|
54
|
+
"yaml": "2.9.1",
|
|
55
|
+
"zod": "^4.0.17",
|
|
56
|
+
"@schema-engine/scripts": "0.0.0"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"yaml": "^2.8.0"
|
|
60
|
+
},
|
|
61
|
+
"peerDependenciesMeta": {
|
|
62
|
+
"yaml": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
"scripts": {
|
|
67
|
+
"build:lib": "pnpm clean && pnpm build:files && pnpm build:types",
|
|
68
|
+
"build:files": "node ./build.ts",
|
|
69
|
+
"build:types": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
|
|
70
|
+
"watch:lib": "node ./build.ts --watch",
|
|
71
|
+
"clean": "rm -rf ./dist",
|
|
72
|
+
"test:all": "vitest run",
|
|
73
|
+
"check-types": "tsc --noEmit"
|
|
74
|
+
}
|
|
6
75
|
}
|
package/skill/SKILL.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: schema-engine
|
|
3
|
+
description: |
|
|
4
|
+
Schema Engine is a common language for declarative interfaces: registrations
|
|
5
|
+
keyed by `$type`, actions that run in sequences, documents that are plain
|
|
6
|
+
data, and rendering from that data. Forms is its first domain. Use this
|
|
7
|
+
skill when an agent is asked to build, configure, validate, submit or extend
|
|
8
|
+
anything with @schema-engine/registry, @schema-engine/actions,
|
|
9
|
+
@schema-engine/layout, @schema-engine/forms, @schema-engine/forms-react or
|
|
10
|
+
@schema-engine/forms-radiant, or to write a form widget for React or Radiant.
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
# Schema Engine
|
|
14
|
+
|
|
15
|
+
Schema Engine is one grammar for interfaces that are described as data. A team registers the pieces (elements, actions, rules, appearance axes) under a `$type`, and a document, plain JSON or YAML, names them. The engine checks the document against the registrations and the renderer draws what passed. Forms is the first domain: a framework-free engine owns validation, state and submission, and a renderer (React or Radiant) only draws the fields and bridges the user's controls into that state.
|
|
16
|
+
|
|
17
|
+
This file is the router. It defines the concepts once; the references assume them and never repeat them. Read a reference only when the task needs it.
|
|
18
|
+
|
|
19
|
+
## Core concepts
|
|
20
|
+
|
|
21
|
+
- **registration**: `{ $type, schema, metadata, ... }`, where `$type` is the stable key, `schema` is any Standard Schema that describes its config, and `metadata` names it. Elements, recipes, actions, validation rules and appearance axes are all registrations.
|
|
22
|
+
- **registry**: a read-only registry, `createRegistry(kind, registrations)` from `@schema-engine/registry`, built once from a list. The last registration of a `$type` wins without a warning, which is how you replace a built-in.
|
|
23
|
+
- **document**: serializable data whose every node names a registration by `$type`. It is checked against the registrations at the boundary, so what is rendered or run has passed its schema.
|
|
24
|
+
- **action**: a registration with `execute` that runs on a trigger. Actions run as a sequence, an inner array is a parallel group, and a failure that sets `shouldContinue: false` stops what follows and cancels the group's siblings through their `signal`.
|
|
25
|
+
|
|
26
|
+
## Forms concepts
|
|
27
|
+
|
|
28
|
+
- **config**: a form is plain data, a `FormConfig` of steps holding elements, each with a `$type`, a `name`, `rules` and `constraints`. `engine.defineForm()` (typed, in TypeScript) or `engine.validateForm(unknown)` (portable JSON) checks it against the engine's registrations and returns a frozen `NormalizedFormConfig` that the engine owns.
|
|
29
|
+
- **container**: the form's state, a `FormStateContainer` from `@schema-engine/forms/state-container`. It owns the nested values, errors, warnings, touched and dirty marks, field-array row ids and the validation in flight. Paths are dotted (`contacts.1.email`) and `FORM_ROOT` is the form itself. Every change is a command (`setValue`, `blur`, `reportNative`, `validate`, `submit`, `reset`, `fieldArray`), and every read is a pure selector over an immutable snapshot.
|
|
30
|
+
- **runtime**: `createFormRuntime` is the lifecycle every renderer shares. It builds the container and owns the submission, the wizard steps and their navigation, `form_mount` and `form_change`, and every action dispatch. A renderer supplies only what an element can do, such as focus.
|
|
31
|
+
- **issues and the formatter**: the engine reports what is wrong as an issue (`type`, `source`, `ruleId`, `params`, `message`) and never makes up text. `formatIssue`, a function of the application, turns an issue into the words shown, and falls back to the issue's own `message`.
|
|
32
|
+
|
|
33
|
+
Outcomes use one vocabulary: a check or a submission ends `passed`, `invalid` or `overtaken`. `overtaken` means an edit or a reset outran the check, so there is no verdict and nothing to show.
|
|
34
|
+
|
|
35
|
+
## Packages
|
|
36
|
+
|
|
37
|
+
| Package | Role |
|
|
38
|
+
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
|
39
|
+
| `@schema-engine/registry` | The registration contract and read-only registries every package builds on, and `/yaml` for documents authored as YAML. Ships this router |
|
|
40
|
+
| `@schema-engine/actions` | Actions: `parseActions`, and a dispatcher that runs a sequence with parallel groups, cancellation and results |
|
|
41
|
+
| `@schema-engine/layout` | Domain-neutral grid, appearance axes, layout themes and the recipe protocol |
|
|
42
|
+
| `@schema-engine/forms` | The forms engine: config, validation, constraints, the container, the runtime |
|
|
43
|
+
| `@schema-engine/forms-react` | React renderer: `FormRenderer` and the hooks. You write the widgets; ready-made ones come from the optional shadcn registry |
|
|
44
|
+
| `@schema-engine/forms-radiant` | Radiant renderer: `se-form-instance`, `FormController`, widgets and recipes in the package |
|
|
45
|
+
|
|
46
|
+
A symbol has one import path. `@schema-engine/forms` has these entries: `.` (the engine, the runtime and the types), `/state-container` (the container and its selectors), `/csrf`, `/server-errors`, `/recipes`, `/recipes/built-in`, `/browser` (browser-side actions such as auto-save), `/testing` (conformance suites; they need vitest) and `/agent-tool` (experimental).
|
|
47
|
+
|
|
48
|
+
## To do X, read Y
|
|
49
|
+
|
|
50
|
+
Each package ships this router as its own `skill/SKILL.md` and its references in its `skill/reference/` folder, so a reference is `node_modules/@schema-engine/<package>/skill/reference/<file>`, and any installed package has the router. Read the rows of the packages the project depends on and skip the others: a package that is not installed has no file. The deployed site serves the latest version of the router and of every reference at `/skill/`, with the references flat at `/skill/reference/<file>`.
|
|
51
|
+
|
|
52
|
+
| To do | Package | Reference |
|
|
53
|
+
| ---------------------------------------------------------------------------- | ------------------------------ | ------------------------------------ |
|
|
54
|
+
| Register something, build a registry, or read a YAML document | `@schema-engine/registry` | `reference/registry.md` |
|
|
55
|
+
| Parse, dispatch or cancel actions outside a form | `@schema-engine/actions` | `reference/actions.md` |
|
|
56
|
+
| Build a grid, an appearance axis or a layout theme | `@schema-engine/layout` | `reference/layout.md` |
|
|
57
|
+
| Create an engine, author a config, use the container or the runtime directly | `@schema-engine/forms` | `reference/forms.md` |
|
|
58
|
+
| Add a rule, explain a validation result, or translate messages | `@schema-engine/forms` | `reference/forms-validation.md` |
|
|
59
|
+
| Handle submit, server errors, CSRF or wizard steps | `@schema-engine/forms` | `reference/forms-submission.md` |
|
|
60
|
+
| Run code on a form event, or define a form action | `@schema-engine/forms` | `reference/forms-actions.md` |
|
|
61
|
+
| Render a form in React, or use its hooks | `@schema-engine/forms-react` | `reference/forms-react.md` |
|
|
62
|
+
| Write or change a React field widget, and test it | `@schema-engine/forms-react` | `reference/forms-react-widgets.md` |
|
|
63
|
+
| Render a form in Radiant, or reach the container from an element | `@schema-engine/forms-radiant` | `reference/forms-radiant.md` |
|
|
64
|
+
| Write or change a Radiant field widget, and test it | `@schema-engine/forms-radiant` | `reference/forms-radiant-widgets.md` |
|
|
65
|
+
|
|
66
|
+
## Documentation map
|
|
67
|
+
|
|
68
|
+
The full documentation is at `/docs` on the deployed site. The LLM-exported corpus is `/llms.txt` (index) and `/docs-llm/<section>/<slug>.md` (page bodies).
|
|
69
|
+
|
|
70
|
+
| Section | Path prefix |
|
|
71
|
+
| ------------------------------ | ---------------------------------- |
|
|
72
|
+
| Schema Engine | `/docs/schema-engine/introduction` |
|
|
73
|
+
| `@schema-engine/registry` | `/docs/registry/overview` |
|
|
74
|
+
| `@schema-engine/actions` | `/docs/actions/overview` |
|
|
75
|
+
| `@schema-engine/forms` | `/docs/forms/overview` |
|
|
76
|
+
| `@schema-engine/forms-react` | `/docs/forms-react/overview` |
|
|
77
|
+
| `@schema-engine/forms-radiant` | `/docs/forms-radiant/overview` |
|
|
78
|
+
| `@schema-engine/layout` | `/docs/layout/overview` |
|
|
79
|
+
| Examples | `/docs/examples/overview` |
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# @schema-engine/registry
|
|
2
|
+
|
|
3
|
+
The registration contract and the read-only registry every other package builds on, and the YAML subpath for documents authored as text. The terms are defined in the router (`SKILL.md`). How the forms engine registers elements, recipes, actions and rules is in `forms.md`.
|
|
4
|
+
|
|
5
|
+
## A registration
|
|
6
|
+
|
|
7
|
+
Every registration is `{ $type, schema, metadata }`: `$type` is the stable key, `schema` is any Standard Schema (Zod, Zod Mini, Valibot, Effect Schema or a hand-written one) that describes the config, and `metadata` has a `name` and optionally a `description`. A package adds what it needs to the type (`BaseRegistration`): a renderable one is a `ComponentRegistration` with `render`, an action adds `execute`, a validation rule adds `category` and `handler`. The registry has no schema-library dependency: install the provider you prefer.
|
|
8
|
+
|
|
9
|
+
## createRegistry
|
|
10
|
+
|
|
11
|
+
`createRegistry(kind, registrations)` builds a frozen registry once, from a list. `kind` is the label in errors.
|
|
12
|
+
|
|
13
|
+
```ts title="registry/widgets.ts"
|
|
14
|
+
import * as z from 'zod/mini';
|
|
15
|
+
import { createRegistry, type BaseRegistration } from '@schema-engine/registry';
|
|
16
|
+
|
|
17
|
+
const defaults: BaseRegistration[] = [
|
|
18
|
+
{ $type: 'card', schema: z.object({ title: z.string() }), metadata: { name: 'Card' } },
|
|
19
|
+
{ $type: 'badge', schema: z.object({ label: z.string() }), metadata: { name: 'Badge' } },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
const custom: BaseRegistration = {
|
|
23
|
+
$type: 'card',
|
|
24
|
+
schema: z.object({ title: z.string(), tone: z.string() }),
|
|
25
|
+
metadata: { name: 'Tonal card' },
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const widgets = createRegistry('Widget', [...defaults, custom]);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- A later registration with the same `$type` replaces the earlier one with no warning, so `[...defaults, custom]` is how you override. The key keeps its first position.
|
|
32
|
+
- Each winning `schema` is checked at build: a value without `~standard.validate` throws, naming the `kind` and the `$type`.
|
|
33
|
+
- The result has `get`, `has`, `all`, `keys` and `size`, and no `register` or `clear`. It holds a frozen shallow copy of each winner taken at build, so patch a registration before building, or build a new registry from a new list.
|
|
34
|
+
- Type it with `ReadOnlyRegistry<TRegistration>`.
|
|
35
|
+
|
|
36
|
+
`safeParseStandardSchema(schema, value)` runs a registration's schema without throwing and returns `{ success: true, data }` or `{ success: false, error: { issues } }` (it throws for a schema that validates asynchronously). Form validation and `parseActions` both go through it; `assertStandardSchema` is the build-time check on its own.
|
|
37
|
+
|
|
38
|
+
## BaseRegistry
|
|
39
|
+
|
|
40
|
+
`BaseRegistry` is the mutable opt-in for registrations that arrive at runtime, such as a plugin system: `register`, `has`, `get`, `getAll`, `getAllKeys`, `size` and `clear`. It warns when `register` overrides a key and does not check schemas. Use `createRegistry` unless the list is not known when the registry is built.
|
|
41
|
+
|
|
42
|
+
## YAML documents
|
|
43
|
+
|
|
44
|
+
`@schema-engine/registry/yaml` parses a YAML text, validates the value and points each issue at a line and column. It needs the optional peer `yaml`, which the root entry never imports. `validate` is a synchronous `YamlValidate<T>`: the value in, `{ success: true, data }` or `{ success: false, issues }` out, each issue `{ message, path? }`. `engine.safeValidateForm` from `@schema-engine/forms` fits as it is.
|
|
45
|
+
|
|
46
|
+
```ts title="registry/site-yaml.ts"
|
|
47
|
+
import * as z from 'zod/mini';
|
|
48
|
+
import { safeParseStandardSchema } from '@schema-engine/registry';
|
|
49
|
+
import { safeParseYaml, type YamlValidate } from '@schema-engine/registry/yaml';
|
|
50
|
+
|
|
51
|
+
const SiteSchema = z.object({ title: z.string(), port: z.number() });
|
|
52
|
+
|
|
53
|
+
const validateSite: YamlValidate<z.output<typeof SiteSchema>> = (value) => {
|
|
54
|
+
const result = safeParseStandardSchema(SiteSchema, value);
|
|
55
|
+
return result.success ? result : { success: false, issues: result.error.issues };
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export function readSite(text: string) {
|
|
59
|
+
return safeParseYaml(text, validateSite, { filename: 'site.yaml' });
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`parseYaml` throws a `YamlDocumentError` (with `issues`) instead of returning, and `stringifyYaml(value, { schemaUrl? })` writes a value back. A `YamlIssue` is `{ message, path, line, column, filename? }`, counted from 1. The text is YAML 1.2 (core schema): `yes` and `no` stay strings, tags are issues, and duplicate keys and several documents are syntax errors.
|