@toloka-platform/sdk 0.25.2 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/toloka.js +185 -170
- package/dist/cli/toloka.js.jsc +0 -0
- package/dist/cli/toloka.js.jsc.sha256 +1 -1
- package/dist/cli/toloka.js.sha256 +1 -1
- package/examples/app-crowdtesting/nodes/app-flow-test/node.ts +24 -0
- package/examples/egocentric-video-collection/nodes/record-activity/node.ts +24 -0
- package/examples/face-image-collection/nodes/annotate-faces/node.ts +16 -1
- package/examples/product-moderation/nodes/moderate-product/instruction.ts +4 -0
- package/examples/product-moderation/nodes/moderate-product/node.ts +19 -0
- package/examples/video-pair-rating/nodes/adjudicate/node.ts +18 -1
- package/examples/video-pair-rating/nodes/adjudicate_op/node.ts +18 -1
- package/examples/video-pair-rating/nodes/overall_preference_pick/node.ts +18 -1
- package/examples/video-pair-rating/nodes/rate_pair/node.ts +18 -1
- package/openapi/gen/api.schemas.ts +50 -42
- package/package.json +3 -3
- package/skills/catalog.json +6 -6
- package/skills/toloka-build/SKILL.md +1 -1
- package/skills/toloka-build/references/human-work.md +97 -8
- package/skills/toloka-build/references/workflow-and-cli.md +2 -2
- package/src/authoring/index.ts +13 -2
- package/src/checks/task-ui-typecheck.ts +1 -1
- package/src/cli/analytics.ts +1 -0
- package/src/cli/commands/schema.ts +27 -0
- package/src/cli/program.ts +2 -0
- package/src/cli/schema.ts +633 -0
- package/src/graph-rules.json +3 -1
- package/src/pipeline-graph-v1.contract.json +12 -4
- package/src/validate.ts +23 -2
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, relative, sep } from "node:path";
|
|
3
|
+
import { isPlainObject } from "es-toolkit";
|
|
4
|
+
import ts from "typescript-api";
|
|
5
|
+
import { tsLibDirectory } from "../checks/task-ui-typecheck";
|
|
6
|
+
import { assertCli } from "./cli-error";
|
|
7
|
+
import type { CliIo } from "./context";
|
|
8
|
+
|
|
9
|
+
type Schema = { readonly [key: string]: unknown };
|
|
10
|
+
|
|
11
|
+
export type SchemaEntry = {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly module: string;
|
|
14
|
+
readonly kind: "function" | "type";
|
|
15
|
+
readonly summary: string;
|
|
16
|
+
readonly detail: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type SdkSchema = {
|
|
20
|
+
readonly version: string;
|
|
21
|
+
readonly entries: ReadonlyArray<SchemaEntry>;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const AUTHORING_ENTRY = "src/authoring/index.ts";
|
|
25
|
+
const TESTING_DIRECTORY = "src/testing";
|
|
26
|
+
const API_SCHEMAS_PATH = "openapi/gen/api.schemas.ts";
|
|
27
|
+
const CONTRACT_PATH = "src/pipeline-graph-v1.contract.json";
|
|
28
|
+
const SDK_PACKAGE = "@toloka-platform/sdk";
|
|
29
|
+
const MODULES = [
|
|
30
|
+
{ name: SDK_PACKAGE, entry: AUTHORING_ENTRY },
|
|
31
|
+
{ name: `${SDK_PACKAGE}/testing`, entry: `${TESTING_DIRECTORY}/index.ts` },
|
|
32
|
+
];
|
|
33
|
+
const MAX_DESCRIPTION_LENGTH = 240;
|
|
34
|
+
const MAX_LITERAL_LENGTH = 80;
|
|
35
|
+
const MAX_SUMMARY_LENGTH = 150;
|
|
36
|
+
const INDENT = " ";
|
|
37
|
+
|
|
38
|
+
const asSchema = (value: unknown): Schema | undefined => (isPlainObject(value) ? value : undefined);
|
|
39
|
+
|
|
40
|
+
const schemaOrNone = (value: unknown): Schema[] => {
|
|
41
|
+
const schema = asSchema(value);
|
|
42
|
+
return schema === undefined ? [] : [schema];
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const schemaList = (value: unknown): Schema[] =>
|
|
46
|
+
Array.isArray(value) ? value.flatMap(schemaOrNone) : [];
|
|
47
|
+
|
|
48
|
+
const truncate = (text: string, length: number): string =>
|
|
49
|
+
text.length <= length ? text : `${text.slice(0, length - 1).trimEnd()}…`;
|
|
50
|
+
|
|
51
|
+
const ancestors = (start: string): string[] => {
|
|
52
|
+
const parent = dirname(start);
|
|
53
|
+
return parent === start ? [start] : [start, ...ancestors(parent)];
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const isSdkRoot = (directory: string): boolean => {
|
|
57
|
+
try {
|
|
58
|
+
const metadata = asSchema(JSON.parse(readFileSync(join(directory, "package.json"), "utf8")));
|
|
59
|
+
return metadata?.["name"] === SDK_PACKAGE && existsSync(join(directory, AUTHORING_ENTRY));
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export const resolveSdkRoot = (sourceRoot: string, cliEntry = process.argv[1]): string => {
|
|
66
|
+
const root =
|
|
67
|
+
ancestors(sourceRoot)
|
|
68
|
+
.map((directory) => join(directory, "node_modules", SDK_PACKAGE))
|
|
69
|
+
.find(isSdkRoot) ??
|
|
70
|
+
(cliEntry === undefined ? undefined : ancestors(dirname(cliEntry)).find(isSdkRoot));
|
|
71
|
+
assertCli(root, `Cannot find the ${SDK_PACKAGE} sources to describe.`, {
|
|
72
|
+
hint: {
|
|
73
|
+
description: `Run toloka schema inside a pipeline project with ${SDK_PACKAGE} installed in node_modules.`,
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
return root;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const createSchemaContract = (contract: Schema) => {
|
|
80
|
+
const definitions = asSchema(contract["$defs"]) ?? {};
|
|
81
|
+
const resolveReference = (schema: Schema, seen = new Set<string>()): Schema => {
|
|
82
|
+
const reference = schema["$ref"];
|
|
83
|
+
if (typeof reference !== "string" || seen.has(reference)) return schema;
|
|
84
|
+
const target = asSchema(definitions[reference.replace("#/$defs/", "")]);
|
|
85
|
+
return target === undefined ? schema : resolveReference(target, new Set(seen).add(reference));
|
|
86
|
+
};
|
|
87
|
+
const variants = (schema: Schema): Schema[] => {
|
|
88
|
+
const resolved = resolveReference(schema);
|
|
89
|
+
const nested = [
|
|
90
|
+
...schemaList(resolved["oneOf"]),
|
|
91
|
+
...schemaList(resolved["anyOf"]),
|
|
92
|
+
...schemaList(resolved["allOf"]),
|
|
93
|
+
];
|
|
94
|
+
return nested.length === 0 ? [resolved] : nested.flatMap(variants);
|
|
95
|
+
};
|
|
96
|
+
const property = (schemas: readonly Schema[], name: string): Schema[] =>
|
|
97
|
+
schemas
|
|
98
|
+
.flatMap(variants)
|
|
99
|
+
.flatMap((schema) => schemaOrNone(asSchema(schema["properties"])?.[name]))
|
|
100
|
+
.map((schema) => resolveReference(schema));
|
|
101
|
+
const items = (schemas: readonly Schema[]): Schema[] =>
|
|
102
|
+
schemas.flatMap(variants).flatMap((schema) => schemaOrNone(schema["items"]));
|
|
103
|
+
const nodeSettings = (type: string): Schema[] =>
|
|
104
|
+
property(
|
|
105
|
+
items([asSchema(asSchema(contract["properties"])?.["nodes"]) ?? {}])
|
|
106
|
+
.flatMap(variants)
|
|
107
|
+
.filter((node) => property([node], "type").some((schema) => schema["const"] === type)),
|
|
108
|
+
"settings",
|
|
109
|
+
);
|
|
110
|
+
return { variants, property, items, nodeSettings };
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const BOUNDS = [
|
|
114
|
+
{ key: "minimum", label: "min" },
|
|
115
|
+
{ key: "exclusiveMinimum", label: ">" },
|
|
116
|
+
{ key: "maximum", label: "max" },
|
|
117
|
+
{ key: "exclusiveMaximum", label: "<" },
|
|
118
|
+
{ key: "minLength", label: "min length" },
|
|
119
|
+
{ key: "maxLength", label: "max length" },
|
|
120
|
+
{ key: "minItems", label: "min items" },
|
|
121
|
+
{ key: "maxItems", label: "max items" },
|
|
122
|
+
];
|
|
123
|
+
|
|
124
|
+
const literalText = (value: unknown): string =>
|
|
125
|
+
truncate(JSON.stringify(value) ?? "undefined", MAX_LITERAL_LENGTH);
|
|
126
|
+
|
|
127
|
+
const annotation = (schemas: readonly Schema[]): string => {
|
|
128
|
+
const first = (key: string): unknown =>
|
|
129
|
+
schemas.find((schema) => schema[key] !== undefined)?.[key];
|
|
130
|
+
const bounds = BOUNDS.flatMap(({ key, label }) => {
|
|
131
|
+
const value = first(key);
|
|
132
|
+
return typeof value === "number" && Math.abs(value) !== Number.MAX_SAFE_INTEGER
|
|
133
|
+
? [`${label} ${value}`]
|
|
134
|
+
: [];
|
|
135
|
+
});
|
|
136
|
+
const fallback = first("default");
|
|
137
|
+
const description = first("description");
|
|
138
|
+
const parts = [
|
|
139
|
+
...bounds,
|
|
140
|
+
...(fallback === undefined ? [] : [`default ${literalText(fallback)}`]),
|
|
141
|
+
...(typeof description === "string"
|
|
142
|
+
? [truncate(description.replace(/\s+/gu, " ").trim(), MAX_DESCRIPTION_LENGTH)]
|
|
143
|
+
: []),
|
|
144
|
+
];
|
|
145
|
+
return parts.length === 0 ? "" : ` // ${parts.join("; ")}`;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const REQUIRED_FILES = [
|
|
149
|
+
AUTHORING_ENTRY,
|
|
150
|
+
CONTRACT_PATH,
|
|
151
|
+
API_SCHEMAS_PATH,
|
|
152
|
+
`${TESTING_DIRECTORY}/index.ts`,
|
|
153
|
+
];
|
|
154
|
+
|
|
155
|
+
export const describeSdkSchema = (sdkRoot: string): SdkSchema => {
|
|
156
|
+
const packageJson = asSchema(JSON.parse(readFileSync(join(sdkRoot, "package.json"), "utf8")));
|
|
157
|
+
const version = typeof packageJson?.["version"] === "string" ? packageJson["version"] : "unknown";
|
|
158
|
+
const missing = REQUIRED_FILES.filter((file) => !existsSync(join(sdkRoot, file)));
|
|
159
|
+
assertCli(
|
|
160
|
+
missing.length === 0,
|
|
161
|
+
`The installed ${SDK_PACKAGE} ${version} at ${sdkRoot} is too old for toloka schema: it has no ${missing.join(", ")}.`,
|
|
162
|
+
{
|
|
163
|
+
hint: {
|
|
164
|
+
description: `Update ${SDK_PACKAGE} in the project to the version of this CLI, then run toloka schema again.`,
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
);
|
|
168
|
+
const contract = createSchemaContract(
|
|
169
|
+
asSchema(JSON.parse(readFileSync(join(sdkRoot, CONTRACT_PATH), "utf8"))) ?? {},
|
|
170
|
+
);
|
|
171
|
+
const options: ts.CompilerOptions = {
|
|
172
|
+
target: ts.ScriptTarget.ES2022,
|
|
173
|
+
module: ts.ModuleKind.ESNext,
|
|
174
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
175
|
+
strict: true,
|
|
176
|
+
noEmit: true,
|
|
177
|
+
skipLibCheck: true,
|
|
178
|
+
noResolve: true,
|
|
179
|
+
types: [],
|
|
180
|
+
lib: ["lib.es2015.d.ts"],
|
|
181
|
+
};
|
|
182
|
+
const host = ts.createCompilerHost(options);
|
|
183
|
+
host.getDefaultLibLocation = () => tsLibDirectory;
|
|
184
|
+
host.getDefaultLibFileName = (compilerOptions) =>
|
|
185
|
+
join(tsLibDirectory, ts.getDefaultLibFileName(compilerOptions));
|
|
186
|
+
const testingFiles = readdirSync(join(sdkRoot, TESTING_DIRECTORY))
|
|
187
|
+
.filter((file) => file.endsWith(".ts") && !file.includes(".spec."))
|
|
188
|
+
.map((file) => join(sdkRoot, TESTING_DIRECTORY, file));
|
|
189
|
+
const program = ts.createProgram(
|
|
190
|
+
[join(sdkRoot, AUTHORING_ENTRY), join(sdkRoot, API_SCHEMAS_PATH), ...testingFiles],
|
|
191
|
+
options,
|
|
192
|
+
host,
|
|
193
|
+
);
|
|
194
|
+
const checker = program.getTypeChecker();
|
|
195
|
+
const modules = MODULES.map((module) => {
|
|
196
|
+
const path = join(sdkRoot, module.entry);
|
|
197
|
+
const file = program.getSourceFile(path);
|
|
198
|
+
assertCli(file, `Cannot read ${path}.`, { hint: { disabled: true } });
|
|
199
|
+
const symbol = checker.getSymbolAtLocation(file);
|
|
200
|
+
assertCli(symbol, `Cannot read the exports of ${path}.`, { hint: { disabled: true } });
|
|
201
|
+
const symbols = checker
|
|
202
|
+
.getExportsOfModule(symbol)
|
|
203
|
+
.map((exported) =>
|
|
204
|
+
exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported,
|
|
205
|
+
);
|
|
206
|
+
return { name: module.name, file, symbols };
|
|
207
|
+
});
|
|
208
|
+
const source = modules[0]!.file;
|
|
209
|
+
|
|
210
|
+
const withoutImports = (text: string): string => text.replace(/import\("[^"]*"\)\./gu, "");
|
|
211
|
+
const printType = (type: ts.Type): string =>
|
|
212
|
+
withoutImports(checker.typeToString(type, source, ts.TypeFormatFlags.NoTruncation));
|
|
213
|
+
const printSignature = (signature: ts.Signature, arrow = false): string =>
|
|
214
|
+
withoutImports(
|
|
215
|
+
checker.signatureToString(
|
|
216
|
+
signature,
|
|
217
|
+
source,
|
|
218
|
+
ts.TypeFormatFlags.NoTruncation |
|
|
219
|
+
(arrow ? ts.TypeFormatFlags.WriteArrowStyleSignature : ts.TypeFormatFlags.None),
|
|
220
|
+
),
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
const isSdkDeclaration = (declaration: ts.Declaration): boolean => {
|
|
224
|
+
const path = relative(sdkRoot, declaration.getSourceFile().fileName);
|
|
225
|
+
return !path.startsWith("..") && !path.split(sep).includes("node_modules");
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const elementType = (type: ts.Type): ts.Type | undefined =>
|
|
229
|
+
checker.isArrayType(type) || checker.isTupleType(type)
|
|
230
|
+
? checker.getIndexTypeOfType(type, ts.IndexKind.Number)
|
|
231
|
+
: undefined;
|
|
232
|
+
|
|
233
|
+
const typeName = (type: ts.Type): string | undefined => {
|
|
234
|
+
if (elementType(type) !== undefined) return undefined;
|
|
235
|
+
const alias = type.aliasSymbol;
|
|
236
|
+
if (alias !== undefined) {
|
|
237
|
+
return (type.aliasTypeArguments ?? []).every((argument) => !isObjectLike(argument)) &&
|
|
238
|
+
(alias.declarations ?? []).some(isSdkDeclaration)
|
|
239
|
+
? alias.name
|
|
240
|
+
: undefined;
|
|
241
|
+
}
|
|
242
|
+
const symbol = type.getSymbol();
|
|
243
|
+
if (symbol === undefined || !(symbol.flags & ts.SymbolFlags.Interface)) return undefined;
|
|
244
|
+
return (symbol.declarations ?? []).some(isSdkDeclaration) ? symbol.name : undefined;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
const isObjectLike = (type: ts.Type): boolean =>
|
|
248
|
+
Boolean(type.flags & ts.TypeFlags.Object) ||
|
|
249
|
+
(type.isIntersection() && type.types.some(isObjectLike)) ||
|
|
250
|
+
(type.isUnion() && type.types.some(isObjectLike));
|
|
251
|
+
|
|
252
|
+
const named = new Map<string, ts.Type>();
|
|
253
|
+
const schemasByName = new Map<string, Schema[]>();
|
|
254
|
+
const discover = (name: string, type: ts.Type, schemas: readonly Schema[]): void => {
|
|
255
|
+
named.set(name, named.get(name) ?? type);
|
|
256
|
+
const known = schemasByName.get(name) ?? [];
|
|
257
|
+
const added = schemas.filter((schema) => !known.includes(schema));
|
|
258
|
+
if (added.length > 0) schemasByName.set(name, [...known, ...added]);
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
const visibleProperties = (type: ts.Type): ts.Symbol[] =>
|
|
262
|
+
checker
|
|
263
|
+
.getPropertiesOfType(type)
|
|
264
|
+
.filter((property) => !String(property.escapedName).startsWith("__@"));
|
|
265
|
+
|
|
266
|
+
const definedType = (type: ts.Type): ts.Type => {
|
|
267
|
+
if (!type.isUnion()) return type;
|
|
268
|
+
const parts = type.types.filter((part) => !(part.flags & ts.TypeFlags.Undefined));
|
|
269
|
+
return parts.length === 1 ? parts[0]! : type;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const propertyType = (property: ts.Symbol): ts.Type =>
|
|
273
|
+
definedType(checker.getTypeOfSymbolAtLocation(property, source));
|
|
274
|
+
|
|
275
|
+
const literalValue = (type: ts.Type): string | number | boolean | undefined => {
|
|
276
|
+
if (type.isStringLiteral() || type.isNumberLiteral()) return type.value;
|
|
277
|
+
return type.flags & ts.TypeFlags.BooleanLiteral
|
|
278
|
+
? checker.typeToString(type) === "true"
|
|
279
|
+
: undefined;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const matchingVariants = (type: ts.Type, schemas: readonly Schema[]): Schema[] => {
|
|
283
|
+
const all = schemas.flatMap(contract.variants);
|
|
284
|
+
if (all.length <= 1) return all;
|
|
285
|
+
return all.filter((schema) => {
|
|
286
|
+
const declared = asSchema(schema["properties"]);
|
|
287
|
+
return visibleProperties(type).every((property) => {
|
|
288
|
+
if (
|
|
289
|
+
declared !== undefined &&
|
|
290
|
+
!(property.flags & ts.SymbolFlags.Optional) &&
|
|
291
|
+
!(property.name in declared)
|
|
292
|
+
)
|
|
293
|
+
return false;
|
|
294
|
+
const value = literalValue(propertyType(property));
|
|
295
|
+
if (value === undefined) return true;
|
|
296
|
+
return contract.property([schema], property.name).every((constraint) => {
|
|
297
|
+
if (constraint["const"] !== undefined) return constraint["const"] === value;
|
|
298
|
+
return Array.isArray(constraint["enum"]) ? constraint["enum"].includes(value) : true;
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
});
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const unionParts = (type: ts.UnionType, schemas: readonly Schema[], depth: number): string[] => {
|
|
305
|
+
const parts = type.types.filter((part) => !(part.flags & ts.TypeFlags.Undefined));
|
|
306
|
+
const booleans = parts.filter((part) => part.flags & ts.TypeFlags.BooleanLiteral);
|
|
307
|
+
const rest = booleans.length === 2 ? parts.filter((part) => !booleans.includes(part)) : parts;
|
|
308
|
+
return [
|
|
309
|
+
...(booleans.length === 2 ? ["boolean"] : []),
|
|
310
|
+
...rest.map((part) =>
|
|
311
|
+
format(
|
|
312
|
+
part,
|
|
313
|
+
isObjectLike(part) && elementType(part) === undefined
|
|
314
|
+
? matchingVariants(part, schemas)
|
|
315
|
+
: schemas,
|
|
316
|
+
depth,
|
|
317
|
+
),
|
|
318
|
+
),
|
|
319
|
+
];
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const format = (
|
|
323
|
+
type: ts.Type,
|
|
324
|
+
schemas: readonly Schema[],
|
|
325
|
+
depth: number,
|
|
326
|
+
top = false,
|
|
327
|
+
): string => {
|
|
328
|
+
if (type.flags & ts.TypeFlags.Boolean) return "boolean";
|
|
329
|
+
const name = top ? undefined : typeName(type);
|
|
330
|
+
if (name !== undefined && isObjectLike(type)) {
|
|
331
|
+
discover(name, type, schemas);
|
|
332
|
+
return name;
|
|
333
|
+
}
|
|
334
|
+
const element = elementType(type);
|
|
335
|
+
if (element !== undefined) {
|
|
336
|
+
const inner = format(element, contract.items(schemas), depth);
|
|
337
|
+
return typeName(element) === undefined &&
|
|
338
|
+
element.isUnion() &&
|
|
339
|
+
!(element.flags & ts.TypeFlags.Boolean)
|
|
340
|
+
? `(${inner})[]`
|
|
341
|
+
: `${inner}[]`;
|
|
342
|
+
}
|
|
343
|
+
if (type.isUnion()) return unionParts(type, schemas, depth).join(" | ");
|
|
344
|
+
const signatures = type.getCallSignatures();
|
|
345
|
+
if (signatures.length > 0 && visibleProperties(type).length === 0) {
|
|
346
|
+
return signatures.map((signature) => printSignature(signature, true)).join(" & ");
|
|
347
|
+
}
|
|
348
|
+
const symbol = type.getSymbol();
|
|
349
|
+
if (
|
|
350
|
+
(symbol?.flags ?? 0) & (ts.SymbolFlags.Interface | ts.SymbolFlags.Class) &&
|
|
351
|
+
!(symbol?.declarations ?? []).some(isSdkDeclaration)
|
|
352
|
+
) {
|
|
353
|
+
return printType(type);
|
|
354
|
+
}
|
|
355
|
+
if (isObjectLike(type)) return formatObject(type, schemas, depth);
|
|
356
|
+
return printType(type);
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
const formatObject = (type: ts.Type, schemas: readonly Schema[], depth: number): string => {
|
|
360
|
+
const pad = INDENT.repeat(depth + 1);
|
|
361
|
+
const lines = visibleProperties(type).map((property) => {
|
|
362
|
+
const childSchemas = contract.property(schemas, property.name);
|
|
363
|
+
const value = propertyType(property);
|
|
364
|
+
const [method] = value.getCallSignatures();
|
|
365
|
+
if (property.flags & ts.SymbolFlags.Method && method !== undefined) {
|
|
366
|
+
return `${pad}${property.name}${printSignature(method)}`;
|
|
367
|
+
}
|
|
368
|
+
const optional = property.flags & ts.SymbolFlags.Optional ? "?" : "";
|
|
369
|
+
const [firstLine, ...rest] = format(value, childSchemas, depth + 1).split("\n");
|
|
370
|
+
return [
|
|
371
|
+
`${pad}${property.name}${optional}: ${firstLine}${annotation(childSchemas)}`,
|
|
372
|
+
...rest,
|
|
373
|
+
].join("\n");
|
|
374
|
+
});
|
|
375
|
+
const indexType = checker.getIndexTypeOfType(type, ts.IndexKind.String);
|
|
376
|
+
if (indexType !== undefined) {
|
|
377
|
+
const valueSchemas = schemas
|
|
378
|
+
.flatMap(contract.variants)
|
|
379
|
+
.flatMap((schema) => schemaOrNone(schema["additionalProperties"]));
|
|
380
|
+
lines.push(`${pad}[key: string]: ${format(indexType, valueSchemas, depth + 1)}`);
|
|
381
|
+
}
|
|
382
|
+
return lines.length === 0 ? "{}" : `{\n${lines.join("\n")}\n${INDENT.repeat(depth)}}`;
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const describeType = (name: string, type: ts.Type): string => {
|
|
386
|
+
const schemas = schemasByName.get(name) ?? [];
|
|
387
|
+
const declaration = ((type.aliasSymbol ?? type.getSymbol())?.declarations ?? []).find(
|
|
388
|
+
(candidate) => ts.isTypeAliasDeclaration(candidate) || ts.isInterfaceDeclaration(candidate),
|
|
389
|
+
);
|
|
390
|
+
const typeParameters =
|
|
391
|
+
declaration !== undefined &&
|
|
392
|
+
(ts.isTypeAliasDeclaration(declaration) || ts.isInterfaceDeclaration(declaration)) &&
|
|
393
|
+
declaration.typeParameters !== undefined
|
|
394
|
+
? `<${declaration.typeParameters.map((parameter) => parameter.getText()).join(", ")}>`
|
|
395
|
+
: "";
|
|
396
|
+
const head = `${name}${typeParameters}${annotation(schemas)}`;
|
|
397
|
+
if (type.isUnion() && type.types.some(isObjectLike)) {
|
|
398
|
+
return [
|
|
399
|
+
head,
|
|
400
|
+
"one of:",
|
|
401
|
+
...unionParts(type, schemas, 1).map((part) => `${INDENT}| ${part}`),
|
|
402
|
+
].join("\n");
|
|
403
|
+
}
|
|
404
|
+
return `${head}\n${format(type, schemas, 0, true)}`;
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
const summarizeType = (type: ts.Type): string => {
|
|
408
|
+
if (type.isUnion() && type.types.some(isObjectLike)) {
|
|
409
|
+
const parts = type.types.filter((part) => !(part.flags & ts.TypeFlags.Undefined));
|
|
410
|
+
const discriminant = visibleProperties(parts[0]!).find((property) =>
|
|
411
|
+
parts.every((part) => {
|
|
412
|
+
const candidate = part.getProperty(property.name);
|
|
413
|
+
return candidate !== undefined && literalValue(propertyType(candidate)) !== undefined;
|
|
414
|
+
}),
|
|
415
|
+
);
|
|
416
|
+
return `one of ${parts.length} variants${discriminant === undefined ? "" : ` by ${discriminant.name}`}`;
|
|
417
|
+
}
|
|
418
|
+
const keys = visibleProperties(type).map(
|
|
419
|
+
(property) => `${property.name}${property.flags & ts.SymbolFlags.Optional ? "?" : ""}`,
|
|
420
|
+
);
|
|
421
|
+
const indexType = checker.getIndexTypeOfType(type, ts.IndexKind.String);
|
|
422
|
+
if (keys.length === 0 && indexType !== undefined)
|
|
423
|
+
return `{ [key: string]: ${format(indexType, [], 0).replace(/\s*\n\s*/gu, " ")} }`;
|
|
424
|
+
return `{ ${keys.join(", ")} }`;
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
const callableProperties = (owner: string, type: ts.Type) =>
|
|
428
|
+
visibleProperties(type).flatMap((property) => {
|
|
429
|
+
const value = checker.getTypeOfSymbolAtLocation(property, source);
|
|
430
|
+
return value.getCallSignatures().length === 0
|
|
431
|
+
? []
|
|
432
|
+
: [{ name: `${owner}.${property.name}`, type: value }];
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
const assignedObjects = (symbol: ts.Symbol): ts.Type[] => {
|
|
436
|
+
const declaration = symbol.valueDeclaration;
|
|
437
|
+
if (
|
|
438
|
+
declaration === undefined ||
|
|
439
|
+
!ts.isVariableDeclaration(declaration) ||
|
|
440
|
+
declaration.initializer === undefined ||
|
|
441
|
+
!ts.isCallExpression(declaration.initializer)
|
|
442
|
+
)
|
|
443
|
+
return [];
|
|
444
|
+
return declaration.initializer.arguments
|
|
445
|
+
.filter(ts.isObjectLiteralExpression)
|
|
446
|
+
.map((argument) => checker.getTypeAtLocation(argument));
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
const callablesOf = (symbol: ts.Symbol) => {
|
|
450
|
+
const type = checker.getTypeOfSymbolAtLocation(symbol, source);
|
|
451
|
+
const own = type.getCallSignatures().length === 0 ? [] : [{ name: symbol.name, type }];
|
|
452
|
+
const properties = [type, ...assignedObjects(symbol)].flatMap((owner) =>
|
|
453
|
+
callableProperties(symbol.name, owner),
|
|
454
|
+
);
|
|
455
|
+
return [
|
|
456
|
+
...own,
|
|
457
|
+
...properties.filter(
|
|
458
|
+
(callable, index) =>
|
|
459
|
+
properties.findIndex((other) => other.name === callable.name) === index,
|
|
460
|
+
),
|
|
461
|
+
];
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const callables = modules.flatMap((module) =>
|
|
465
|
+
module.symbols
|
|
466
|
+
.filter((symbol) => symbol.flags & (ts.SymbolFlags.Function | ts.SymbolFlags.Variable))
|
|
467
|
+
.flatMap((symbol) =>
|
|
468
|
+
callablesOf(symbol).map((callable) => ({ module: module.name, ...callable })),
|
|
469
|
+
),
|
|
470
|
+
);
|
|
471
|
+
|
|
472
|
+
const nodeTypeOf = (signature: ts.Signature): string | undefined => {
|
|
473
|
+
const typeProperty = checker.getReturnTypeOfSignature(signature).getProperty("type");
|
|
474
|
+
if (typeProperty === undefined) return undefined;
|
|
475
|
+
const literal = checker.getTypeOfSymbolAtLocation(typeProperty, source);
|
|
476
|
+
return literal.isStringLiteral() ? literal.value : undefined;
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const typeParameterList = (parameters: readonly ts.Type[]): string =>
|
|
480
|
+
parameters.length === 0
|
|
481
|
+
? ""
|
|
482
|
+
: `<${parameters
|
|
483
|
+
.map((parameter) => {
|
|
484
|
+
const constraint = parameter.getConstraint();
|
|
485
|
+
return `${parameter.symbol.name}${constraint === undefined ? "" : ` extends ${format(constraint, [], 0)}`}`;
|
|
486
|
+
})
|
|
487
|
+
.join(", ")}>`;
|
|
488
|
+
|
|
489
|
+
const parameterName = (parameter: ts.Symbol): string => {
|
|
490
|
+
const declaration = parameter.valueDeclaration;
|
|
491
|
+
return declaration !== undefined &&
|
|
492
|
+
ts.isParameter(declaration) &&
|
|
493
|
+
!ts.isIdentifier(declaration.name)
|
|
494
|
+
? "options"
|
|
495
|
+
: parameter.name;
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
const describeCallable = (callable: {
|
|
499
|
+
name: string;
|
|
500
|
+
type: ts.Type;
|
|
501
|
+
}): { signature: string; summary: string; parameterNames: string[] } => {
|
|
502
|
+
const parameterNames = new Set<string>();
|
|
503
|
+
const lines = callable.type.getCallSignatures().map((signature) => {
|
|
504
|
+
const nodeType = nodeTypeOf(signature);
|
|
505
|
+
const parameters = signature.getParameters().map((parameter) => {
|
|
506
|
+
const declaration = parameter.valueDeclaration;
|
|
507
|
+
const optional =
|
|
508
|
+
declaration !== undefined &&
|
|
509
|
+
ts.isParameter(declaration) &&
|
|
510
|
+
(declaration.questionToken !== undefined || declaration.initializer !== undefined);
|
|
511
|
+
const parameterType = definedType(checker.getTypeOfSymbolAtLocation(parameter, source));
|
|
512
|
+
const schemas =
|
|
513
|
+
nodeType !== undefined && parameter.name === "settings"
|
|
514
|
+
? contract.nodeSettings(nodeType)
|
|
515
|
+
: [];
|
|
516
|
+
const text = format(parameterType, schemas, 0);
|
|
517
|
+
const named = typeName(parameterType);
|
|
518
|
+
if (named !== undefined && isObjectLike(parameterType)) parameterNames.add(named);
|
|
519
|
+
return `${parameterName(parameter)}${optional ? "?" : ""}: ${text}`;
|
|
520
|
+
});
|
|
521
|
+
const returns = format(checker.getReturnTypeOfSignature(signature), [], 0);
|
|
522
|
+
return `${callable.name}${typeParameterList(signature.getTypeParameters() ?? [])}(${parameters.join(", ")}): ${returns}`;
|
|
523
|
+
});
|
|
524
|
+
return {
|
|
525
|
+
signature: lines.join("\n"),
|
|
526
|
+
summary: lines.map((line) => line.replace(/\s*\n\s*/gu, " ")).join("\n"),
|
|
527
|
+
parameterNames: [...parameterNames],
|
|
528
|
+
};
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
const functionDescriptions = callables.map((callable) => ({
|
|
532
|
+
module: callable.module,
|
|
533
|
+
name: callable.name,
|
|
534
|
+
...describeCallable(callable),
|
|
535
|
+
}));
|
|
536
|
+
const typeModules = new Map<string, string>();
|
|
537
|
+
for (const module of modules) {
|
|
538
|
+
for (const symbol of module.symbols) {
|
|
539
|
+
if (!(symbol.flags & (ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface))) continue;
|
|
540
|
+
typeModules.set(symbol.name, typeModules.get(symbol.name) ?? module.name);
|
|
541
|
+
discover(symbol.name, checker.getDeclaredTypeOfSymbol(symbol), []);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const discovered = () => named.size + [...schemasByName.values()].flat().length;
|
|
546
|
+
const renderTypes = (): SchemaEntry[] =>
|
|
547
|
+
[...named]
|
|
548
|
+
.toSorted(([left], [right]) => left.localeCompare(right))
|
|
549
|
+
.map(([name, type]) => ({
|
|
550
|
+
name,
|
|
551
|
+
module: typeModules.get(name) ?? SDK_PACKAGE,
|
|
552
|
+
kind: "type",
|
|
553
|
+
summary: truncate(`${name}: ${summarizeType(type)}`, MAX_SUMMARY_LENGTH),
|
|
554
|
+
detail: describeType(name, type),
|
|
555
|
+
}));
|
|
556
|
+
let before = discovered();
|
|
557
|
+
let typeEntries = renderTypes();
|
|
558
|
+
while (discovered() !== before) {
|
|
559
|
+
before = discovered();
|
|
560
|
+
typeEntries = renderTypes();
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const functionEntries = functionDescriptions.map(
|
|
564
|
+
({ module, name, signature, summary, parameterNames }): SchemaEntry => ({
|
|
565
|
+
name,
|
|
566
|
+
module,
|
|
567
|
+
kind: "function",
|
|
568
|
+
summary,
|
|
569
|
+
detail: [
|
|
570
|
+
signature,
|
|
571
|
+
...parameterNames.flatMap((parameterName) =>
|
|
572
|
+
typeEntries.filter((entry) => entry.name === parameterName).map((entry) => entry.detail),
|
|
573
|
+
),
|
|
574
|
+
].join("\n\n"),
|
|
575
|
+
}),
|
|
576
|
+
);
|
|
577
|
+
|
|
578
|
+
return {
|
|
579
|
+
version,
|
|
580
|
+
entries: [...functionEntries, ...typeEntries],
|
|
581
|
+
};
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
export const formatSchemaIndex = (schema: SdkSchema): string => {
|
|
585
|
+
const functions = (module: string) =>
|
|
586
|
+
schema.entries
|
|
587
|
+
.filter((entry) => entry.kind === "function" && entry.module === module)
|
|
588
|
+
.map((entry) => entry.summary);
|
|
589
|
+
return [
|
|
590
|
+
`Authoring and testing API of ${SDK_PACKAGE} ${schema.version}, read from its installed types.`,
|
|
591
|
+
...MODULES.flatMap((module) => ["", `Functions of ${module.name}:`, ...functions(module.name)]),
|
|
592
|
+
"",
|
|
593
|
+
"Types:",
|
|
594
|
+
...schema.entries.filter((entry) => entry.kind === "type").map((entry) => entry.summary),
|
|
595
|
+
"",
|
|
596
|
+
"Run `toloka schema <name> [name...]` for the full shape of a function's settings or of a type: fields, optionality, allowed values, defaults and bounds.",
|
|
597
|
+
].join("\n");
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
export const schemaCommand = ({
|
|
601
|
+
sourceRoot,
|
|
602
|
+
names,
|
|
603
|
+
io,
|
|
604
|
+
}: {
|
|
605
|
+
sourceRoot: string;
|
|
606
|
+
names: readonly string[];
|
|
607
|
+
io: CliIo;
|
|
608
|
+
}): void => {
|
|
609
|
+
const schema = describeSdkSchema(resolveSdkRoot(sourceRoot));
|
|
610
|
+
if (names.length === 0) {
|
|
611
|
+
io.stdout(formatSchemaIndex(schema));
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
const details = names.map((name) => {
|
|
615
|
+
const entry =
|
|
616
|
+
schema.entries.find((candidate) => candidate.name === name) ??
|
|
617
|
+
schema.entries.find((candidate) => candidate.name.toLowerCase() === name.toLowerCase());
|
|
618
|
+
const similar = schema.entries
|
|
619
|
+
.filter((candidate) => candidate.name.toLowerCase().includes(name.toLowerCase()))
|
|
620
|
+
.slice(0, 10)
|
|
621
|
+
.map((candidate) => candidate.name);
|
|
622
|
+
assertCli(entry, `Unknown SDK name: ${name}.`, {
|
|
623
|
+
hint: {
|
|
624
|
+
description:
|
|
625
|
+
similar.length === 0
|
|
626
|
+
? "Run toloka schema without names to list every function and type."
|
|
627
|
+
: `Names that contain it: ${similar.join(", ")}. Run toloka schema without names to list every function and type.`,
|
|
628
|
+
},
|
|
629
|
+
});
|
|
630
|
+
return entry.detail;
|
|
631
|
+
});
|
|
632
|
+
io.stdout(details.join("\n\n"));
|
|
633
|
+
};
|
package/src/graph-rules.json
CHANGED
|
@@ -10,5 +10,7 @@
|
|
|
10
10
|
"mediaUploadComponentPattern": "<Field\\.(?:Video(?:Upload|Record)|FileUpload)\\b",
|
|
11
11
|
"nodeSettingMaxCharacters": 150000,
|
|
12
12
|
"minTrainingSteps": 3,
|
|
13
|
-
"maxTrainingSteps": 6
|
|
13
|
+
"maxTrainingSteps": 6,
|
|
14
|
+
"expectedExpertBehaviorMaxCharacters": 10000,
|
|
15
|
+
"expectedExpertBehaviorRequiredMessage": "Describe how experts complete this task: the steps, the pages and media they open, what they write and paste in each answer field, and which use of AI tools is allowed."
|
|
14
16
|
}
|