@dxos/effect 0.7.3-staging.cc8dd3e → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/browser/index.mjs +29 -6
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +30 -6
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node-esm/index.mjs +29 -6
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/src/ast.d.ts +7 -0
- package/dist/types/src/ast.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/ast.ts +26 -0
|
@@ -30,6 +30,28 @@ var getSimpleType = (node) => {
|
|
|
30
30
|
}
|
|
31
31
|
};
|
|
32
32
|
var isSimpleType = (node) => !!getSimpleType(node);
|
|
33
|
+
var SimpleType;
|
|
34
|
+
(function(SimpleType2) {
|
|
35
|
+
SimpleType2.getDefaultValue = (type) => {
|
|
36
|
+
switch (type) {
|
|
37
|
+
case "string": {
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
case "number": {
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
case "boolean": {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
case "object": {
|
|
47
|
+
return {};
|
|
48
|
+
}
|
|
49
|
+
default: {
|
|
50
|
+
throw new Error(`Unsupported type for default value: ${type}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
})(SimpleType || (SimpleType = {}));
|
|
33
55
|
var PATH_REGEX = /[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)*/;
|
|
34
56
|
var PROP_REGEX = /\w+/;
|
|
35
57
|
var JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX));
|
|
@@ -129,7 +151,7 @@ var findProperty = (schema, path) => {
|
|
|
129
151
|
const typeNode = findNode(node, AST.isTypeLiteral);
|
|
130
152
|
invariant(typeNode, void 0, {
|
|
131
153
|
F: __dxlog_file,
|
|
132
|
-
L:
|
|
154
|
+
L: 249,
|
|
133
155
|
S: void 0,
|
|
134
156
|
A: [
|
|
135
157
|
"typeNode",
|
|
@@ -189,7 +211,7 @@ var isDiscriminatedUnion = (node) => {
|
|
|
189
211
|
var getDiscriminatingProps = (node) => {
|
|
190
212
|
invariant(AST.isUnion(node), void 0, {
|
|
191
213
|
F: __dxlog_file,
|
|
192
|
-
L:
|
|
214
|
+
L: 346,
|
|
193
215
|
S: void 0,
|
|
194
216
|
A: [
|
|
195
217
|
"AST.isUnion(node)",
|
|
@@ -207,7 +229,7 @@ var getDiscriminatingProps = (node) => {
|
|
|
207
229
|
var getDiscriminatedType = (node, value = {}) => {
|
|
208
230
|
invariant(AST.isUnion(node), void 0, {
|
|
209
231
|
F: __dxlog_file,
|
|
210
|
-
L:
|
|
232
|
+
L: 367,
|
|
211
233
|
S: void 0,
|
|
212
234
|
A: [
|
|
213
235
|
"AST.isUnion(node)",
|
|
@@ -216,7 +238,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
216
238
|
});
|
|
217
239
|
invariant(value, void 0, {
|
|
218
240
|
F: __dxlog_file,
|
|
219
|
-
L:
|
|
241
|
+
L: 368,
|
|
220
242
|
S: void 0,
|
|
221
243
|
A: [
|
|
222
244
|
"value",
|
|
@@ -231,7 +253,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
231
253
|
const match = AST.getPropertySignatures(type).filter((prop) => props?.includes(prop.name.toString())).every((prop) => {
|
|
232
254
|
invariant(AST.isLiteral(prop.type), void 0, {
|
|
233
255
|
F: __dxlog_file,
|
|
234
|
-
L:
|
|
256
|
+
L: 379,
|
|
235
257
|
S: void 0,
|
|
236
258
|
A: [
|
|
237
259
|
"AST.isLiteral(prop.type)",
|
|
@@ -249,7 +271,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
249
271
|
const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop);
|
|
250
272
|
invariant(AST.isLiteral(literal.type), void 0, {
|
|
251
273
|
F: __dxlog_file,
|
|
252
|
-
L:
|
|
274
|
+
L: 397,
|
|
253
275
|
S: void 0,
|
|
254
276
|
A: [
|
|
255
277
|
"AST.isLiteral(literal.type)",
|
|
@@ -344,6 +366,7 @@ export {
|
|
|
344
366
|
JsonProp,
|
|
345
367
|
ParamKeyAnnotation,
|
|
346
368
|
S2 as S,
|
|
369
|
+
SimpleType,
|
|
347
370
|
UrlParser,
|
|
348
371
|
VisitResult,
|
|
349
372
|
findAnnotation,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/index.ts", "../../../src/ast.ts", "../../../src/url.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { AST, JSONSchema, Schema as S } from '@effect/schema';\nimport type * as Types from 'effect/Types';\n\n// TODO(dmaretskyi): Remove re-exports.\nexport { AST, JSONSchema, S, Types };\n\nexport * from './ast';\nexport * from './url';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { invariant } from '@dxos/invariant';\nimport { nonNullable } from '@dxos/util';\n\n//\n// Refs\n// https://effect.website/docs/schema/introduction\n// https://www.npmjs.com/package/@effect/schema\n// https://effect-ts.github.io/effect/schema/AST.ts.html\n//\n\nexport type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';\n\n/**\n * Get the base type; e.g., traverse through refinements.\n */\nexport const getSimpleType = (node: AST.AST): SimpleType | undefined => {\n if (AST.isObjectKeyword(node) || AST.isTypeLiteral(node) || isDiscriminatedUnion(node)) {\n return 'object';\n }\n\n if (AST.isStringKeyword(node)) {\n return 'string';\n }\n if (AST.isNumberKeyword(node)) {\n return 'number';\n }\n if (AST.isBooleanKeyword(node)) {\n return 'boolean';\n }\n\n if (AST.isEnums(node)) {\n return 'enum';\n }\n\n if (AST.isLiteral(node)) {\n return 'literal';\n }\n};\n\nexport const isSimpleType = (node: AST.AST): boolean => !!getSimpleType(node);\n\n//\n// Branded types\n//\n\nexport type JsonProp = string & { __JsonPath: true; __JsonProp: true };\nexport type JsonPath = string & { __JsonPath: true };\n\nconst PATH_REGEX = /[a-zA-Z_$][\\w$]*(?:\\.[a-zA-Z_$][\\w$]*)*/;\nconst PROP_REGEX = /\\w+/;\n\n/**\n * https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html\n */\nexport const JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX)) as any as S.Schema<JsonPath>;\nexport const JsonProp = S.NonEmptyString.pipe(S.pattern(PROP_REGEX)) as any as S.Schema<JsonProp>;\n\nexport enum VisitResult {\n CONTINUE = 0,\n /**\n * Skip visiting children.\n */\n SKIP = 1,\n /**\n * Stop traversing immediately.\n */\n EXIT = 2,\n}\n\nexport type Path = (string | number)[];\n\nexport type TestFn = (node: AST.AST, path: Path, depth: number) => VisitResult | boolean | undefined;\n\nexport type VisitorFn = (node: AST.AST, path: Path, depth: number) => void;\n\nconst defaultTest: TestFn = isSimpleType;\n\n/**\n * Visit leaf nodes.\n * Refs:\n * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor\n * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test\n */\nexport const visit: {\n (node: AST.AST, visitor: VisitorFn): void;\n (node: AST.AST, test: TestFn, visitor: VisitorFn): void;\n} = (node: AST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {\n if (!visitor) {\n visitNode(node, defaultTest, testOrVisitor);\n } else {\n visitNode(node, testOrVisitor as TestFn, visitor);\n }\n};\n\nconst visitNode = (\n node: AST.AST,\n test: TestFn | undefined,\n visitor: VisitorFn,\n path: Path = [],\n depth = 0,\n): VisitResult | undefined => {\n const _result = test?.(node, path, depth);\n const result: VisitResult =\n _result === undefined\n ? VisitResult.CONTINUE\n : typeof _result === 'boolean'\n ? _result\n ? VisitResult.CONTINUE\n : VisitResult.SKIP\n : _result;\n\n if (result === VisitResult.EXIT) {\n return result;\n }\n if (result !== VisitResult.SKIP) {\n visitor(node, path, depth);\n }\n\n // Object.\n if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const currentPath = [...path, prop.name.toString()];\n const result = visitNode(prop.type, test, visitor, currentPath, depth + 1);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Array.\n else if (AST.isTupleType(node)) {\n for (const [i, element] of node.elements.entries()) {\n const currentPath = [...path, i];\n const result = visitNode(element.type, test, visitor, currentPath, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n for (const type of node.types) {\n const result = visitNode(type, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n const result = visitNode(node.from, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n\n // TODO(burdon): Transforms?\n};\n\n/**\n * Recursively descend into AST to find first node that passes the test.\n */\n// TODO(burdon): Rewrite using visitNode?\nexport const findNode = (node: AST.AST, test: (node: AST.AST) => boolean): AST.AST | undefined => {\n if (test(node)) {\n return node;\n }\n\n // Object.\n else if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const child = findNode(prop.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Tuple.\n else if (AST.isTupleType(node)) {\n for (const [_, element] of node.elements.entries()) {\n const child = findNode(element.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n if (isOption(node)) {\n for (const type of node.types) {\n const child = findNode(type, test);\n if (child) {\n return child;\n }\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n return findNode(node.from, test);\n }\n};\n\n/**\n * Get the AST node for the given property (dot-path).\n */\nexport const findProperty = (schema: S.Schema<any>, path: JsonPath | JsonProp): AST.AST | undefined => {\n const getProp = (node: AST.AST, path: JsonProp[]): AST.AST | undefined => {\n const [name, ...rest] = path;\n const typeNode = findNode(node, AST.isTypeLiteral);\n invariant(typeNode);\n for (const prop of AST.getPropertySignatures(typeNode)) {\n if (prop.name === name) {\n if (rest.length) {\n return getProp(prop.type, rest);\n } else {\n return prop.type;\n }\n }\n }\n };\n\n return getProp(schema.ast, path.split('.') as JsonProp[]);\n};\n\n//\n// Annotations\n//\n\nconst defaultAnnotations: Record<string, AST.Annotated> = {\n ['ObjectKeyword' as const]: AST.objectKeyword,\n ['StringKeyword' as const]: AST.stringKeyword,\n ['NumberKeyword' as const]: AST.numberKeyword,\n ['BooleanKeyword' as const]: AST.booleanKeyword,\n};\n\n/**\n * Get annotation or return undefined.\n * @param annotationId\n * @param noDefault If true, then return undefined for effect library defined values.\n */\nexport const getAnnotation =\n <T>(annotationId: symbol, noDefault = true) =>\n (node: AST.AST): T | undefined => {\n // Title fallback seems to be the identifier.\n const id = pipe(AST.getIdentifierAnnotation(node), Option.getOrUndefined);\n const value = pipe(AST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);\n if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {\n return undefined;\n }\n\n return value;\n };\n\n/**\n * Recursively descend into AST to find first matching annotations.\n * Optionally skips default annotations for basic types (e.g., 'a string').\n */\n// TODO(burdon): Convert to effect pattern (i.e., return operator like getAnnotation).\nexport const findAnnotation = <T>(node: AST.AST, annotationId: symbol, noDefault = true): T | undefined => {\n const getAnnotationById = getAnnotation(annotationId, noDefault);\n\n const getBaseAnnotation = (node: AST.AST): T | undefined => {\n const value = getAnnotationById(node);\n if (value !== undefined) {\n return value as T;\n }\n\n if (AST.isUnion(node)) {\n if (isOption(node)) {\n return getAnnotationById(node.types[0]) as T;\n }\n }\n };\n\n return getBaseAnnotation(node);\n};\n\n//\n// Unions\n//\n\n/**\n * Effect S.optional creates a union type with undefined as the second type.\n */\nexport const isOption = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.length === 2 && AST.isUndefinedKeyword(node.types[1]);\n};\n\n/**\n * Determines if the node is a union of literal types.\n */\nexport const isLiteralUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.every(AST.isLiteral);\n};\n\n/**\n * Determines if the node is a discriminated union.\n */\nexport const isDiscriminatedUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && !!getDiscriminatingProps(node)?.length;\n};\n\n/**\n * Get the discriminating properties for the given union type.\n */\nexport const getDiscriminatingProps = (node: AST.AST): string[] | undefined => {\n invariant(AST.isUnion(node));\n if (isOption(node)) {\n return;\n }\n\n // Get common literals across all types.\n return node.types.reduce<string[]>((shared, type) => {\n const props = AST.getPropertySignatures(type)\n // TODO(burdon): Should check each literal is unique.\n .filter((p) => AST.isLiteral(p.type))\n .map((p) => p.name.toString());\n\n // Return common literals.\n return shared.length === 0 ? props : shared.filter((prop) => props.includes(prop));\n }, []);\n};\n\n/**\n * Get the discriminated type for the given value.\n */\nexport const getDiscriminatedType = (node: AST.AST, value: Record<string, any> = {}): AST.AST | undefined => {\n invariant(AST.isUnion(node));\n invariant(value);\n const props = getDiscriminatingProps(node);\n if (!props?.length) {\n return;\n }\n\n // Match provided values.\n for (const type of node.types) {\n const match = AST.getPropertySignatures(type)\n .filter((prop) => props?.includes(prop.name.toString()))\n .every((prop) => {\n invariant(AST.isLiteral(prop.type));\n return prop.type.literal === value[prop.name.toString()];\n });\n\n if (match) {\n return type;\n }\n }\n\n // Create union of discriminating properties.\n // NOTE: This may not work with non-overlapping variants.\n // TODO(burdon): Iterate through props and knock-out variants that don't match.\n const fields = Object.fromEntries(\n props\n .map((prop) => {\n const literals = node.types\n .map((type) => {\n const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop)!;\n invariant(AST.isLiteral(literal.type));\n return literal.type.literal;\n })\n .filter(nonNullable);\n\n return literals.length ? [prop, S.Literal(...literals)] : undefined;\n })\n .filter(nonNullable),\n );\n\n const schema = S.Struct(fields);\n return schema.ast;\n};\n\n/**\n * Maps AST nodes.\n * The user is responsible for recursively calling {@link mapAst} on the AST.\n * NOTE: Will evaluate suspended ASTs.\n */\nexport const mapAst = (ast: AST.AST, f: (ast: AST.AST) => AST.AST): AST.AST => {\n switch (ast._tag) {\n case 'TypeLiteral':\n return new AST.TypeLiteral(\n ast.propertySignatures.map(\n (prop) =>\n new AST.PropertySignature(prop.name, f(prop.type), prop.isOptional, prop.isReadonly, prop.annotations),\n ),\n ast.indexSignatures,\n );\n case 'Union':\n return AST.Union.make(ast.types.map(f), ast.annotations);\n case 'TupleType':\n return new AST.TupleType(\n ast.elements.map((t) => new AST.OptionalType(f(t.type), t.isOptional, t.annotations)),\n ast.rest.map((t) => new AST.Type(f(t.type), t.annotations)),\n ast.isReadonly,\n ast.annotations,\n );\n case 'Suspend': {\n const newAst = f(ast.f());\n return new AST.Suspend(() => newAst, ast.annotations);\n }\n default:\n // TODO(dmaretskyi): Support more nodes.\n return ast;\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, type Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { decamelize } from '@dxos/util';\n\nconst ParamKeyAnnotationId = Symbol.for('@dxos/schema/annotation/ParamKey');\n\ntype ParamKeyAnnotationValue = { key: string };\n\nexport const getParamKeyAnnotation: (annotated: AST.Annotated) => Option.Option<ParamKeyAnnotationValue> =\n AST.getAnnotation<ParamKeyAnnotationValue>(ParamKeyAnnotationId);\n\nexport const ParamKeyAnnotation =\n (value: ParamKeyAnnotationValue) =>\n <S extends S.Annotable.All>(self: S): S.Annotable.Self<S> =>\n self.annotations({ [ParamKeyAnnotationId]: value });\n\n/**\n * HTTP params parser.\n * Supports custom key serialization.\n */\nexport class UrlParser<T extends Record<string, any>> {\n constructor(private readonly _schema: S.Struct<T>) {}\n\n /**\n * Parse URL params.\n */\n parse(_url: string): T {\n const url = new URL(_url);\n return Object.entries(this._schema.fields).reduce<Record<string, any>>((params, [key, type]) => {\n let value = url.searchParams.get(decamelize(key));\n if (value == null) {\n value = url.searchParams.get(key);\n }\n\n if (value != null) {\n if (AST.isNumberKeyword(type.ast)) {\n params[key] = parseInt(value);\n } else if (AST.isBooleanKeyword(type.ast)) {\n params[key] = value === 'true' || value === '1';\n } else {\n params[key] = value;\n }\n }\n\n return params;\n }, {}) as T;\n }\n\n /**\n * Return URL with encoded params.\n */\n create(_url: string, params: T): URL {\n const url = new URL(_url);\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined) {\n const field = this._schema.fields[key];\n if (field) {\n const { key: serializedKey } = pipe(\n getParamKeyAnnotation(field.ast),\n Option.getOrElse(() => ({\n key: decamelize(key),\n })),\n );\n\n url.searchParams.set(serializedKey, String(value));\n }\n }\n });\n\n return url;\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;AAIA,SAASA,OAAAA,MAAKC,YAAYC,UAAUC,UAAS;;;ACA7C,SAASC,KAAKC,UAAUC,SAAS;AACjC,SAASC,QAAQC,YAAY;AAE7B,SAASC,iBAAiB;AAC1B,SAASC,mBAAmB;;AAcrB,IAAMC,gBAAgB,CAACC,SAAAA;AAC5B,MAAIR,IAAIS,gBAAgBD,IAAAA,KAASR,IAAIU,cAAcF,IAAAA,KAASG,qBAAqBH,IAAAA,GAAO;AACtF,WAAO;EACT;AAEA,MAAIR,IAAIY,gBAAgBJ,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIR,IAAIa,gBAAgBL,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIR,IAAIc,iBAAiBN,IAAAA,GAAO;AAC9B,WAAO;EACT;AAEA,MAAIR,IAAIe,QAAQP,IAAAA,GAAO;AACrB,WAAO;EACT;AAEA,MAAIR,IAAIgB,UAAUR,IAAAA,GAAO;AACvB,WAAO;EACT;AACF;AAEO,IAAMS,eAAe,CAACT,SAA2B,CAAC,CAACD,cAAcC,IAAAA;
|
|
6
|
-
"names": ["AST", "JSONSchema", "Schema", "S", "AST", "Schema", "S", "Option", "pipe", "invariant", "nonNullable", "getSimpleType", "node", "isObjectKeyword", "isTypeLiteral", "isDiscriminatedUnion", "isStringKeyword", "isNumberKeyword", "isBooleanKeyword", "isEnums", "isLiteral", "isSimpleType", "PATH_REGEX", "PROP_REGEX", "JsonPath", "NonEmptyString", "pattern", "JsonProp", "VisitResult", "defaultTest", "visit", "testOrVisitor", "visitor", "visitNode", "test", "path", "depth", "_result", "result", "undefined", "prop", "getPropertySignatures", "currentPath", "name", "toString", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { AST, JSONSchema, Schema as S } from '@effect/schema';\nimport type * as Types from 'effect/Types';\n\n// TODO(dmaretskyi): Remove re-exports.\nexport { AST, JSONSchema, S, Types };\n\nexport * from './ast';\nexport * from './url';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { invariant } from '@dxos/invariant';\nimport { nonNullable } from '@dxos/util';\n\n//\n// Refs\n// https://effect.website/docs/schema/introduction\n// https://www.npmjs.com/package/@effect/schema\n// https://effect-ts.github.io/effect/schema/AST.ts.html\n//\n\nexport type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';\n\n/**\n * Get the base type; e.g., traverse through refinements.\n */\nexport const getSimpleType = (node: AST.AST): SimpleType | undefined => {\n if (AST.isObjectKeyword(node) || AST.isTypeLiteral(node) || isDiscriminatedUnion(node)) {\n return 'object';\n }\n\n if (AST.isStringKeyword(node)) {\n return 'string';\n }\n if (AST.isNumberKeyword(node)) {\n return 'number';\n }\n if (AST.isBooleanKeyword(node)) {\n return 'boolean';\n }\n\n if (AST.isEnums(node)) {\n return 'enum';\n }\n\n if (AST.isLiteral(node)) {\n return 'literal';\n }\n};\n\nexport const isSimpleType = (node: AST.AST): boolean => !!getSimpleType(node);\n\nexport namespace SimpleType {\n /**\n * Returns the default empty value for a given SimpleType.\n * Used for initializing new array values etc.\n */\n export const getDefaultValue = (type: SimpleType): any => {\n switch (type) {\n case 'string': {\n return '';\n }\n case 'number': {\n return 0;\n }\n case 'boolean': {\n return false;\n }\n case 'object': {\n return {};\n }\n default: {\n throw new Error(`Unsupported type for default value: ${type}`);\n }\n }\n };\n}\n\n//\n// Branded types\n//\n\nexport type JsonProp = string & { __JsonPath: true; __JsonProp: true };\nexport type JsonPath = string & { __JsonPath: true };\n\nconst PATH_REGEX = /[a-zA-Z_$][\\w$]*(?:\\.[a-zA-Z_$][\\w$]*)*/;\nconst PROP_REGEX = /\\w+/;\n\n/**\n * https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html\n */\nexport const JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX)) as any as S.Schema<JsonPath>;\nexport const JsonProp = S.NonEmptyString.pipe(S.pattern(PROP_REGEX)) as any as S.Schema<JsonProp>;\n\nexport enum VisitResult {\n CONTINUE = 0,\n /**\n * Skip visiting children.\n */\n SKIP = 1,\n /**\n * Stop traversing immediately.\n */\n EXIT = 2,\n}\n\nexport type Path = (string | number)[];\n\nexport type TestFn = (node: AST.AST, path: Path, depth: number) => VisitResult | boolean | undefined;\n\nexport type VisitorFn = (node: AST.AST, path: Path, depth: number) => void;\n\nconst defaultTest: TestFn = isSimpleType;\n\n/**\n * Visit leaf nodes.\n * Refs:\n * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor\n * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test\n */\nexport const visit: {\n (node: AST.AST, visitor: VisitorFn): void;\n (node: AST.AST, test: TestFn, visitor: VisitorFn): void;\n} = (node: AST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {\n if (!visitor) {\n visitNode(node, defaultTest, testOrVisitor);\n } else {\n visitNode(node, testOrVisitor as TestFn, visitor);\n }\n};\n\nconst visitNode = (\n node: AST.AST,\n test: TestFn | undefined,\n visitor: VisitorFn,\n path: Path = [],\n depth = 0,\n): VisitResult | undefined => {\n const _result = test?.(node, path, depth);\n const result: VisitResult =\n _result === undefined\n ? VisitResult.CONTINUE\n : typeof _result === 'boolean'\n ? _result\n ? VisitResult.CONTINUE\n : VisitResult.SKIP\n : _result;\n\n if (result === VisitResult.EXIT) {\n return result;\n }\n if (result !== VisitResult.SKIP) {\n visitor(node, path, depth);\n }\n\n // Object.\n if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const currentPath = [...path, prop.name.toString()];\n const result = visitNode(prop.type, test, visitor, currentPath, depth + 1);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Array.\n else if (AST.isTupleType(node)) {\n for (const [i, element] of node.elements.entries()) {\n const currentPath = [...path, i];\n const result = visitNode(element.type, test, visitor, currentPath, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n for (const type of node.types) {\n const result = visitNode(type, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n const result = visitNode(node.from, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n\n // TODO(burdon): Transforms?\n};\n\n/**\n * Recursively descend into AST to find first node that passes the test.\n */\n// TODO(burdon): Rewrite using visitNode?\nexport const findNode = (node: AST.AST, test: (node: AST.AST) => boolean): AST.AST | undefined => {\n if (test(node)) {\n return node;\n }\n\n // Object.\n else if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const child = findNode(prop.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Tuple.\n else if (AST.isTupleType(node)) {\n for (const [_, element] of node.elements.entries()) {\n const child = findNode(element.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n if (isOption(node)) {\n for (const type of node.types) {\n const child = findNode(type, test);\n if (child) {\n return child;\n }\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n return findNode(node.from, test);\n }\n};\n\n/**\n * Get the AST node for the given property (dot-path).\n */\nexport const findProperty = (schema: S.Schema<any>, path: JsonPath | JsonProp): AST.AST | undefined => {\n const getProp = (node: AST.AST, path: JsonProp[]): AST.AST | undefined => {\n const [name, ...rest] = path;\n const typeNode = findNode(node, AST.isTypeLiteral);\n invariant(typeNode);\n for (const prop of AST.getPropertySignatures(typeNode)) {\n if (prop.name === name) {\n if (rest.length) {\n return getProp(prop.type, rest);\n } else {\n return prop.type;\n }\n }\n }\n };\n\n return getProp(schema.ast, path.split('.') as JsonProp[]);\n};\n\n//\n// Annotations\n//\n\nconst defaultAnnotations: Record<string, AST.Annotated> = {\n ['ObjectKeyword' as const]: AST.objectKeyword,\n ['StringKeyword' as const]: AST.stringKeyword,\n ['NumberKeyword' as const]: AST.numberKeyword,\n ['BooleanKeyword' as const]: AST.booleanKeyword,\n};\n\n/**\n * Get annotation or return undefined.\n * @param annotationId\n * @param noDefault If true, then return undefined for effect library defined values.\n */\nexport const getAnnotation =\n <T>(annotationId: symbol, noDefault = true) =>\n (node: AST.AST): T | undefined => {\n // Title fallback seems to be the identifier.\n const id = pipe(AST.getIdentifierAnnotation(node), Option.getOrUndefined);\n const value = pipe(AST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);\n if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {\n return undefined;\n }\n\n return value;\n };\n\n/**\n * Recursively descend into AST to find first matching annotations.\n * Optionally skips default annotations for basic types (e.g., 'a string').\n */\n// TODO(burdon): Convert to effect pattern (i.e., return operator like getAnnotation).\nexport const findAnnotation = <T>(node: AST.AST, annotationId: symbol, noDefault = true): T | undefined => {\n const getAnnotationById = getAnnotation(annotationId, noDefault);\n\n const getBaseAnnotation = (node: AST.AST): T | undefined => {\n const value = getAnnotationById(node);\n if (value !== undefined) {\n return value as T;\n }\n\n if (AST.isUnion(node)) {\n if (isOption(node)) {\n return getAnnotationById(node.types[0]) as T;\n }\n }\n };\n\n return getBaseAnnotation(node);\n};\n\n//\n// Unions\n//\n\n/**\n * Effect S.optional creates a union type with undefined as the second type.\n */\nexport const isOption = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.length === 2 && AST.isUndefinedKeyword(node.types[1]);\n};\n\n/**\n * Determines if the node is a union of literal types.\n */\nexport const isLiteralUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.every(AST.isLiteral);\n};\n\n/**\n * Determines if the node is a discriminated union.\n */\nexport const isDiscriminatedUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && !!getDiscriminatingProps(node)?.length;\n};\n\n/**\n * Get the discriminating properties for the given union type.\n */\nexport const getDiscriminatingProps = (node: AST.AST): string[] | undefined => {\n invariant(AST.isUnion(node));\n if (isOption(node)) {\n return;\n }\n\n // Get common literals across all types.\n return node.types.reduce<string[]>((shared, type) => {\n const props = AST.getPropertySignatures(type)\n // TODO(burdon): Should check each literal is unique.\n .filter((p) => AST.isLiteral(p.type))\n .map((p) => p.name.toString());\n\n // Return common literals.\n return shared.length === 0 ? props : shared.filter((prop) => props.includes(prop));\n }, []);\n};\n\n/**\n * Get the discriminated type for the given value.\n */\nexport const getDiscriminatedType = (node: AST.AST, value: Record<string, any> = {}): AST.AST | undefined => {\n invariant(AST.isUnion(node));\n invariant(value);\n const props = getDiscriminatingProps(node);\n if (!props?.length) {\n return;\n }\n\n // Match provided values.\n for (const type of node.types) {\n const match = AST.getPropertySignatures(type)\n .filter((prop) => props?.includes(prop.name.toString()))\n .every((prop) => {\n invariant(AST.isLiteral(prop.type));\n return prop.type.literal === value[prop.name.toString()];\n });\n\n if (match) {\n return type;\n }\n }\n\n // Create union of discriminating properties.\n // NOTE: This may not work with non-overlapping variants.\n // TODO(burdon): Iterate through props and knock-out variants that don't match.\n const fields = Object.fromEntries(\n props\n .map((prop) => {\n const literals = node.types\n .map((type) => {\n const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop)!;\n invariant(AST.isLiteral(literal.type));\n return literal.type.literal;\n })\n .filter(nonNullable);\n\n return literals.length ? [prop, S.Literal(...literals)] : undefined;\n })\n .filter(nonNullable),\n );\n\n const schema = S.Struct(fields);\n return schema.ast;\n};\n\n/**\n * Maps AST nodes.\n * The user is responsible for recursively calling {@link mapAst} on the AST.\n * NOTE: Will evaluate suspended ASTs.\n */\nexport const mapAst = (ast: AST.AST, f: (ast: AST.AST) => AST.AST): AST.AST => {\n switch (ast._tag) {\n case 'TypeLiteral':\n return new AST.TypeLiteral(\n ast.propertySignatures.map(\n (prop) =>\n new AST.PropertySignature(prop.name, f(prop.type), prop.isOptional, prop.isReadonly, prop.annotations),\n ),\n ast.indexSignatures,\n );\n case 'Union':\n return AST.Union.make(ast.types.map(f), ast.annotations);\n case 'TupleType':\n return new AST.TupleType(\n ast.elements.map((t) => new AST.OptionalType(f(t.type), t.isOptional, t.annotations)),\n ast.rest.map((t) => new AST.Type(f(t.type), t.annotations)),\n ast.isReadonly,\n ast.annotations,\n );\n case 'Suspend': {\n const newAst = f(ast.f());\n return new AST.Suspend(() => newAst, ast.annotations);\n }\n default:\n // TODO(dmaretskyi): Support more nodes.\n return ast;\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, type Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { decamelize } from '@dxos/util';\n\nconst ParamKeyAnnotationId = Symbol.for('@dxos/schema/annotation/ParamKey');\n\ntype ParamKeyAnnotationValue = { key: string };\n\nexport const getParamKeyAnnotation: (annotated: AST.Annotated) => Option.Option<ParamKeyAnnotationValue> =\n AST.getAnnotation<ParamKeyAnnotationValue>(ParamKeyAnnotationId);\n\nexport const ParamKeyAnnotation =\n (value: ParamKeyAnnotationValue) =>\n <S extends S.Annotable.All>(self: S): S.Annotable.Self<S> =>\n self.annotations({ [ParamKeyAnnotationId]: value });\n\n/**\n * HTTP params parser.\n * Supports custom key serialization.\n */\nexport class UrlParser<T extends Record<string, any>> {\n constructor(private readonly _schema: S.Struct<T>) {}\n\n /**\n * Parse URL params.\n */\n parse(_url: string): T {\n const url = new URL(_url);\n return Object.entries(this._schema.fields).reduce<Record<string, any>>((params, [key, type]) => {\n let value = url.searchParams.get(decamelize(key));\n if (value == null) {\n value = url.searchParams.get(key);\n }\n\n if (value != null) {\n if (AST.isNumberKeyword(type.ast)) {\n params[key] = parseInt(value);\n } else if (AST.isBooleanKeyword(type.ast)) {\n params[key] = value === 'true' || value === '1';\n } else {\n params[key] = value;\n }\n }\n\n return params;\n }, {}) as T;\n }\n\n /**\n * Return URL with encoded params.\n */\n create(_url: string, params: T): URL {\n const url = new URL(_url);\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined) {\n const field = this._schema.fields[key];\n if (field) {\n const { key: serializedKey } = pipe(\n getParamKeyAnnotation(field.ast),\n Option.getOrElse(() => ({\n key: decamelize(key),\n })),\n );\n\n url.searchParams.set(serializedKey, String(value));\n }\n }\n });\n\n return url;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;AAIA,SAASA,OAAAA,MAAKC,YAAYC,UAAUC,UAAS;;;ACA7C,SAASC,KAAKC,UAAUC,SAAS;AACjC,SAASC,QAAQC,YAAY;AAE7B,SAASC,iBAAiB;AAC1B,SAASC,mBAAmB;;AAcrB,IAAMC,gBAAgB,CAACC,SAAAA;AAC5B,MAAIR,IAAIS,gBAAgBD,IAAAA,KAASR,IAAIU,cAAcF,IAAAA,KAASG,qBAAqBH,IAAAA,GAAO;AACtF,WAAO;EACT;AAEA,MAAIR,IAAIY,gBAAgBJ,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIR,IAAIa,gBAAgBL,IAAAA,G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AAAA,IAAOf;QAChB;MACF;AAEA,aAAOc;IACT,GAAG,CAAC,CAAA;EACN;;;;EAKAU,OAAOjB,MAAcO,QAAgB;AACnC,UAAMN,MAAM,IAAIC,IAAIF,IAAAA;AACpBG,WAAOC,QAAQG,MAAAA,EAAQW,QAAQ,CAAC,CAACV,KAAKf,KAAAA,MAAM;AAC1C,UAAIA,UAAU0B,QAAW;AACvB,cAAMC,QAAQ,KAAKtB,QAAQO,OAAOG,GAAAA;AAClC,YAAIY,OAAO;AACT,gBAAM,EAAEZ,KAAKa,cAAa,IAAKC,MAC7BjC,sBAAsB+B,MAAMN,GAAG,GAC/BS,QAAOC,UAAU,OAAO;YACtBhB,KAAKI,WAAWJ,GAAAA;UAClB,EAAA,CAAA;AAGFP,cAAIS,aAAae,IAAIJ,eAAeK,OAAOjC,KAAAA,CAAAA;QAC7C;MACF;IACF,CAAA;AAEA,WAAOQ;EACT;AACF;",
|
|
6
|
+
"names": ["AST", "JSONSchema", "Schema", "S", "AST", "Schema", "S", "Option", "pipe", "invariant", "nonNullable", "getSimpleType", "node", "isObjectKeyword", "isTypeLiteral", "isDiscriminatedUnion", "isStringKeyword", "isNumberKeyword", "isBooleanKeyword", "isEnums", "isLiteral", "isSimpleType", "SimpleType", "getDefaultValue", "type", "Error", "PATH_REGEX", "PROP_REGEX", "JsonPath", "NonEmptyString", "pattern", "JsonProp", "VisitResult", "defaultTest", "visit", "testOrVisitor", "visitor", "visitNode", "test", "path", "depth", "_result", "result", "undefined", "prop", "getPropertySignatures", "currentPath", "name", "toString", "isTupleType", "i", "element", "elements", "entries", "isUnion", "types", "isRefinement", "from", "findNode", "child", "_", "isOption", "findProperty", "schema", "getProp", "rest", "typeNode", "length", "ast", "split", "defaultAnnotations", "objectKeyword", "stringKeyword", "numberKeyword", "booleanKeyword", "getAnnotation", "annotationId", "noDefault", "id", "getIdentifierAnnotation", "getOrUndefined", "value", "_tag", "annotations", "findAnnotation", "getAnnotationById", "getBaseAnnotation", "isUndefinedKeyword", "isLiteralUnion", "every", "getDiscriminatingProps", "reduce", "shared", "props", "filter", "p", "map", "includes", "getDiscriminatedType", "match", "literal", "fields", "Object", "fromEntries", "literals", "find", "Literal", "Struct", "mapAst", "f", "TypeLiteral", "propertySignatures", "PropertySignature", "isOptional", "isReadonly", "indexSignatures", "Union", "make", "TupleType", "t", "OptionalType", "Type", "newAst", "Suspend", "AST", "Option", "pipe", "decamelize", "ParamKeyAnnotationId", "Symbol", "for", "getParamKeyAnnotation", "AST", "getAnnotation", "ParamKeyAnnotation", "value", "self", "annotations", "UrlParser", "constructor", "_schema", "parse", "_url", "url", "URL", "Object", "entries", "fields", "reduce", "params", "key", "type", "searchParams", "get", "decamelize", "isNumberKeyword", "ast", "parseInt", "isBooleanKeyword", "create", "forEach", "undefined", "field", "serializedKey", "pipe", "Option", "getOrElse", "set", "String"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/common/effect/src/ast.ts":{"bytes":
|
|
1
|
+
{"inputs":{"packages/common/effect/src/ast.ts":{"bytes":41444,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/common/effect/src/url.ts":{"bytes":7711,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/common/effect/src/index.ts":{"bytes":1150,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"packages/common/effect/src/ast.ts","kind":"import-statement","original":"./ast"},{"path":"packages/common/effect/src/url.ts","kind":"import-statement","original":"./url"}],"format":"esm"}},"outputs":{"packages/common/effect/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":25493},"packages/common/effect/dist/lib/browser/index.mjs":{"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AST","JSONSchema","JsonPath","JsonProp","ParamKeyAnnotation","S","SimpleType","UrlParser","VisitResult","findAnnotation","findNode","findProperty","getAnnotation","getDiscriminatedType","getDiscriminatingProps","getParamKeyAnnotation","getSimpleType","isDiscriminatedUnion","isLiteralUnion","isOption","isSimpleType","mapAst","visit"],"entryPoint":"packages/common/effect/src/index.ts","inputs":{"packages/common/effect/src/index.ts":{"bytesInOutput":72},"packages/common/effect/src/ast.ts":{"bytesInOutput":8647},"packages/common/effect/src/url.ts":{"bytesInOutput":1624}},"bytes":10910}}}
|
package/dist/lib/node/index.cjs
CHANGED
|
@@ -24,6 +24,7 @@ __export(node_exports, {
|
|
|
24
24
|
JsonProp: () => JsonProp,
|
|
25
25
|
ParamKeyAnnotation: () => ParamKeyAnnotation,
|
|
26
26
|
S: () => import_schema.Schema,
|
|
27
|
+
SimpleType: () => SimpleType,
|
|
27
28
|
UrlParser: () => UrlParser,
|
|
28
29
|
VisitResult: () => VisitResult,
|
|
29
30
|
findAnnotation: () => findAnnotation,
|
|
@@ -72,6 +73,28 @@ var getSimpleType = (node) => {
|
|
|
72
73
|
}
|
|
73
74
|
};
|
|
74
75
|
var isSimpleType = (node) => !!getSimpleType(node);
|
|
76
|
+
var SimpleType;
|
|
77
|
+
(function(SimpleType2) {
|
|
78
|
+
SimpleType2.getDefaultValue = (type) => {
|
|
79
|
+
switch (type) {
|
|
80
|
+
case "string": {
|
|
81
|
+
return "";
|
|
82
|
+
}
|
|
83
|
+
case "number": {
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
case "boolean": {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
case "object": {
|
|
90
|
+
return {};
|
|
91
|
+
}
|
|
92
|
+
default: {
|
|
93
|
+
throw new Error(`Unsupported type for default value: ${type}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
})(SimpleType || (SimpleType = {}));
|
|
75
98
|
var PATH_REGEX = /[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)*/;
|
|
76
99
|
var PROP_REGEX = /\w+/;
|
|
77
100
|
var JsonPath = import_schema2.Schema.NonEmptyString.pipe(import_schema2.Schema.pattern(PATH_REGEX));
|
|
@@ -171,7 +194,7 @@ var findProperty = (schema, path) => {
|
|
|
171
194
|
const typeNode = findNode(node, import_schema2.AST.isTypeLiteral);
|
|
172
195
|
(0, import_invariant.invariant)(typeNode, void 0, {
|
|
173
196
|
F: __dxlog_file,
|
|
174
|
-
L:
|
|
197
|
+
L: 249,
|
|
175
198
|
S: void 0,
|
|
176
199
|
A: [
|
|
177
200
|
"typeNode",
|
|
@@ -231,7 +254,7 @@ var isDiscriminatedUnion = (node) => {
|
|
|
231
254
|
var getDiscriminatingProps = (node) => {
|
|
232
255
|
(0, import_invariant.invariant)(import_schema2.AST.isUnion(node), void 0, {
|
|
233
256
|
F: __dxlog_file,
|
|
234
|
-
L:
|
|
257
|
+
L: 346,
|
|
235
258
|
S: void 0,
|
|
236
259
|
A: [
|
|
237
260
|
"AST.isUnion(node)",
|
|
@@ -249,7 +272,7 @@ var getDiscriminatingProps = (node) => {
|
|
|
249
272
|
var getDiscriminatedType = (node, value = {}) => {
|
|
250
273
|
(0, import_invariant.invariant)(import_schema2.AST.isUnion(node), void 0, {
|
|
251
274
|
F: __dxlog_file,
|
|
252
|
-
L:
|
|
275
|
+
L: 367,
|
|
253
276
|
S: void 0,
|
|
254
277
|
A: [
|
|
255
278
|
"AST.isUnion(node)",
|
|
@@ -258,7 +281,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
258
281
|
});
|
|
259
282
|
(0, import_invariant.invariant)(value, void 0, {
|
|
260
283
|
F: __dxlog_file,
|
|
261
|
-
L:
|
|
284
|
+
L: 368,
|
|
262
285
|
S: void 0,
|
|
263
286
|
A: [
|
|
264
287
|
"value",
|
|
@@ -273,7 +296,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
273
296
|
const match = import_schema2.AST.getPropertySignatures(type).filter((prop) => props?.includes(prop.name.toString())).every((prop) => {
|
|
274
297
|
(0, import_invariant.invariant)(import_schema2.AST.isLiteral(prop.type), void 0, {
|
|
275
298
|
F: __dxlog_file,
|
|
276
|
-
L:
|
|
299
|
+
L: 379,
|
|
277
300
|
S: void 0,
|
|
278
301
|
A: [
|
|
279
302
|
"AST.isLiteral(prop.type)",
|
|
@@ -291,7 +314,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
291
314
|
const literal = import_schema2.AST.getPropertySignatures(type).find((p) => p.name.toString() === prop);
|
|
292
315
|
(0, import_invariant.invariant)(import_schema2.AST.isLiteral(literal.type), void 0, {
|
|
293
316
|
F: __dxlog_file,
|
|
294
|
-
L:
|
|
317
|
+
L: 397,
|
|
295
318
|
S: void 0,
|
|
296
319
|
A: [
|
|
297
320
|
"AST.isLiteral(literal.type)",
|
|
@@ -382,6 +405,7 @@ var UrlParser = class {
|
|
|
382
405
|
JsonProp,
|
|
383
406
|
ParamKeyAnnotation,
|
|
384
407
|
S,
|
|
408
|
+
SimpleType,
|
|
385
409
|
UrlParser,
|
|
386
410
|
VisitResult,
|
|
387
411
|
findAnnotation,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/index.ts", "../../../src/ast.ts", "../../../src/url.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { AST, JSONSchema, Schema as S } from '@effect/schema';\nimport type * as Types from 'effect/Types';\n\n// TODO(dmaretskyi): Remove re-exports.\nexport { AST, JSONSchema, S, Types };\n\nexport * from './ast';\nexport * from './url';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { invariant } from '@dxos/invariant';\nimport { nonNullable } from '@dxos/util';\n\n//\n// Refs\n// https://effect.website/docs/schema/introduction\n// https://www.npmjs.com/package/@effect/schema\n// https://effect-ts.github.io/effect/schema/AST.ts.html\n//\n\nexport type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';\n\n/**\n * Get the base type; e.g., traverse through refinements.\n */\nexport const getSimpleType = (node: AST.AST): SimpleType | undefined => {\n if (AST.isObjectKeyword(node) || AST.isTypeLiteral(node) || isDiscriminatedUnion(node)) {\n return 'object';\n }\n\n if (AST.isStringKeyword(node)) {\n return 'string';\n }\n if (AST.isNumberKeyword(node)) {\n return 'number';\n }\n if (AST.isBooleanKeyword(node)) {\n return 'boolean';\n }\n\n if (AST.isEnums(node)) {\n return 'enum';\n }\n\n if (AST.isLiteral(node)) {\n return 'literal';\n }\n};\n\nexport const isSimpleType = (node: AST.AST): boolean => !!getSimpleType(node);\n\n//\n// Branded types\n//\n\nexport type JsonProp = string & { __JsonPath: true; __JsonProp: true };\nexport type JsonPath = string & { __JsonPath: true };\n\nconst PATH_REGEX = /[a-zA-Z_$][\\w$]*(?:\\.[a-zA-Z_$][\\w$]*)*/;\nconst PROP_REGEX = /\\w+/;\n\n/**\n * https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html\n */\nexport const JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX)) as any as S.Schema<JsonPath>;\nexport const JsonProp = S.NonEmptyString.pipe(S.pattern(PROP_REGEX)) as any as S.Schema<JsonProp>;\n\nexport enum VisitResult {\n CONTINUE = 0,\n /**\n * Skip visiting children.\n */\n SKIP = 1,\n /**\n * Stop traversing immediately.\n */\n EXIT = 2,\n}\n\nexport type Path = (string | number)[];\n\nexport type TestFn = (node: AST.AST, path: Path, depth: number) => VisitResult | boolean | undefined;\n\nexport type VisitorFn = (node: AST.AST, path: Path, depth: number) => void;\n\nconst defaultTest: TestFn = isSimpleType;\n\n/**\n * Visit leaf nodes.\n * Refs:\n * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor\n * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test\n */\nexport const visit: {\n (node: AST.AST, visitor: VisitorFn): void;\n (node: AST.AST, test: TestFn, visitor: VisitorFn): void;\n} = (node: AST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {\n if (!visitor) {\n visitNode(node, defaultTest, testOrVisitor);\n } else {\n visitNode(node, testOrVisitor as TestFn, visitor);\n }\n};\n\nconst visitNode = (\n node: AST.AST,\n test: TestFn | undefined,\n visitor: VisitorFn,\n path: Path = [],\n depth = 0,\n): VisitResult | undefined => {\n const _result = test?.(node, path, depth);\n const result: VisitResult =\n _result === undefined\n ? VisitResult.CONTINUE\n : typeof _result === 'boolean'\n ? _result\n ? VisitResult.CONTINUE\n : VisitResult.SKIP\n : _result;\n\n if (result === VisitResult.EXIT) {\n return result;\n }\n if (result !== VisitResult.SKIP) {\n visitor(node, path, depth);\n }\n\n // Object.\n if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const currentPath = [...path, prop.name.toString()];\n const result = visitNode(prop.type, test, visitor, currentPath, depth + 1);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Array.\n else if (AST.isTupleType(node)) {\n for (const [i, element] of node.elements.entries()) {\n const currentPath = [...path, i];\n const result = visitNode(element.type, test, visitor, currentPath, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n for (const type of node.types) {\n const result = visitNode(type, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n const result = visitNode(node.from, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n\n // TODO(burdon): Transforms?\n};\n\n/**\n * Recursively descend into AST to find first node that passes the test.\n */\n// TODO(burdon): Rewrite using visitNode?\nexport const findNode = (node: AST.AST, test: (node: AST.AST) => boolean): AST.AST | undefined => {\n if (test(node)) {\n return node;\n }\n\n // Object.\n else if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const child = findNode(prop.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Tuple.\n else if (AST.isTupleType(node)) {\n for (const [_, element] of node.elements.entries()) {\n const child = findNode(element.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n if (isOption(node)) {\n for (const type of node.types) {\n const child = findNode(type, test);\n if (child) {\n return child;\n }\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n return findNode(node.from, test);\n }\n};\n\n/**\n * Get the AST node for the given property (dot-path).\n */\nexport const findProperty = (schema: S.Schema<any>, path: JsonPath | JsonProp): AST.AST | undefined => {\n const getProp = (node: AST.AST, path: JsonProp[]): AST.AST | undefined => {\n const [name, ...rest] = path;\n const typeNode = findNode(node, AST.isTypeLiteral);\n invariant(typeNode);\n for (const prop of AST.getPropertySignatures(typeNode)) {\n if (prop.name === name) {\n if (rest.length) {\n return getProp(prop.type, rest);\n } else {\n return prop.type;\n }\n }\n }\n };\n\n return getProp(schema.ast, path.split('.') as JsonProp[]);\n};\n\n//\n// Annotations\n//\n\nconst defaultAnnotations: Record<string, AST.Annotated> = {\n ['ObjectKeyword' as const]: AST.objectKeyword,\n ['StringKeyword' as const]: AST.stringKeyword,\n ['NumberKeyword' as const]: AST.numberKeyword,\n ['BooleanKeyword' as const]: AST.booleanKeyword,\n};\n\n/**\n * Get annotation or return undefined.\n * @param annotationId\n * @param noDefault If true, then return undefined for effect library defined values.\n */\nexport const getAnnotation =\n <T>(annotationId: symbol, noDefault = true) =>\n (node: AST.AST): T | undefined => {\n // Title fallback seems to be the identifier.\n const id = pipe(AST.getIdentifierAnnotation(node), Option.getOrUndefined);\n const value = pipe(AST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);\n if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {\n return undefined;\n }\n\n return value;\n };\n\n/**\n * Recursively descend into AST to find first matching annotations.\n * Optionally skips default annotations for basic types (e.g., 'a string').\n */\n// TODO(burdon): Convert to effect pattern (i.e., return operator like getAnnotation).\nexport const findAnnotation = <T>(node: AST.AST, annotationId: symbol, noDefault = true): T | undefined => {\n const getAnnotationById = getAnnotation(annotationId, noDefault);\n\n const getBaseAnnotation = (node: AST.AST): T | undefined => {\n const value = getAnnotationById(node);\n if (value !== undefined) {\n return value as T;\n }\n\n if (AST.isUnion(node)) {\n if (isOption(node)) {\n return getAnnotationById(node.types[0]) as T;\n }\n }\n };\n\n return getBaseAnnotation(node);\n};\n\n//\n// Unions\n//\n\n/**\n * Effect S.optional creates a union type with undefined as the second type.\n */\nexport const isOption = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.length === 2 && AST.isUndefinedKeyword(node.types[1]);\n};\n\n/**\n * Determines if the node is a union of literal types.\n */\nexport const isLiteralUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.every(AST.isLiteral);\n};\n\n/**\n * Determines if the node is a discriminated union.\n */\nexport const isDiscriminatedUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && !!getDiscriminatingProps(node)?.length;\n};\n\n/**\n * Get the discriminating properties for the given union type.\n */\nexport const getDiscriminatingProps = (node: AST.AST): string[] | undefined => {\n invariant(AST.isUnion(node));\n if (isOption(node)) {\n return;\n }\n\n // Get common literals across all types.\n return node.types.reduce<string[]>((shared, type) => {\n const props = AST.getPropertySignatures(type)\n // TODO(burdon): Should check each literal is unique.\n .filter((p) => AST.isLiteral(p.type))\n .map((p) => p.name.toString());\n\n // Return common literals.\n return shared.length === 0 ? props : shared.filter((prop) => props.includes(prop));\n }, []);\n};\n\n/**\n * Get the discriminated type for the given value.\n */\nexport const getDiscriminatedType = (node: AST.AST, value: Record<string, any> = {}): AST.AST | undefined => {\n invariant(AST.isUnion(node));\n invariant(value);\n const props = getDiscriminatingProps(node);\n if (!props?.length) {\n return;\n }\n\n // Match provided values.\n for (const type of node.types) {\n const match = AST.getPropertySignatures(type)\n .filter((prop) => props?.includes(prop.name.toString()))\n .every((prop) => {\n invariant(AST.isLiteral(prop.type));\n return prop.type.literal === value[prop.name.toString()];\n });\n\n if (match) {\n return type;\n }\n }\n\n // Create union of discriminating properties.\n // NOTE: This may not work with non-overlapping variants.\n // TODO(burdon): Iterate through props and knock-out variants that don't match.\n const fields = Object.fromEntries(\n props\n .map((prop) => {\n const literals = node.types\n .map((type) => {\n const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop)!;\n invariant(AST.isLiteral(literal.type));\n return literal.type.literal;\n })\n .filter(nonNullable);\n\n return literals.length ? [prop, S.Literal(...literals)] : undefined;\n })\n .filter(nonNullable),\n );\n\n const schema = S.Struct(fields);\n return schema.ast;\n};\n\n/**\n * Maps AST nodes.\n * The user is responsible for recursively calling {@link mapAst} on the AST.\n * NOTE: Will evaluate suspended ASTs.\n */\nexport const mapAst = (ast: AST.AST, f: (ast: AST.AST) => AST.AST): AST.AST => {\n switch (ast._tag) {\n case 'TypeLiteral':\n return new AST.TypeLiteral(\n ast.propertySignatures.map(\n (prop) =>\n new AST.PropertySignature(prop.name, f(prop.type), prop.isOptional, prop.isReadonly, prop.annotations),\n ),\n ast.indexSignatures,\n );\n case 'Union':\n return AST.Union.make(ast.types.map(f), ast.annotations);\n case 'TupleType':\n return new AST.TupleType(\n ast.elements.map((t) => new AST.OptionalType(f(t.type), t.isOptional, t.annotations)),\n ast.rest.map((t) => new AST.Type(f(t.type), t.annotations)),\n ast.isReadonly,\n ast.annotations,\n );\n case 'Suspend': {\n const newAst = f(ast.f());\n return new AST.Suspend(() => newAst, ast.annotations);\n }\n default:\n // TODO(dmaretskyi): Support more nodes.\n return ast;\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, type Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { decamelize } from '@dxos/util';\n\nconst ParamKeyAnnotationId = Symbol.for('@dxos/schema/annotation/ParamKey');\n\ntype ParamKeyAnnotationValue = { key: string };\n\nexport const getParamKeyAnnotation: (annotated: AST.Annotated) => Option.Option<ParamKeyAnnotationValue> =\n AST.getAnnotation<ParamKeyAnnotationValue>(ParamKeyAnnotationId);\n\nexport const ParamKeyAnnotation =\n (value: ParamKeyAnnotationValue) =>\n <S extends S.Annotable.All>(self: S): S.Annotable.Self<S> =>\n self.annotations({ [ParamKeyAnnotationId]: value });\n\n/**\n * HTTP params parser.\n * Supports custom key serialization.\n */\nexport class UrlParser<T extends Record<string, any>> {\n constructor(private readonly _schema: S.Struct<T>) {}\n\n /**\n * Parse URL params.\n */\n parse(_url: string): T {\n const url = new URL(_url);\n return Object.entries(this._schema.fields).reduce<Record<string, any>>((params, [key, type]) => {\n let value = url.searchParams.get(decamelize(key));\n if (value == null) {\n value = url.searchParams.get(key);\n }\n\n if (value != null) {\n if (AST.isNumberKeyword(type.ast)) {\n params[key] = parseInt(value);\n } else if (AST.isBooleanKeyword(type.ast)) {\n params[key] = value === 'true' || value === '1';\n } else {\n params[key] = value;\n }\n }\n\n return params;\n }, {}) as T;\n }\n\n /**\n * Return URL with encoded params.\n */\n create(_url: string, params: T): URL {\n const url = new URL(_url);\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined) {\n const field = this._schema.fields[key];\n if (field) {\n const { key: serializedKey } = pipe(\n getParamKeyAnnotation(field.ast),\n Option.getOrElse(() => ({\n key: decamelize(key),\n })),\n );\n\n url.searchParams.set(serializedKey, String(value));\n }\n }\n });\n\n return url;\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["import_schema", "import_effect", "import_util", "getSimpleType", "node", "AST", "isObjectKeyword", "isTypeLiteral", "isDiscriminatedUnion", "isStringKeyword", "isNumberKeyword", "isBooleanKeyword", "isEnums", "isLiteral", "isSimpleType", "PATH_REGEX", "PROP_REGEX", "JsonPath", "S", "NonEmptyString", "pipe", "pattern", "JsonProp", "VisitResult", "defaultTest", "visit", "testOrVisitor", "visitor", "visitNode", "test", "path", "depth", "_result", "result", "undefined", "prop", "getPropertySignatures", "currentPath", "name", "toString", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { AST, JSONSchema, Schema as S } from '@effect/schema';\nimport type * as Types from 'effect/Types';\n\n// TODO(dmaretskyi): Remove re-exports.\nexport { AST, JSONSchema, S, Types };\n\nexport * from './ast';\nexport * from './url';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { invariant } from '@dxos/invariant';\nimport { nonNullable } from '@dxos/util';\n\n//\n// Refs\n// https://effect.website/docs/schema/introduction\n// https://www.npmjs.com/package/@effect/schema\n// https://effect-ts.github.io/effect/schema/AST.ts.html\n//\n\nexport type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';\n\n/**\n * Get the base type; e.g., traverse through refinements.\n */\nexport const getSimpleType = (node: AST.AST): SimpleType | undefined => {\n if (AST.isObjectKeyword(node) || AST.isTypeLiteral(node) || isDiscriminatedUnion(node)) {\n return 'object';\n }\n\n if (AST.isStringKeyword(node)) {\n return 'string';\n }\n if (AST.isNumberKeyword(node)) {\n return 'number';\n }\n if (AST.isBooleanKeyword(node)) {\n return 'boolean';\n }\n\n if (AST.isEnums(node)) {\n return 'enum';\n }\n\n if (AST.isLiteral(node)) {\n return 'literal';\n }\n};\n\nexport const isSimpleType = (node: AST.AST): boolean => !!getSimpleType(node);\n\nexport namespace SimpleType {\n /**\n * Returns the default empty value for a given SimpleType.\n * Used for initializing new array values etc.\n */\n export const getDefaultValue = (type: SimpleType): any => {\n switch (type) {\n case 'string': {\n return '';\n }\n case 'number': {\n return 0;\n }\n case 'boolean': {\n return false;\n }\n case 'object': {\n return {};\n }\n default: {\n throw new Error(`Unsupported type for default value: ${type}`);\n }\n }\n };\n}\n\n//\n// Branded types\n//\n\nexport type JsonProp = string & { __JsonPath: true; __JsonProp: true };\nexport type JsonPath = string & { __JsonPath: true };\n\nconst PATH_REGEX = /[a-zA-Z_$][\\w$]*(?:\\.[a-zA-Z_$][\\w$]*)*/;\nconst PROP_REGEX = /\\w+/;\n\n/**\n * https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html\n */\nexport const JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX)) as any as S.Schema<JsonPath>;\nexport const JsonProp = S.NonEmptyString.pipe(S.pattern(PROP_REGEX)) as any as S.Schema<JsonProp>;\n\nexport enum VisitResult {\n CONTINUE = 0,\n /**\n * Skip visiting children.\n */\n SKIP = 1,\n /**\n * Stop traversing immediately.\n */\n EXIT = 2,\n}\n\nexport type Path = (string | number)[];\n\nexport type TestFn = (node: AST.AST, path: Path, depth: number) => VisitResult | boolean | undefined;\n\nexport type VisitorFn = (node: AST.AST, path: Path, depth: number) => void;\n\nconst defaultTest: TestFn = isSimpleType;\n\n/**\n * Visit leaf nodes.\n * Refs:\n * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor\n * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test\n */\nexport const visit: {\n (node: AST.AST, visitor: VisitorFn): void;\n (node: AST.AST, test: TestFn, visitor: VisitorFn): void;\n} = (node: AST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {\n if (!visitor) {\n visitNode(node, defaultTest, testOrVisitor);\n } else {\n visitNode(node, testOrVisitor as TestFn, visitor);\n }\n};\n\nconst visitNode = (\n node: AST.AST,\n test: TestFn | undefined,\n visitor: VisitorFn,\n path: Path = [],\n depth = 0,\n): VisitResult | undefined => {\n const _result = test?.(node, path, depth);\n const result: VisitResult =\n _result === undefined\n ? VisitResult.CONTINUE\n : typeof _result === 'boolean'\n ? _result\n ? VisitResult.CONTINUE\n : VisitResult.SKIP\n : _result;\n\n if (result === VisitResult.EXIT) {\n return result;\n }\n if (result !== VisitResult.SKIP) {\n visitor(node, path, depth);\n }\n\n // Object.\n if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const currentPath = [...path, prop.name.toString()];\n const result = visitNode(prop.type, test, visitor, currentPath, depth + 1);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Array.\n else if (AST.isTupleType(node)) {\n for (const [i, element] of node.elements.entries()) {\n const currentPath = [...path, i];\n const result = visitNode(element.type, test, visitor, currentPath, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n for (const type of node.types) {\n const result = visitNode(type, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n const result = visitNode(node.from, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n\n // TODO(burdon): Transforms?\n};\n\n/**\n * Recursively descend into AST to find first node that passes the test.\n */\n// TODO(burdon): Rewrite using visitNode?\nexport const findNode = (node: AST.AST, test: (node: AST.AST) => boolean): AST.AST | undefined => {\n if (test(node)) {\n return node;\n }\n\n // Object.\n else if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const child = findNode(prop.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Tuple.\n else if (AST.isTupleType(node)) {\n for (const [_, element] of node.elements.entries()) {\n const child = findNode(element.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n if (isOption(node)) {\n for (const type of node.types) {\n const child = findNode(type, test);\n if (child) {\n return child;\n }\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n return findNode(node.from, test);\n }\n};\n\n/**\n * Get the AST node for the given property (dot-path).\n */\nexport const findProperty = (schema: S.Schema<any>, path: JsonPath | JsonProp): AST.AST | undefined => {\n const getProp = (node: AST.AST, path: JsonProp[]): AST.AST | undefined => {\n const [name, ...rest] = path;\n const typeNode = findNode(node, AST.isTypeLiteral);\n invariant(typeNode);\n for (const prop of AST.getPropertySignatures(typeNode)) {\n if (prop.name === name) {\n if (rest.length) {\n return getProp(prop.type, rest);\n } else {\n return prop.type;\n }\n }\n }\n };\n\n return getProp(schema.ast, path.split('.') as JsonProp[]);\n};\n\n//\n// Annotations\n//\n\nconst defaultAnnotations: Record<string, AST.Annotated> = {\n ['ObjectKeyword' as const]: AST.objectKeyword,\n ['StringKeyword' as const]: AST.stringKeyword,\n ['NumberKeyword' as const]: AST.numberKeyword,\n ['BooleanKeyword' as const]: AST.booleanKeyword,\n};\n\n/**\n * Get annotation or return undefined.\n * @param annotationId\n * @param noDefault If true, then return undefined for effect library defined values.\n */\nexport const getAnnotation =\n <T>(annotationId: symbol, noDefault = true) =>\n (node: AST.AST): T | undefined => {\n // Title fallback seems to be the identifier.\n const id = pipe(AST.getIdentifierAnnotation(node), Option.getOrUndefined);\n const value = pipe(AST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);\n if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {\n return undefined;\n }\n\n return value;\n };\n\n/**\n * Recursively descend into AST to find first matching annotations.\n * Optionally skips default annotations for basic types (e.g., 'a string').\n */\n// TODO(burdon): Convert to effect pattern (i.e., return operator like getAnnotation).\nexport const findAnnotation = <T>(node: AST.AST, annotationId: symbol, noDefault = true): T | undefined => {\n const getAnnotationById = getAnnotation(annotationId, noDefault);\n\n const getBaseAnnotation = (node: AST.AST): T | undefined => {\n const value = getAnnotationById(node);\n if (value !== undefined) {\n return value as T;\n }\n\n if (AST.isUnion(node)) {\n if (isOption(node)) {\n return getAnnotationById(node.types[0]) as T;\n }\n }\n };\n\n return getBaseAnnotation(node);\n};\n\n//\n// Unions\n//\n\n/**\n * Effect S.optional creates a union type with undefined as the second type.\n */\nexport const isOption = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.length === 2 && AST.isUndefinedKeyword(node.types[1]);\n};\n\n/**\n * Determines if the node is a union of literal types.\n */\nexport const isLiteralUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.every(AST.isLiteral);\n};\n\n/**\n * Determines if the node is a discriminated union.\n */\nexport const isDiscriminatedUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && !!getDiscriminatingProps(node)?.length;\n};\n\n/**\n * Get the discriminating properties for the given union type.\n */\nexport const getDiscriminatingProps = (node: AST.AST): string[] | undefined => {\n invariant(AST.isUnion(node));\n if (isOption(node)) {\n return;\n }\n\n // Get common literals across all types.\n return node.types.reduce<string[]>((shared, type) => {\n const props = AST.getPropertySignatures(type)\n // TODO(burdon): Should check each literal is unique.\n .filter((p) => AST.isLiteral(p.type))\n .map((p) => p.name.toString());\n\n // Return common literals.\n return shared.length === 0 ? props : shared.filter((prop) => props.includes(prop));\n }, []);\n};\n\n/**\n * Get the discriminated type for the given value.\n */\nexport const getDiscriminatedType = (node: AST.AST, value: Record<string, any> = {}): AST.AST | undefined => {\n invariant(AST.isUnion(node));\n invariant(value);\n const props = getDiscriminatingProps(node);\n if (!props?.length) {\n return;\n }\n\n // Match provided values.\n for (const type of node.types) {\n const match = AST.getPropertySignatures(type)\n .filter((prop) => props?.includes(prop.name.toString()))\n .every((prop) => {\n invariant(AST.isLiteral(prop.type));\n return prop.type.literal === value[prop.name.toString()];\n });\n\n if (match) {\n return type;\n }\n }\n\n // Create union of discriminating properties.\n // NOTE: This may not work with non-overlapping variants.\n // TODO(burdon): Iterate through props and knock-out variants that don't match.\n const fields = Object.fromEntries(\n props\n .map((prop) => {\n const literals = node.types\n .map((type) => {\n const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop)!;\n invariant(AST.isLiteral(literal.type));\n return literal.type.literal;\n })\n .filter(nonNullable);\n\n return literals.length ? [prop, S.Literal(...literals)] : undefined;\n })\n .filter(nonNullable),\n );\n\n const schema = S.Struct(fields);\n return schema.ast;\n};\n\n/**\n * Maps AST nodes.\n * The user is responsible for recursively calling {@link mapAst} on the AST.\n * NOTE: Will evaluate suspended ASTs.\n */\nexport const mapAst = (ast: AST.AST, f: (ast: AST.AST) => AST.AST): AST.AST => {\n switch (ast._tag) {\n case 'TypeLiteral':\n return new AST.TypeLiteral(\n ast.propertySignatures.map(\n (prop) =>\n new AST.PropertySignature(prop.name, f(prop.type), prop.isOptional, prop.isReadonly, prop.annotations),\n ),\n ast.indexSignatures,\n );\n case 'Union':\n return AST.Union.make(ast.types.map(f), ast.annotations);\n case 'TupleType':\n return new AST.TupleType(\n ast.elements.map((t) => new AST.OptionalType(f(t.type), t.isOptional, t.annotations)),\n ast.rest.map((t) => new AST.Type(f(t.type), t.annotations)),\n ast.isReadonly,\n ast.annotations,\n );\n case 'Suspend': {\n const newAst = f(ast.f());\n return new AST.Suspend(() => newAst, ast.annotations);\n }\n default:\n // TODO(dmaretskyi): Support more nodes.\n return ast;\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, type Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { decamelize } from '@dxos/util';\n\nconst ParamKeyAnnotationId = Symbol.for('@dxos/schema/annotation/ParamKey');\n\ntype ParamKeyAnnotationValue = { key: string };\n\nexport const getParamKeyAnnotation: (annotated: AST.Annotated) => Option.Option<ParamKeyAnnotationValue> =\n AST.getAnnotation<ParamKeyAnnotationValue>(ParamKeyAnnotationId);\n\nexport const ParamKeyAnnotation =\n (value: ParamKeyAnnotationValue) =>\n <S extends S.Annotable.All>(self: S): S.Annotable.Self<S> =>\n self.annotations({ [ParamKeyAnnotationId]: value });\n\n/**\n * HTTP params parser.\n * Supports custom key serialization.\n */\nexport class UrlParser<T extends Record<string, any>> {\n constructor(private readonly _schema: S.Struct<T>) {}\n\n /**\n * Parse URL params.\n */\n parse(_url: string): T {\n const url = new URL(_url);\n return Object.entries(this._schema.fields).reduce<Record<string, any>>((params, [key, type]) => {\n let value = url.searchParams.get(decamelize(key));\n if (value == null) {\n value = url.searchParams.get(key);\n }\n\n if (value != null) {\n if (AST.isNumberKeyword(type.ast)) {\n params[key] = parseInt(value);\n } else if (AST.isBooleanKeyword(type.ast)) {\n params[key] = value === 'true' || value === '1';\n } else {\n params[key] = value;\n }\n }\n\n return params;\n }, {}) as T;\n }\n\n /**\n * Return URL with encoded params.\n */\n create(_url: string, params: T): URL {\n const url = new URL(_url);\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined) {\n const field = this._schema.fields[key];\n if (field) {\n const { key: serializedKey } = pipe(\n getParamKeyAnnotation(field.ast),\n Option.getOrElse(() => ({\n key: decamelize(key),\n })),\n );\n\n url.searchParams.set(serializedKey, String(value));\n }\n }\n });\n\n return url;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oBAA6C;ACA7C,IAAAA,iBAAiC;AACjC,oBAA6B;AAE7B,uBAA0B;AAC1B,kBAA4B;ACJ5B,IAAAA,iBAAsC;AACtC,IAAAC,iBAA6B;AAE7B,IAAAC,eAA2B;;ADepB,IAAMC,gBAAgB,CAACC,SAAAA;AAC5B,MAAIC,mBAAIC,gBAAgBF,IAAAA,KAASC,mBAAIE,cAAcH,IAAAA,KAASI,qBAAqBJ,IAAAA,GAAO;AACtF,WAAO;EACT;AAEA,MAAIC,mBAAII,gBAAgBL,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIC,mBAAIK,gBAAgBN,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIC,mBAAIM,iBAAiBP,IAAAA,GAAO;AAC9B,WAAO;EACT;AAEA,MAAIC,mBAAIO,QAAQR,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A;EACN;;;;EAKAM,OAAOT,MAAcG,QAAgB;AACnC,UAAMF,MAAM,IAAIC,IAAIF,IAAAA;AACpBjC,WAAOnD,QAAQuF,MAAAA,EAAQO,QAAQ,CAAC,CAACN,KAAK1D,KAAAA,MAAM;AAC1C,UAAIA,UAAUxC,QAAW;AACvB,cAAMyG,QAAQ,KAAKb,QAAQhC,OAAOsC,GAAAA;AAClC,YAAIO,OAAO;AACT,gBAAM,EAAEP,KAAKQ,cAAa,QAAKxH,eAAAA,MAC7BqG,sBAAsBkB,MAAM/E,GAAG,GAC/BY,eAAAA,OAAOqE,UAAU,OAAO;YACtBT,SAAKG,yBAAWH,GAAAA;UAClB,EAAA,CAAA;AAGFH,cAAII,aAAaS,IAAIF,eAAeG,OAAOrE,KAAAA,CAAAA;QAC7C;MACF;IACF,CAAA;AAEA,WAAOuD;EACT;AACF;",
|
|
6
|
+
"names": ["import_schema", "import_effect", "import_util", "getSimpleType", "node", "AST", "isObjectKeyword", "isTypeLiteral", "isDiscriminatedUnion", "isStringKeyword", "isNumberKeyword", "isBooleanKeyword", "isEnums", "isLiteral", "isSimpleType", "SimpleType", "getDefaultValue", "type", "Error", "PATH_REGEX", "PROP_REGEX", "JsonPath", "S", "NonEmptyString", "pipe", "pattern", "JsonProp", "VisitResult", "defaultTest", "visit", "testOrVisitor", "visitor", "visitNode", "test", "path", "depth", "_result", "result", "undefined", "prop", "getPropertySignatures", "currentPath", "name", "toString", "isTupleType", "i", "element", "elements", "entries", "isUnion", "types", "isRefinement", "from", "findNode", "child", "_", "isOption", "findProperty", "schema", "getProp", "rest", "typeNode", "invariant", "length", "ast", "split", "defaultAnnotations", "objectKeyword", "stringKeyword", "numberKeyword", "booleanKeyword", "getAnnotation", "annotationId", "noDefault", "id", "getIdentifierAnnotation", "Option", "getOrUndefined", "value", "_tag", "annotations", "findAnnotation", "getAnnotationById", "getBaseAnnotation", "isUndefinedKeyword", "isLiteralUnion", "every", "getDiscriminatingProps", "reduce", "shared", "props", "filter", "p", "map", "includes", "getDiscriminatedType", "match", "literal", "fields", "Object", "fromEntries", "literals", "find", "nonNullable", "Literal", "Struct", "mapAst", "f", "TypeLiteral", "propertySignatures", "PropertySignature", "isOptional", "isReadonly", "indexSignatures", "Union", "make", "TupleType", "t", "OptionalType", "Type", "newAst", "Suspend", "ParamKeyAnnotationId", "Symbol", "for", "getParamKeyAnnotation", "ParamKeyAnnotation", "self", "UrlParser", "constructor", "_schema", "parse", "_url", "url", "URL", "params", "key", "searchParams", "get", "decamelize", "parseInt", "create", "forEach", "field", "serializedKey", "getOrElse", "set", "String"]
|
|
7
7
|
}
|
package/dist/lib/node/meta.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/common/effect/src/ast.ts":{"bytes":
|
|
1
|
+
{"inputs":{"packages/common/effect/src/ast.ts":{"bytes":41444,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/common/effect/src/url.ts":{"bytes":7711,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/common/effect/src/index.ts":{"bytes":1150,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"packages/common/effect/src/ast.ts","kind":"import-statement","original":"./ast"},{"path":"packages/common/effect/src/url.ts","kind":"import-statement","original":"./url"}],"format":"esm"}},"outputs":{"packages/common/effect/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":25491},"packages/common/effect/dist/lib/node/index.cjs":{"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AST","JSONSchema","JsonPath","JsonProp","ParamKeyAnnotation","S","SimpleType","UrlParser","VisitResult","findAnnotation","findNode","findProperty","getAnnotation","getDiscriminatedType","getDiscriminatingProps","getParamKeyAnnotation","getSimpleType","isDiscriminatedUnion","isLiteralUnion","isOption","isSimpleType","mapAst","visit"],"entryPoint":"packages/common/effect/src/index.ts","inputs":{"packages/common/effect/src/index.ts":{"bytesInOutput":72},"packages/common/effect/src/ast.ts":{"bytesInOutput":8647},"packages/common/effect/src/url.ts":{"bytesInOutput":1624}},"bytes":10876}}}
|
|
@@ -30,6 +30,28 @@ var getSimpleType = (node) => {
|
|
|
30
30
|
}
|
|
31
31
|
};
|
|
32
32
|
var isSimpleType = (node) => !!getSimpleType(node);
|
|
33
|
+
var SimpleType;
|
|
34
|
+
(function(SimpleType2) {
|
|
35
|
+
SimpleType2.getDefaultValue = (type) => {
|
|
36
|
+
switch (type) {
|
|
37
|
+
case "string": {
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
case "number": {
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
case "boolean": {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
case "object": {
|
|
47
|
+
return {};
|
|
48
|
+
}
|
|
49
|
+
default: {
|
|
50
|
+
throw new Error(`Unsupported type for default value: ${type}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
})(SimpleType || (SimpleType = {}));
|
|
33
55
|
var PATH_REGEX = /[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)*/;
|
|
34
56
|
var PROP_REGEX = /\w+/;
|
|
35
57
|
var JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX));
|
|
@@ -129,7 +151,7 @@ var findProperty = (schema, path) => {
|
|
|
129
151
|
const typeNode = findNode(node, AST.isTypeLiteral);
|
|
130
152
|
invariant(typeNode, void 0, {
|
|
131
153
|
F: __dxlog_file,
|
|
132
|
-
L:
|
|
154
|
+
L: 249,
|
|
133
155
|
S: void 0,
|
|
134
156
|
A: [
|
|
135
157
|
"typeNode",
|
|
@@ -189,7 +211,7 @@ var isDiscriminatedUnion = (node) => {
|
|
|
189
211
|
var getDiscriminatingProps = (node) => {
|
|
190
212
|
invariant(AST.isUnion(node), void 0, {
|
|
191
213
|
F: __dxlog_file,
|
|
192
|
-
L:
|
|
214
|
+
L: 346,
|
|
193
215
|
S: void 0,
|
|
194
216
|
A: [
|
|
195
217
|
"AST.isUnion(node)",
|
|
@@ -207,7 +229,7 @@ var getDiscriminatingProps = (node) => {
|
|
|
207
229
|
var getDiscriminatedType = (node, value = {}) => {
|
|
208
230
|
invariant(AST.isUnion(node), void 0, {
|
|
209
231
|
F: __dxlog_file,
|
|
210
|
-
L:
|
|
232
|
+
L: 367,
|
|
211
233
|
S: void 0,
|
|
212
234
|
A: [
|
|
213
235
|
"AST.isUnion(node)",
|
|
@@ -216,7 +238,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
216
238
|
});
|
|
217
239
|
invariant(value, void 0, {
|
|
218
240
|
F: __dxlog_file,
|
|
219
|
-
L:
|
|
241
|
+
L: 368,
|
|
220
242
|
S: void 0,
|
|
221
243
|
A: [
|
|
222
244
|
"value",
|
|
@@ -231,7 +253,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
231
253
|
const match = AST.getPropertySignatures(type).filter((prop) => props?.includes(prop.name.toString())).every((prop) => {
|
|
232
254
|
invariant(AST.isLiteral(prop.type), void 0, {
|
|
233
255
|
F: __dxlog_file,
|
|
234
|
-
L:
|
|
256
|
+
L: 379,
|
|
235
257
|
S: void 0,
|
|
236
258
|
A: [
|
|
237
259
|
"AST.isLiteral(prop.type)",
|
|
@@ -249,7 +271,7 @@ var getDiscriminatedType = (node, value = {}) => {
|
|
|
249
271
|
const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop);
|
|
250
272
|
invariant(AST.isLiteral(literal.type), void 0, {
|
|
251
273
|
F: __dxlog_file,
|
|
252
|
-
L:
|
|
274
|
+
L: 397,
|
|
253
275
|
S: void 0,
|
|
254
276
|
A: [
|
|
255
277
|
"AST.isLiteral(literal.type)",
|
|
@@ -344,6 +366,7 @@ export {
|
|
|
344
366
|
JsonProp,
|
|
345
367
|
ParamKeyAnnotation,
|
|
346
368
|
S2 as S,
|
|
369
|
+
SimpleType,
|
|
347
370
|
UrlParser,
|
|
348
371
|
VisitResult,
|
|
349
372
|
findAnnotation,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/index.ts", "../../../src/ast.ts", "../../../src/url.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { AST, JSONSchema, Schema as S } from '@effect/schema';\nimport type * as Types from 'effect/Types';\n\n// TODO(dmaretskyi): Remove re-exports.\nexport { AST, JSONSchema, S, Types };\n\nexport * from './ast';\nexport * from './url';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { invariant } from '@dxos/invariant';\nimport { nonNullable } from '@dxos/util';\n\n//\n// Refs\n// https://effect.website/docs/schema/introduction\n// https://www.npmjs.com/package/@effect/schema\n// https://effect-ts.github.io/effect/schema/AST.ts.html\n//\n\nexport type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';\n\n/**\n * Get the base type; e.g., traverse through refinements.\n */\nexport const getSimpleType = (node: AST.AST): SimpleType | undefined => {\n if (AST.isObjectKeyword(node) || AST.isTypeLiteral(node) || isDiscriminatedUnion(node)) {\n return 'object';\n }\n\n if (AST.isStringKeyword(node)) {\n return 'string';\n }\n if (AST.isNumberKeyword(node)) {\n return 'number';\n }\n if (AST.isBooleanKeyword(node)) {\n return 'boolean';\n }\n\n if (AST.isEnums(node)) {\n return 'enum';\n }\n\n if (AST.isLiteral(node)) {\n return 'literal';\n }\n};\n\nexport const isSimpleType = (node: AST.AST): boolean => !!getSimpleType(node);\n\n//\n// Branded types\n//\n\nexport type JsonProp = string & { __JsonPath: true; __JsonProp: true };\nexport type JsonPath = string & { __JsonPath: true };\n\nconst PATH_REGEX = /[a-zA-Z_$][\\w$]*(?:\\.[a-zA-Z_$][\\w$]*)*/;\nconst PROP_REGEX = /\\w+/;\n\n/**\n * https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html\n */\nexport const JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX)) as any as S.Schema<JsonPath>;\nexport const JsonProp = S.NonEmptyString.pipe(S.pattern(PROP_REGEX)) as any as S.Schema<JsonProp>;\n\nexport enum VisitResult {\n CONTINUE = 0,\n /**\n * Skip visiting children.\n */\n SKIP = 1,\n /**\n * Stop traversing immediately.\n */\n EXIT = 2,\n}\n\nexport type Path = (string | number)[];\n\nexport type TestFn = (node: AST.AST, path: Path, depth: number) => VisitResult | boolean | undefined;\n\nexport type VisitorFn = (node: AST.AST, path: Path, depth: number) => void;\n\nconst defaultTest: TestFn = isSimpleType;\n\n/**\n * Visit leaf nodes.\n * Refs:\n * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor\n * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test\n */\nexport const visit: {\n (node: AST.AST, visitor: VisitorFn): void;\n (node: AST.AST, test: TestFn, visitor: VisitorFn): void;\n} = (node: AST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {\n if (!visitor) {\n visitNode(node, defaultTest, testOrVisitor);\n } else {\n visitNode(node, testOrVisitor as TestFn, visitor);\n }\n};\n\nconst visitNode = (\n node: AST.AST,\n test: TestFn | undefined,\n visitor: VisitorFn,\n path: Path = [],\n depth = 0,\n): VisitResult | undefined => {\n const _result = test?.(node, path, depth);\n const result: VisitResult =\n _result === undefined\n ? VisitResult.CONTINUE\n : typeof _result === 'boolean'\n ? _result\n ? VisitResult.CONTINUE\n : VisitResult.SKIP\n : _result;\n\n if (result === VisitResult.EXIT) {\n return result;\n }\n if (result !== VisitResult.SKIP) {\n visitor(node, path, depth);\n }\n\n // Object.\n if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const currentPath = [...path, prop.name.toString()];\n const result = visitNode(prop.type, test, visitor, currentPath, depth + 1);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Array.\n else if (AST.isTupleType(node)) {\n for (const [i, element] of node.elements.entries()) {\n const currentPath = [...path, i];\n const result = visitNode(element.type, test, visitor, currentPath, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n for (const type of node.types) {\n const result = visitNode(type, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n const result = visitNode(node.from, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n\n // TODO(burdon): Transforms?\n};\n\n/**\n * Recursively descend into AST to find first node that passes the test.\n */\n// TODO(burdon): Rewrite using visitNode?\nexport const findNode = (node: AST.AST, test: (node: AST.AST) => boolean): AST.AST | undefined => {\n if (test(node)) {\n return node;\n }\n\n // Object.\n else if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const child = findNode(prop.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Tuple.\n else if (AST.isTupleType(node)) {\n for (const [_, element] of node.elements.entries()) {\n const child = findNode(element.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n if (isOption(node)) {\n for (const type of node.types) {\n const child = findNode(type, test);\n if (child) {\n return child;\n }\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n return findNode(node.from, test);\n }\n};\n\n/**\n * Get the AST node for the given property (dot-path).\n */\nexport const findProperty = (schema: S.Schema<any>, path: JsonPath | JsonProp): AST.AST | undefined => {\n const getProp = (node: AST.AST, path: JsonProp[]): AST.AST | undefined => {\n const [name, ...rest] = path;\n const typeNode = findNode(node, AST.isTypeLiteral);\n invariant(typeNode);\n for (const prop of AST.getPropertySignatures(typeNode)) {\n if (prop.name === name) {\n if (rest.length) {\n return getProp(prop.type, rest);\n } else {\n return prop.type;\n }\n }\n }\n };\n\n return getProp(schema.ast, path.split('.') as JsonProp[]);\n};\n\n//\n// Annotations\n//\n\nconst defaultAnnotations: Record<string, AST.Annotated> = {\n ['ObjectKeyword' as const]: AST.objectKeyword,\n ['StringKeyword' as const]: AST.stringKeyword,\n ['NumberKeyword' as const]: AST.numberKeyword,\n ['BooleanKeyword' as const]: AST.booleanKeyword,\n};\n\n/**\n * Get annotation or return undefined.\n * @param annotationId\n * @param noDefault If true, then return undefined for effect library defined values.\n */\nexport const getAnnotation =\n <T>(annotationId: symbol, noDefault = true) =>\n (node: AST.AST): T | undefined => {\n // Title fallback seems to be the identifier.\n const id = pipe(AST.getIdentifierAnnotation(node), Option.getOrUndefined);\n const value = pipe(AST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);\n if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {\n return undefined;\n }\n\n return value;\n };\n\n/**\n * Recursively descend into AST to find first matching annotations.\n * Optionally skips default annotations for basic types (e.g., 'a string').\n */\n// TODO(burdon): Convert to effect pattern (i.e., return operator like getAnnotation).\nexport const findAnnotation = <T>(node: AST.AST, annotationId: symbol, noDefault = true): T | undefined => {\n const getAnnotationById = getAnnotation(annotationId, noDefault);\n\n const getBaseAnnotation = (node: AST.AST): T | undefined => {\n const value = getAnnotationById(node);\n if (value !== undefined) {\n return value as T;\n }\n\n if (AST.isUnion(node)) {\n if (isOption(node)) {\n return getAnnotationById(node.types[0]) as T;\n }\n }\n };\n\n return getBaseAnnotation(node);\n};\n\n//\n// Unions\n//\n\n/**\n * Effect S.optional creates a union type with undefined as the second type.\n */\nexport const isOption = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.length === 2 && AST.isUndefinedKeyword(node.types[1]);\n};\n\n/**\n * Determines if the node is a union of literal types.\n */\nexport const isLiteralUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.every(AST.isLiteral);\n};\n\n/**\n * Determines if the node is a discriminated union.\n */\nexport const isDiscriminatedUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && !!getDiscriminatingProps(node)?.length;\n};\n\n/**\n * Get the discriminating properties for the given union type.\n */\nexport const getDiscriminatingProps = (node: AST.AST): string[] | undefined => {\n invariant(AST.isUnion(node));\n if (isOption(node)) {\n return;\n }\n\n // Get common literals across all types.\n return node.types.reduce<string[]>((shared, type) => {\n const props = AST.getPropertySignatures(type)\n // TODO(burdon): Should check each literal is unique.\n .filter((p) => AST.isLiteral(p.type))\n .map((p) => p.name.toString());\n\n // Return common literals.\n return shared.length === 0 ? props : shared.filter((prop) => props.includes(prop));\n }, []);\n};\n\n/**\n * Get the discriminated type for the given value.\n */\nexport const getDiscriminatedType = (node: AST.AST, value: Record<string, any> = {}): AST.AST | undefined => {\n invariant(AST.isUnion(node));\n invariant(value);\n const props = getDiscriminatingProps(node);\n if (!props?.length) {\n return;\n }\n\n // Match provided values.\n for (const type of node.types) {\n const match = AST.getPropertySignatures(type)\n .filter((prop) => props?.includes(prop.name.toString()))\n .every((prop) => {\n invariant(AST.isLiteral(prop.type));\n return prop.type.literal === value[prop.name.toString()];\n });\n\n if (match) {\n return type;\n }\n }\n\n // Create union of discriminating properties.\n // NOTE: This may not work with non-overlapping variants.\n // TODO(burdon): Iterate through props and knock-out variants that don't match.\n const fields = Object.fromEntries(\n props\n .map((prop) => {\n const literals = node.types\n .map((type) => {\n const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop)!;\n invariant(AST.isLiteral(literal.type));\n return literal.type.literal;\n })\n .filter(nonNullable);\n\n return literals.length ? [prop, S.Literal(...literals)] : undefined;\n })\n .filter(nonNullable),\n );\n\n const schema = S.Struct(fields);\n return schema.ast;\n};\n\n/**\n * Maps AST nodes.\n * The user is responsible for recursively calling {@link mapAst} on the AST.\n * NOTE: Will evaluate suspended ASTs.\n */\nexport const mapAst = (ast: AST.AST, f: (ast: AST.AST) => AST.AST): AST.AST => {\n switch (ast._tag) {\n case 'TypeLiteral':\n return new AST.TypeLiteral(\n ast.propertySignatures.map(\n (prop) =>\n new AST.PropertySignature(prop.name, f(prop.type), prop.isOptional, prop.isReadonly, prop.annotations),\n ),\n ast.indexSignatures,\n );\n case 'Union':\n return AST.Union.make(ast.types.map(f), ast.annotations);\n case 'TupleType':\n return new AST.TupleType(\n ast.elements.map((t) => new AST.OptionalType(f(t.type), t.isOptional, t.annotations)),\n ast.rest.map((t) => new AST.Type(f(t.type), t.annotations)),\n ast.isReadonly,\n ast.annotations,\n );\n case 'Suspend': {\n const newAst = f(ast.f());\n return new AST.Suspend(() => newAst, ast.annotations);\n }\n default:\n // TODO(dmaretskyi): Support more nodes.\n return ast;\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, type Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { decamelize } from '@dxos/util';\n\nconst ParamKeyAnnotationId = Symbol.for('@dxos/schema/annotation/ParamKey');\n\ntype ParamKeyAnnotationValue = { key: string };\n\nexport const getParamKeyAnnotation: (annotated: AST.Annotated) => Option.Option<ParamKeyAnnotationValue> =\n AST.getAnnotation<ParamKeyAnnotationValue>(ParamKeyAnnotationId);\n\nexport const ParamKeyAnnotation =\n (value: ParamKeyAnnotationValue) =>\n <S extends S.Annotable.All>(self: S): S.Annotable.Self<S> =>\n self.annotations({ [ParamKeyAnnotationId]: value });\n\n/**\n * HTTP params parser.\n * Supports custom key serialization.\n */\nexport class UrlParser<T extends Record<string, any>> {\n constructor(private readonly _schema: S.Struct<T>) {}\n\n /**\n * Parse URL params.\n */\n parse(_url: string): T {\n const url = new URL(_url);\n return Object.entries(this._schema.fields).reduce<Record<string, any>>((params, [key, type]) => {\n let value = url.searchParams.get(decamelize(key));\n if (value == null) {\n value = url.searchParams.get(key);\n }\n\n if (value != null) {\n if (AST.isNumberKeyword(type.ast)) {\n params[key] = parseInt(value);\n } else if (AST.isBooleanKeyword(type.ast)) {\n params[key] = value === 'true' || value === '1';\n } else {\n params[key] = value;\n }\n }\n\n return params;\n }, {}) as T;\n }\n\n /**\n * Return URL with encoded params.\n */\n create(_url: string, params: T): URL {\n const url = new URL(_url);\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined) {\n const field = this._schema.fields[key];\n if (field) {\n const { key: serializedKey } = pipe(\n getParamKeyAnnotation(field.ast),\n Option.getOrElse(() => ({\n key: decamelize(key),\n })),\n );\n\n url.searchParams.set(serializedKey, String(value));\n }\n }\n });\n\n return url;\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;AAIA,SAASA,OAAAA,MAAKC,YAAYC,UAAUC,UAAS;;;ACA7C,SAASC,KAAKC,UAAUC,SAAS;AACjC,SAASC,QAAQC,YAAY;AAE7B,SAASC,iBAAiB;AAC1B,SAASC,mBAAmB;;AAcrB,IAAMC,gBAAgB,CAACC,SAAAA;AAC5B,MAAIR,IAAIS,gBAAgBD,IAAAA,KAASR,IAAIU,cAAcF,IAAAA,KAASG,qBAAqBH,IAAAA,GAAO;AACtF,WAAO;EACT;AAEA,MAAIR,IAAIY,gBAAgBJ,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIR,IAAIa,gBAAgBL,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIR,IAAIc,iBAAiBN,IAAAA,GAAO;AAC9B,WAAO;EACT;AAEA,MAAIR,IAAIe,QAAQP,IAAAA,GAAO;AACrB,WAAO;EACT;AAEA,MAAIR,IAAIgB,UAAUR,IAAAA,GAAO;AACvB,WAAO;EACT;AACF;AAEO,IAAMS,eAAe,CAACT,SAA2B,CAAC,CAACD,cAAcC,IAAAA;
|
|
6
|
-
"names": ["AST", "JSONSchema", "Schema", "S", "AST", "Schema", "S", "Option", "pipe", "invariant", "nonNullable", "getSimpleType", "node", "isObjectKeyword", "isTypeLiteral", "isDiscriminatedUnion", "isStringKeyword", "isNumberKeyword", "isBooleanKeyword", "isEnums", "isLiteral", "isSimpleType", "PATH_REGEX", "PROP_REGEX", "JsonPath", "NonEmptyString", "pattern", "JsonProp", "VisitResult", "defaultTest", "visit", "testOrVisitor", "visitor", "visitNode", "test", "path", "depth", "_result", "result", "undefined", "prop", "getPropertySignatures", "currentPath", "name", "toString", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { AST, JSONSchema, Schema as S } from '@effect/schema';\nimport type * as Types from 'effect/Types';\n\n// TODO(dmaretskyi): Remove re-exports.\nexport { AST, JSONSchema, S, Types };\n\nexport * from './ast';\nexport * from './url';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { invariant } from '@dxos/invariant';\nimport { nonNullable } from '@dxos/util';\n\n//\n// Refs\n// https://effect.website/docs/schema/introduction\n// https://www.npmjs.com/package/@effect/schema\n// https://effect-ts.github.io/effect/schema/AST.ts.html\n//\n\nexport type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';\n\n/**\n * Get the base type; e.g., traverse through refinements.\n */\nexport const getSimpleType = (node: AST.AST): SimpleType | undefined => {\n if (AST.isObjectKeyword(node) || AST.isTypeLiteral(node) || isDiscriminatedUnion(node)) {\n return 'object';\n }\n\n if (AST.isStringKeyword(node)) {\n return 'string';\n }\n if (AST.isNumberKeyword(node)) {\n return 'number';\n }\n if (AST.isBooleanKeyword(node)) {\n return 'boolean';\n }\n\n if (AST.isEnums(node)) {\n return 'enum';\n }\n\n if (AST.isLiteral(node)) {\n return 'literal';\n }\n};\n\nexport const isSimpleType = (node: AST.AST): boolean => !!getSimpleType(node);\n\nexport namespace SimpleType {\n /**\n * Returns the default empty value for a given SimpleType.\n * Used for initializing new array values etc.\n */\n export const getDefaultValue = (type: SimpleType): any => {\n switch (type) {\n case 'string': {\n return '';\n }\n case 'number': {\n return 0;\n }\n case 'boolean': {\n return false;\n }\n case 'object': {\n return {};\n }\n default: {\n throw new Error(`Unsupported type for default value: ${type}`);\n }\n }\n };\n}\n\n//\n// Branded types\n//\n\nexport type JsonProp = string & { __JsonPath: true; __JsonProp: true };\nexport type JsonPath = string & { __JsonPath: true };\n\nconst PATH_REGEX = /[a-zA-Z_$][\\w$]*(?:\\.[a-zA-Z_$][\\w$]*)*/;\nconst PROP_REGEX = /\\w+/;\n\n/**\n * https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html\n */\nexport const JsonPath = S.NonEmptyString.pipe(S.pattern(PATH_REGEX)) as any as S.Schema<JsonPath>;\nexport const JsonProp = S.NonEmptyString.pipe(S.pattern(PROP_REGEX)) as any as S.Schema<JsonProp>;\n\nexport enum VisitResult {\n CONTINUE = 0,\n /**\n * Skip visiting children.\n */\n SKIP = 1,\n /**\n * Stop traversing immediately.\n */\n EXIT = 2,\n}\n\nexport type Path = (string | number)[];\n\nexport type TestFn = (node: AST.AST, path: Path, depth: number) => VisitResult | boolean | undefined;\n\nexport type VisitorFn = (node: AST.AST, path: Path, depth: number) => void;\n\nconst defaultTest: TestFn = isSimpleType;\n\n/**\n * Visit leaf nodes.\n * Refs:\n * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor\n * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test\n */\nexport const visit: {\n (node: AST.AST, visitor: VisitorFn): void;\n (node: AST.AST, test: TestFn, visitor: VisitorFn): void;\n} = (node: AST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {\n if (!visitor) {\n visitNode(node, defaultTest, testOrVisitor);\n } else {\n visitNode(node, testOrVisitor as TestFn, visitor);\n }\n};\n\nconst visitNode = (\n node: AST.AST,\n test: TestFn | undefined,\n visitor: VisitorFn,\n path: Path = [],\n depth = 0,\n): VisitResult | undefined => {\n const _result = test?.(node, path, depth);\n const result: VisitResult =\n _result === undefined\n ? VisitResult.CONTINUE\n : typeof _result === 'boolean'\n ? _result\n ? VisitResult.CONTINUE\n : VisitResult.SKIP\n : _result;\n\n if (result === VisitResult.EXIT) {\n return result;\n }\n if (result !== VisitResult.SKIP) {\n visitor(node, path, depth);\n }\n\n // Object.\n if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const currentPath = [...path, prop.name.toString()];\n const result = visitNode(prop.type, test, visitor, currentPath, depth + 1);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Array.\n else if (AST.isTupleType(node)) {\n for (const [i, element] of node.elements.entries()) {\n const currentPath = [...path, i];\n const result = visitNode(element.type, test, visitor, currentPath, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n for (const type of node.types) {\n const result = visitNode(type, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n const result = visitNode(node.from, test, visitor, path, depth);\n if (result === VisitResult.EXIT) {\n return result;\n }\n }\n\n // TODO(burdon): Transforms?\n};\n\n/**\n * Recursively descend into AST to find first node that passes the test.\n */\n// TODO(burdon): Rewrite using visitNode?\nexport const findNode = (node: AST.AST, test: (node: AST.AST) => boolean): AST.AST | undefined => {\n if (test(node)) {\n return node;\n }\n\n // Object.\n else if (AST.isTypeLiteral(node)) {\n for (const prop of AST.getPropertySignatures(node)) {\n const child = findNode(prop.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Tuple.\n else if (AST.isTupleType(node)) {\n for (const [_, element] of node.elements.entries()) {\n const child = findNode(element.type, test);\n if (child) {\n return child;\n }\n }\n }\n\n // Branching union (e.g., optional, discriminated unions).\n else if (AST.isUnion(node)) {\n if (isOption(node)) {\n for (const type of node.types) {\n const child = findNode(type, test);\n if (child) {\n return child;\n }\n }\n }\n }\n\n // Refinement.\n else if (AST.isRefinement(node)) {\n return findNode(node.from, test);\n }\n};\n\n/**\n * Get the AST node for the given property (dot-path).\n */\nexport const findProperty = (schema: S.Schema<any>, path: JsonPath | JsonProp): AST.AST | undefined => {\n const getProp = (node: AST.AST, path: JsonProp[]): AST.AST | undefined => {\n const [name, ...rest] = path;\n const typeNode = findNode(node, AST.isTypeLiteral);\n invariant(typeNode);\n for (const prop of AST.getPropertySignatures(typeNode)) {\n if (prop.name === name) {\n if (rest.length) {\n return getProp(prop.type, rest);\n } else {\n return prop.type;\n }\n }\n }\n };\n\n return getProp(schema.ast, path.split('.') as JsonProp[]);\n};\n\n//\n// Annotations\n//\n\nconst defaultAnnotations: Record<string, AST.Annotated> = {\n ['ObjectKeyword' as const]: AST.objectKeyword,\n ['StringKeyword' as const]: AST.stringKeyword,\n ['NumberKeyword' as const]: AST.numberKeyword,\n ['BooleanKeyword' as const]: AST.booleanKeyword,\n};\n\n/**\n * Get annotation or return undefined.\n * @param annotationId\n * @param noDefault If true, then return undefined for effect library defined values.\n */\nexport const getAnnotation =\n <T>(annotationId: symbol, noDefault = true) =>\n (node: AST.AST): T | undefined => {\n // Title fallback seems to be the identifier.\n const id = pipe(AST.getIdentifierAnnotation(node), Option.getOrUndefined);\n const value = pipe(AST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);\n if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {\n return undefined;\n }\n\n return value;\n };\n\n/**\n * Recursively descend into AST to find first matching annotations.\n * Optionally skips default annotations for basic types (e.g., 'a string').\n */\n// TODO(burdon): Convert to effect pattern (i.e., return operator like getAnnotation).\nexport const findAnnotation = <T>(node: AST.AST, annotationId: symbol, noDefault = true): T | undefined => {\n const getAnnotationById = getAnnotation(annotationId, noDefault);\n\n const getBaseAnnotation = (node: AST.AST): T | undefined => {\n const value = getAnnotationById(node);\n if (value !== undefined) {\n return value as T;\n }\n\n if (AST.isUnion(node)) {\n if (isOption(node)) {\n return getAnnotationById(node.types[0]) as T;\n }\n }\n };\n\n return getBaseAnnotation(node);\n};\n\n//\n// Unions\n//\n\n/**\n * Effect S.optional creates a union type with undefined as the second type.\n */\nexport const isOption = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.length === 2 && AST.isUndefinedKeyword(node.types[1]);\n};\n\n/**\n * Determines if the node is a union of literal types.\n */\nexport const isLiteralUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && node.types.every(AST.isLiteral);\n};\n\n/**\n * Determines if the node is a discriminated union.\n */\nexport const isDiscriminatedUnion = (node: AST.AST): boolean => {\n return AST.isUnion(node) && !!getDiscriminatingProps(node)?.length;\n};\n\n/**\n * Get the discriminating properties for the given union type.\n */\nexport const getDiscriminatingProps = (node: AST.AST): string[] | undefined => {\n invariant(AST.isUnion(node));\n if (isOption(node)) {\n return;\n }\n\n // Get common literals across all types.\n return node.types.reduce<string[]>((shared, type) => {\n const props = AST.getPropertySignatures(type)\n // TODO(burdon): Should check each literal is unique.\n .filter((p) => AST.isLiteral(p.type))\n .map((p) => p.name.toString());\n\n // Return common literals.\n return shared.length === 0 ? props : shared.filter((prop) => props.includes(prop));\n }, []);\n};\n\n/**\n * Get the discriminated type for the given value.\n */\nexport const getDiscriminatedType = (node: AST.AST, value: Record<string, any> = {}): AST.AST | undefined => {\n invariant(AST.isUnion(node));\n invariant(value);\n const props = getDiscriminatingProps(node);\n if (!props?.length) {\n return;\n }\n\n // Match provided values.\n for (const type of node.types) {\n const match = AST.getPropertySignatures(type)\n .filter((prop) => props?.includes(prop.name.toString()))\n .every((prop) => {\n invariant(AST.isLiteral(prop.type));\n return prop.type.literal === value[prop.name.toString()];\n });\n\n if (match) {\n return type;\n }\n }\n\n // Create union of discriminating properties.\n // NOTE: This may not work with non-overlapping variants.\n // TODO(burdon): Iterate through props and knock-out variants that don't match.\n const fields = Object.fromEntries(\n props\n .map((prop) => {\n const literals = node.types\n .map((type) => {\n const literal = AST.getPropertySignatures(type).find((p) => p.name.toString() === prop)!;\n invariant(AST.isLiteral(literal.type));\n return literal.type.literal;\n })\n .filter(nonNullable);\n\n return literals.length ? [prop, S.Literal(...literals)] : undefined;\n })\n .filter(nonNullable),\n );\n\n const schema = S.Struct(fields);\n return schema.ast;\n};\n\n/**\n * Maps AST nodes.\n * The user is responsible for recursively calling {@link mapAst} on the AST.\n * NOTE: Will evaluate suspended ASTs.\n */\nexport const mapAst = (ast: AST.AST, f: (ast: AST.AST) => AST.AST): AST.AST => {\n switch (ast._tag) {\n case 'TypeLiteral':\n return new AST.TypeLiteral(\n ast.propertySignatures.map(\n (prop) =>\n new AST.PropertySignature(prop.name, f(prop.type), prop.isOptional, prop.isReadonly, prop.annotations),\n ),\n ast.indexSignatures,\n );\n case 'Union':\n return AST.Union.make(ast.types.map(f), ast.annotations);\n case 'TupleType':\n return new AST.TupleType(\n ast.elements.map((t) => new AST.OptionalType(f(t.type), t.isOptional, t.annotations)),\n ast.rest.map((t) => new AST.Type(f(t.type), t.annotations)),\n ast.isReadonly,\n ast.annotations,\n );\n case 'Suspend': {\n const newAst = f(ast.f());\n return new AST.Suspend(() => newAst, ast.annotations);\n }\n default:\n // TODO(dmaretskyi): Support more nodes.\n return ast;\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { AST, type Schema as S } from '@effect/schema';\nimport { Option, pipe } from 'effect';\n\nimport { decamelize } from '@dxos/util';\n\nconst ParamKeyAnnotationId = Symbol.for('@dxos/schema/annotation/ParamKey');\n\ntype ParamKeyAnnotationValue = { key: string };\n\nexport const getParamKeyAnnotation: (annotated: AST.Annotated) => Option.Option<ParamKeyAnnotationValue> =\n AST.getAnnotation<ParamKeyAnnotationValue>(ParamKeyAnnotationId);\n\nexport const ParamKeyAnnotation =\n (value: ParamKeyAnnotationValue) =>\n <S extends S.Annotable.All>(self: S): S.Annotable.Self<S> =>\n self.annotations({ [ParamKeyAnnotationId]: value });\n\n/**\n * HTTP params parser.\n * Supports custom key serialization.\n */\nexport class UrlParser<T extends Record<string, any>> {\n constructor(private readonly _schema: S.Struct<T>) {}\n\n /**\n * Parse URL params.\n */\n parse(_url: string): T {\n const url = new URL(_url);\n return Object.entries(this._schema.fields).reduce<Record<string, any>>((params, [key, type]) => {\n let value = url.searchParams.get(decamelize(key));\n if (value == null) {\n value = url.searchParams.get(key);\n }\n\n if (value != null) {\n if (AST.isNumberKeyword(type.ast)) {\n params[key] = parseInt(value);\n } else if (AST.isBooleanKeyword(type.ast)) {\n params[key] = value === 'true' || value === '1';\n } else {\n params[key] = value;\n }\n }\n\n return params;\n }, {}) as T;\n }\n\n /**\n * Return URL with encoded params.\n */\n create(_url: string, params: T): URL {\n const url = new URL(_url);\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined) {\n const field = this._schema.fields[key];\n if (field) {\n const { key: serializedKey } = pipe(\n getParamKeyAnnotation(field.ast),\n Option.getOrElse(() => ({\n key: decamelize(key),\n })),\n );\n\n url.searchParams.set(serializedKey, String(value));\n }\n }\n });\n\n return url;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;AAIA,SAASA,OAAAA,MAAKC,YAAYC,UAAUC,UAAS;;;ACA7C,SAASC,KAAKC,UAAUC,SAAS;AACjC,SAASC,QAAQC,YAAY;AAE7B,SAASC,iBAAiB;AAC1B,SAASC,mBAAmB;;AAcrB,IAAMC,gBAAgB,CAACC,SAAAA;AAC5B,MAAIR,IAAIS,gBAAgBD,IAAAA,KAASR,IAAIU,cAAcF,IAAAA,KAASG,qBAAqBH,IAAAA,GAAO;AACtF,WAAO;EACT;AAEA,MAAIR,IAAIY,gBAAgBJ,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIR,IAAIa,gBAAgBL,IAAAA,GAAO;AAC7B,WAAO;EACT;AACA,MAAIR,IAAIc,iBA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G,CAAC,CAAA;EACN;;;;EAKAU,OAAOjB,MAAcO,QAAgB;AACnC,UAAMN,MAAM,IAAIC,IAAIF,IAAAA;AACpBG,WAAOC,QAAQG,MAAAA,EAAQW,QAAQ,CAAC,CAACV,KAAKf,KAAAA,MAAM;AAC1C,UAAIA,UAAU0B,QAAW;AACvB,cAAMC,QAAQ,KAAKtB,QAAQO,OAAOG,GAAAA;AAClC,YAAIY,OAAO;AACT,gBAAM,EAAEZ,KAAKa,cAAa,IAAKC,MAC7BjC,sBAAsB+B,MAAMN,GAAG,GAC/BS,QAAOC,UAAU,OAAO;YACtBhB,KAAKI,WAAWJ,GAAAA;UAClB,EAAA,CAAA;AAGFP,cAAIS,aAAae,IAAIJ,eAAeK,OAAOjC,KAAAA,CAAAA;QAC7C;MACF;IACF,CAAA;AAEA,WAAOQ;EACT;AACF;",
|
|
6
|
+
"names": ["AST", "JSONSchema", "Schema", "S", "AST", "Schema", "S", "Option", "pipe", "invariant", "nonNullable", "getSimpleType", "node", "isObjectKeyword", "isTypeLiteral", "isDiscriminatedUnion", "isStringKeyword", "isNumberKeyword", "isBooleanKeyword", "isEnums", "isLiteral", "isSimpleType", "SimpleType", "getDefaultValue", "type", "Error", "PATH_REGEX", "PROP_REGEX", "JsonPath", "NonEmptyString", "pattern", "JsonProp", "VisitResult", "defaultTest", "visit", "testOrVisitor", "visitor", "visitNode", "test", "path", "depth", "_result", "result", "undefined", "prop", "getPropertySignatures", "currentPath", "name", "toString", "isTupleType", "i", "element", "elements", "entries", "isUnion", "types", "isRefinement", "from", "findNode", "child", "_", "isOption", "findProperty", "schema", "getProp", "rest", "typeNode", "length", "ast", "split", "defaultAnnotations", "objectKeyword", "stringKeyword", "numberKeyword", "booleanKeyword", "getAnnotation", "annotationId", "noDefault", "id", "getIdentifierAnnotation", "getOrUndefined", "value", "_tag", "annotations", "findAnnotation", "getAnnotationById", "getBaseAnnotation", "isUndefinedKeyword", "isLiteralUnion", "every", "getDiscriminatingProps", "reduce", "shared", "props", "filter", "p", "map", "includes", "getDiscriminatedType", "match", "literal", "fields", "Object", "fromEntries", "literals", "find", "Literal", "Struct", "mapAst", "f", "TypeLiteral", "propertySignatures", "PropertySignature", "isOptional", "isReadonly", "indexSignatures", "Union", "make", "TupleType", "t", "OptionalType", "Type", "newAst", "Suspend", "AST", "Option", "pipe", "decamelize", "ParamKeyAnnotationId", "Symbol", "for", "getParamKeyAnnotation", "AST", "getAnnotation", "ParamKeyAnnotation", "value", "self", "annotations", "UrlParser", "constructor", "_schema", "parse", "_url", "url", "URL", "Object", "entries", "fields", "reduce", "params", "key", "type", "searchParams", "get", "decamelize", "isNumberKeyword", "ast", "parseInt", "isBooleanKeyword", "create", "forEach", "undefined", "field", "serializedKey", "pipe", "Option", "getOrElse", "set", "String"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/common/effect/src/ast.ts":{"bytes":
|
|
1
|
+
{"inputs":{"packages/common/effect/src/ast.ts":{"bytes":41444,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/common/effect/src/url.ts":{"bytes":7711,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/common/effect/src/index.ts":{"bytes":1150,"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"packages/common/effect/src/ast.ts","kind":"import-statement","original":"./ast"},{"path":"packages/common/effect/src/url.ts","kind":"import-statement","original":"./url"}],"format":"esm"}},"outputs":{"packages/common/effect/dist/lib/node-esm/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":25493},"packages/common/effect/dist/lib/node-esm/index.mjs":{"imports":[{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@effect/schema","kind":"import-statement","external":true},{"path":"effect","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AST","JSONSchema","JsonPath","JsonProp","ParamKeyAnnotation","S","SimpleType","UrlParser","VisitResult","findAnnotation","findNode","findProperty","getAnnotation","getDiscriminatedType","getDiscriminatingProps","getParamKeyAnnotation","getSimpleType","isDiscriminatedUnion","isLiteralUnion","isOption","isSimpleType","mapAst","visit"],"entryPoint":"packages/common/effect/src/index.ts","inputs":{"packages/common/effect/src/index.ts":{"bytesInOutput":72},"packages/common/effect/src/ast.ts":{"bytesInOutput":8647},"packages/common/effect/src/url.ts":{"bytesInOutput":1624}},"bytes":10969}}}
|
package/dist/types/src/ast.d.ts
CHANGED
|
@@ -5,6 +5,13 @@ export type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | '
|
|
|
5
5
|
*/
|
|
6
6
|
export declare const getSimpleType: (node: AST.AST) => SimpleType | undefined;
|
|
7
7
|
export declare const isSimpleType: (node: AST.AST) => boolean;
|
|
8
|
+
export declare namespace SimpleType {
|
|
9
|
+
/**
|
|
10
|
+
* Returns the default empty value for a given SimpleType.
|
|
11
|
+
* Used for initializing new array values etc.
|
|
12
|
+
*/
|
|
13
|
+
const getDefaultValue: (type: SimpleType) => any;
|
|
14
|
+
}
|
|
8
15
|
export type JsonProp = string & {
|
|
9
16
|
__JsonPath: true;
|
|
10
17
|
__JsonProp: true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../../src/ast.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,GAAG,EAAE,MAAM,IAAI,CAAC,EAAE,MAAM,gBAAgB,CAAC;AAalD,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,SAAS,GA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,SAAU,GAAG,CAAC,GAAG,KAAG,OAE9C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,oBAAoB,SAAU,GAAG,CAAC,GAAG,KAAG,OAEpD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,SAAU,GAAG,CAAC,GAAG,KAAG,MAAM,EAAE,GAAG,SAgBjE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,oBAAoB,SAAU,GAAG,CAAC,GAAG,UAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAQ,GAAG,CAAC,GAAG,GAAG,SA2C/F,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,MAAM,QAAS,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,GAAG,KAAG,GAAG,CAAC,GA2BvE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxos/effect",
|
|
3
|
-
"version": "0.7.3
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Effect utils.",
|
|
5
5
|
"homepage": "https://dxos.org",
|
|
6
6
|
"bugs": "https://github.com/dxos/dxos/issues",
|
|
@@ -22,14 +22,14 @@
|
|
|
22
22
|
"src"
|
|
23
23
|
],
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@dxos/
|
|
26
|
-
"@dxos/
|
|
27
|
-
"@dxos/
|
|
25
|
+
"@dxos/node-std": "0.7.3",
|
|
26
|
+
"@dxos/invariant": "0.7.3",
|
|
27
|
+
"@dxos/util": "0.7.3"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@effect/schema": "^0.75.5",
|
|
31
31
|
"effect": "^3.9.2",
|
|
32
|
-
"@dxos/log": "0.7.3
|
|
32
|
+
"@dxos/log": "0.7.3"
|
|
33
33
|
},
|
|
34
34
|
"peerDependencies": {
|
|
35
35
|
"@effect/schema": "^0.75.5",
|
package/src/ast.ts
CHANGED
|
@@ -46,6 +46,32 @@ export const getSimpleType = (node: AST.AST): SimpleType | undefined => {
|
|
|
46
46
|
|
|
47
47
|
export const isSimpleType = (node: AST.AST): boolean => !!getSimpleType(node);
|
|
48
48
|
|
|
49
|
+
export namespace SimpleType {
|
|
50
|
+
/**
|
|
51
|
+
* Returns the default empty value for a given SimpleType.
|
|
52
|
+
* Used for initializing new array values etc.
|
|
53
|
+
*/
|
|
54
|
+
export const getDefaultValue = (type: SimpleType): any => {
|
|
55
|
+
switch (type) {
|
|
56
|
+
case 'string': {
|
|
57
|
+
return '';
|
|
58
|
+
}
|
|
59
|
+
case 'number': {
|
|
60
|
+
return 0;
|
|
61
|
+
}
|
|
62
|
+
case 'boolean': {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
case 'object': {
|
|
66
|
+
return {};
|
|
67
|
+
}
|
|
68
|
+
default: {
|
|
69
|
+
throw new Error(`Unsupported type for default value: ${type}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
49
75
|
//
|
|
50
76
|
// Branded types
|
|
51
77
|
//
|