@bidirekt/typescript-sdk-cli 0.2.0 → 0.4.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.
Files changed (36) hide show
  1. package/README.md +77 -37
  2. package/dist/command.js +14 -13
  3. package/dist/model/contract.js +7 -1
  4. package/dist/model/declarations-to-contract.js +97 -37
  5. package/dist/model/protocols/graphql/block-to-references.js +8 -0
  6. package/dist/model/protocols/graphql/blocks-to-merged.js +77 -0
  7. package/dist/model/protocols/graphql/contract.js +1 -0
  8. package/dist/model/protocols/graphql/field-extra.js +46 -0
  9. package/dist/model/protocols/graphql/returns-to-schema.js +77 -0
  10. package/dist/model/protocols/rest/contract.js +1 -0
  11. package/dist/model/{resources-to-merged.js → protocols/rest/resources-to-merged.js} +15 -10
  12. package/dist/model/protocols/rest/resources-to-references.js +10 -0
  13. package/dist/protocols.js +49 -0
  14. package/dist/reader/comment-tags.js +77 -37
  15. package/dist/reader/literal-options.js +8 -2
  16. package/dist/reader/program.js +1 -1
  17. package/dist/reader/project-to-contract.js +51 -23
  18. package/dist/reader/protocols/graphql/decorators-to-blocks.js +412 -0
  19. package/dist/reader/protocols/graphql/protocol-input-to-blocks.js +11 -0
  20. package/dist/reader/protocols/graphql/tags-to-blocks.js +239 -0
  21. package/dist/reader/{handler-methods.js → protocols/rest/handler-methods.js} +36 -26
  22. package/dist/reader/protocols/rest/protocol-input-to-resources.js +11 -0
  23. package/dist/reader/protocols/rest/tag-handlers.js +152 -0
  24. package/dist/reader/schema-classes.js +191 -29
  25. package/dist/reader/schema-context.js +10 -5
  26. package/dist/reader/sdk-references.js +149 -39
  27. package/dist/reader/tag-handlers.js +36 -146
  28. package/dist/reader/tag-schemas.js +82 -40
  29. package/dist/reader/type-text-to-schema-node.js +4 -1
  30. package/dist/reader/type-to-schema-node.js +60 -10
  31. package/dist/writer/contract-to-yaml.js +38 -59
  32. package/dist/writer/protocols/graphql/block-to-yaml.js +31 -0
  33. package/dist/writer/protocols/graphql/field-extra-to-yaml.js +13 -0
  34. package/dist/writer/protocols/rest/resources-to-yaml.js +36 -0
  35. package/package.json +2 -2
  36. /package/dist/model/{schema-names.js → protocols/rest/schema-names.js} +0 -0
@@ -1,9 +1,9 @@
1
1
  import ts from 'typescript';
2
2
  import { descriptionToDiagnostic } from "../model/description.js";
3
3
  import { isDiagnostic } from "../model/diagnostic.js";
4
- import { argumentToOption, isHandlerTag } from "./comment-tags.js";
5
- import { namesToChoice } from "./literal-options.js";
6
- import { declarationToDescription } from "./schema-classes.js";
4
+ import { argumentToOption, isHandlerTag, tagToLabel } from "./comment-tags.js";
5
+ import { hintToSuffix, namesToChoice } from "./literal-options.js";
6
+ import { declarationToDescription, optionToOwningProtocol, } from "./schema-classes.js";
7
7
  import { isObjectDeclaration, isShadowedByScript, memberToOwner, } from "./schema-context.js";
8
8
  import { isStatic } from "./sdk-references.js";
9
9
  import { isSchemaName, tagTypeTextToSchemaNode, tagTypeTextUsage, } from "./type-text-to-schema-node.js";
@@ -18,28 +18,31 @@ const optionUsages = {
18
18
  };
19
19
  const fieldKeys = Object.keys(optionUsages);
20
20
  export const blockFieldKeys = fieldKeys.filter((key) => key !== 'name');
21
+ const schemaKeys = ['name', 'union'];
22
+ const enumSchemaKeys = ['name'];
21
23
  const unionPattern = /^\{([^{}]*)\}$/;
22
24
  const unionMemberPattern = /^([^\s:,]+)\s*:\s*([^\s:,]+)$/;
23
- export function taggedCommentsToSchemaTags(comments, context) {
25
+ export function taggedCommentsToSchemaTags(comments, context, protocols) {
24
26
  const read = {
25
27
  schemas: new Set(),
28
+ unions: new Map(),
26
29
  fields: new Map(),
27
30
  malformedFields: new Set(),
28
31
  errors: [],
29
32
  warnings: [],
30
33
  };
31
34
  const tagged = { schemas: new Set(), fields: new Set() };
32
- for (const { element, tags } of comments) {
35
+ for (const { element, tags, hasUnknownTag = false } of comments) {
33
36
  if (tags.some(isHandlerTag) || isDeclaredByScript(element, context)) {
34
37
  continue;
35
38
  }
36
39
  const schemaTag = tagsToSingle(tags, 'schema', read);
37
40
  if (schemaTag !== undefined) {
38
- schemaTagToName(schemaTag, element, context, read, tagged.schemas);
41
+ schemaTagToName(schemaTag, element, context, read, tagged.schemas, hasUnknownTag);
39
42
  }
40
43
  const fieldTag = tagsToSingle(tags, 'field', read);
41
44
  if (fieldTag !== undefined) {
42
- fieldTagToOptions(fieldTag, element, read, tagged.fields);
45
+ fieldTagToOptions(fieldTag, element, read, tagged.fields, protocols, hasUnknownTag);
43
46
  }
44
47
  }
45
48
  return read;
@@ -62,7 +65,7 @@ function tagsToSingle(tags, keyword, read) {
62
65
  })));
63
66
  return tag;
64
67
  }
65
- function schemaTagToName(tag, element, context, read, taggedSchemas) {
68
+ function schemaTagToName(tag, element, context, read, taggedSchemas, hasUnknownTag) {
66
69
  if (ts.isJSDocTypedefTag(element) || ts.isJSDocCallbackTag(element)) {
67
70
  read.warnings.push({
68
71
  message: `"@bidirekt schema" is on a @${element.tagName.text}, so it is not read: declare the schema as a class with "@bidirekt schema"`,
@@ -71,10 +74,7 @@ function schemaTagToName(tag, element, context, read, taggedSchemas) {
71
74
  return;
72
75
  }
73
76
  if (!ts.isEnumDeclaration(element) && !isObjectDeclaration(element)) {
74
- read.warnings.push({
75
- message: '"@bidirekt schema" is not above an enum, a class, an interface or an object type, so it is not read: put it above one of them',
76
- location: tag.location,
77
- });
77
+ warnMisplaced(read, hasUnknownTag, '"@bidirekt schema" is not above an enum, a class, an interface or an object type, so it is not read: put it above one of them', tag);
78
78
  return;
79
79
  }
80
80
  if (ts.isTypeAliasDeclaration(element) &&
@@ -98,16 +98,16 @@ function schemaTagToName(tag, element, context, read, taggedSchemas) {
98
98
  taggedSchemas.add(tagged);
99
99
  read.schemas.add(element);
100
100
  }
101
- const declared = tagToName(tag);
102
- if (isDiagnostic(declared)) {
103
- read.errors.push(declared);
101
+ const options = argumentsToOptions(tag.arguments, tag, elementToSchemaKeys(element));
102
+ if (isDiagnostic(options)) {
103
+ read.errors.push(options);
104
104
  return;
105
105
  }
106
106
  if (ts.isEnumDeclaration(element)) {
107
- enumTagToSchema(tag, element, declared, context, read, taggedSchemas);
107
+ enumTagToSchema(tag, element, options.name, context, read, taggedSchemas);
108
108
  return;
109
109
  }
110
- const name = declared ?? element.name?.text;
110
+ const name = options.name ?? element.name?.text;
111
111
  if (name === undefined) {
112
112
  read.errors.push({
113
113
  message: 'cannot name an anonymous class: declare it with "@bidirekt schema name=<name>"',
@@ -116,6 +116,18 @@ function schemaTagToName(tag, element, context, read, taggedSchemas) {
116
116
  return;
117
117
  }
118
118
  context.schemaDeclarations.set(element, name);
119
+ if (options.declared?.type === 'union') {
120
+ read.unions.set(element, {
121
+ members: options.declared.members,
122
+ location: tag.location,
123
+ });
124
+ }
125
+ }
126
+ function elementToSchemaKeys(element) {
127
+ if (ts.isEnumDeclaration(element)) {
128
+ return enumSchemaKeys;
129
+ }
130
+ return schemaKeys;
119
131
  }
120
132
  function enumTagToSchema(tag, element, declared, context, read, taggedSchemas) {
121
133
  const symbol = context.checker.getSymbolAtLocation(element.name);
@@ -141,25 +153,22 @@ function enumTagToSchema(tag, element, declared, context, read, taggedSchemas) {
141
153
  });
142
154
  }
143
155
  }
156
+ // An unknown tag can be the handler of its comment, whose schema and field tags are then the handler's.
157
+ function warnMisplaced(read, hasUnknownTag, message, tag) {
158
+ if (hasUnknownTag) {
159
+ return;
160
+ }
161
+ read.warnings.push({ message, location: tag.location });
162
+ }
144
163
  function declarationToTagged(declaration, context) {
145
164
  if (!ts.isInterfaceDeclaration(declaration)) {
146
165
  return declaration;
147
166
  }
148
167
  return context.checker.getSymbolAtLocation(declaration.name) ?? declaration;
149
168
  }
150
- function tagToName(tag) {
151
- const options = argumentsToOptions(tag.arguments, tag, ['name']);
152
- if (isDiagnostic(options)) {
153
- return options;
154
- }
155
- return options.name;
156
- }
157
- function fieldTagToOptions(tag, element, read, taggedFields) {
169
+ function fieldTagToOptions(tag, element, read, taggedFields, protocols, hasUnknownTag) {
158
170
  if (!ts.isPropertyDeclaration(element) && !ts.isPropertySignature(element)) {
159
- read.warnings.push({
160
- message: '"@bidirekt field" is not above a property, so it is not read: put it above a property of a class, an interface or an object type',
161
- location: tag.location,
162
- });
171
+ warnMisplaced(read, hasUnknownTag, '"@bidirekt field" is not above a property, so it is not read: put it above a property of a class, an interface or an object type', tag);
163
172
  return;
164
173
  }
165
174
  if (isStatic(element)) {
@@ -177,39 +186,56 @@ function fieldTagToOptions(tag, element, read, taggedFields) {
177
186
  return;
178
187
  }
179
188
  taggedFields.add(element);
180
- const options = argumentsToOptions(tag.arguments, tag, fieldKeys);
189
+ const options = argumentsToOptions(tag.arguments, tag, fieldKeys, protocols);
181
190
  if (isDiagnostic(options)) {
182
191
  read.errors.push(options);
183
192
  read.malformedFields.add(element);
184
193
  return;
185
194
  }
186
- read.fields.set(element, { options, location: tag.location });
195
+ read.fields.set(element, {
196
+ label: tagToLabel(tag),
197
+ options,
198
+ location: tag.location,
199
+ });
200
+ }
201
+ function tagToVocabulary(tag, protocols) {
202
+ return protocols.find(({ name }) => name === tag.vocabulary)?.vocabulary;
187
203
  }
188
- export function argumentsToOptions(tagArguments, tag, keys) {
204
+ export function argumentsToOptions(tagArguments, tag, keys, protocols = []) {
189
205
  if (tag.error !== undefined) {
190
206
  return tag.error;
191
207
  }
192
208
  const options = {};
193
209
  const seen = new Set();
210
+ const vocabulary = tagToVocabulary(tag, protocols);
211
+ const known = [...keys, ...(vocabulary?.fieldOptions ?? [])];
212
+ const vocabularyOptions = {};
194
213
  for (const argument of tagArguments) {
195
214
  const option = argumentToOption(argument);
196
215
  const key = option?.key ?? '';
197
216
  const fail = (usage) => ({
198
- message: `cannot read "${argument}" in "@bidirekt ${tag.keyword}": write ${usage}`,
217
+ message: `cannot read "${argument}" in "${tagToLabel(tag)}": write ${usage}`,
199
218
  location: tag.location,
200
219
  });
201
- if (option === undefined || !keys.includes(key)) {
202
- return fail(keysToUsage(keys));
220
+ if (option === undefined || !known.includes(key)) {
221
+ return fail(`${keysToUsage(known)}${hintToSuffix(optionToFieldTagHint(key, protocols))}`);
203
222
  }
204
223
  if (seen.has(key)) {
205
224
  return {
206
- message: `"${key}=" is declared more than once in "@bidirekt ${tag.keyword}": keep one`,
225
+ message: `"${key}=" is declared more than once in "${tagToLabel(tag)}": keep one`,
207
226
  location: tag.location,
208
227
  };
209
228
  }
210
229
  seen.add(key);
211
230
  const value = option.value;
212
- const usage = fail(optionUsages[key]);
231
+ const usage = fail(keyToUsage(key));
232
+ if (!keys.includes(key)) {
233
+ if (value === '') {
234
+ return usage;
235
+ }
236
+ vocabularyOptions[key] = value;
237
+ continue;
238
+ }
213
239
  switch (key) {
214
240
  case 'type': {
215
241
  const declared = tagTypeTextToSchemaNode(value);
@@ -254,19 +280,35 @@ export function argumentsToOptions(tagArguments, tag, keys) {
254
280
  }
255
281
  if (seen.has('type') && seen.has('union')) {
256
282
  return {
257
- message: 'declare either "type=" or "union=" in "@bidirekt field", not both',
283
+ message: `declare either "type=" or "union=" in "${tagToLabel(tag)}", not both`,
258
284
  location: tag.location,
259
285
  };
260
286
  }
287
+ if (vocabulary !== undefined) {
288
+ options.extension = { vocabulary, options: vocabularyOptions };
289
+ }
261
290
  return options;
262
291
  }
292
+ function optionToFieldTagHint(key, protocols) {
293
+ const owner = optionToOwningProtocol(key, protocols);
294
+ if (owner?.vocabulary === undefined) {
295
+ return undefined;
296
+ }
297
+ return `for ${owner.vocabulary.label}, use "@bidirekt ${owner.name} field"`;
298
+ }
263
299
  function keysToUsage(keys) {
264
300
  if (keys.length === 1) {
265
- return optionUsages[keys[0]];
301
+ return keyToUsage(keys[0]);
266
302
  }
267
303
  return `"<key>=<value>" with key ${namesToChoice(keys)}`;
268
304
  }
269
- function valueToUnionMembers(value) {
305
+ function keyToUsage(key) {
306
+ if (Object.hasOwn(optionUsages, key)) {
307
+ return optionUsages[key];
308
+ }
309
+ return `"${key}=<value>"`;
310
+ }
311
+ export function valueToUnionMembers(value) {
270
312
  const braces = unionPattern.exec(value);
271
313
  if (braces === null) {
272
314
  return undefined;
@@ -36,8 +36,11 @@ function nestedTextToSchemaNode(text, leafToSchemaNode) {
36
36
  }
37
37
  return leafToSchemaNode(text);
38
38
  }
39
+ export function textToPrimitive(text) {
40
+ return primitiveTypes.find((type) => type === text);
41
+ }
39
42
  function primitiveToSchemaNode(text) {
40
- const primitive = primitiveTypes.find((type) => type === text);
43
+ const primitive = textToPrimitive(text);
41
44
  if (primitive === undefined) {
42
45
  return undefined;
43
46
  }
@@ -3,6 +3,7 @@ import { isDiagnostic } from "../model/diagnostic.js";
3
3
  import { nodeToLocation } from "./location.js";
4
4
  import { builtDeclarationToDiagnostic, classToDiagnostic, classToSchemaName, isDefaultLibrarySymbol, isLibrarySymbol, nodeToSymbol, symbolToSchemaName, typeToUntranslatableMessage, } from "./schema-context.js";
5
5
  const boxedPrimitives = ['String', 'Number', 'Boolean'];
6
+ const listNames = ['Array', 'ReadonlyArray'];
6
7
  function startWalk(union) {
7
8
  return { expanding: new Set(), bindings: new Map(), union };
8
9
  }
@@ -121,6 +122,59 @@ function walkToTranslatedType(typeNode, context, walk) {
121
122
  }
122
123
  return { node, optional: parts.optional || translated.optional };
123
124
  }
125
+ export function typeNodeToShapedLeaf(typeNode, leaf, context) {
126
+ return walkToShapedLeaf(typeNode, leaf, context, startWalk(undefined));
127
+ }
128
+ function walkToShapedLeaf(typeNode, leaf, context, walk) {
129
+ const parts = typeNodeToParts(typeNode);
130
+ let shaped = { node: leaf, optional: false };
131
+ if (parts.members.length === 1) {
132
+ shaped = memberToShapedLeaf(parts.members[0], leaf, context, walk);
133
+ }
134
+ if (isDiagnostic(shaped)) {
135
+ return shaped;
136
+ }
137
+ const flags = walkToFlags(typeNode, context, walk);
138
+ let node = shaped.node;
139
+ if (flags.nullable) {
140
+ node = { ...node, nullable: true };
141
+ }
142
+ return { node, optional: flags.optional || shaped.optional };
143
+ }
144
+ function memberToShapedLeaf(member, leaf, context, walk) {
145
+ const items = memberToListItems(member, context);
146
+ if (items !== undefined) {
147
+ const node = translatedToNestedNode(walkToShapedLeaf(items, leaf, context, walk), items, context);
148
+ if (isDiagnostic(node)) {
149
+ return node;
150
+ }
151
+ return { node: { type: 'array', items: node }, optional: false };
152
+ }
153
+ const followed = memberToFollowed(member, context, walk);
154
+ if (followed !== undefined) {
155
+ return walkToShapedLeaf(followed.typeNode, leaf, context, followed.walk);
156
+ }
157
+ return { node: leaf, optional: false };
158
+ }
159
+ function memberToListItems(member, context) {
160
+ if (ts.isArrayTypeNode(member)) {
161
+ return member.elementType;
162
+ }
163
+ if (ts.isTypeOperatorNode(member) &&
164
+ member.operator === ts.SyntaxKind.ReadonlyKeyword) {
165
+ return memberToListItems(member.type, context);
166
+ }
167
+ if (!isReference(member) || member.typeArguments?.length !== 1) {
168
+ return undefined;
169
+ }
170
+ const symbol = referenceToSymbol(member, context);
171
+ if (symbol === undefined ||
172
+ !isLibrarySymbol(symbol, context) ||
173
+ !listNames.includes(symbol.name)) {
174
+ return undefined;
175
+ }
176
+ return member.typeArguments[0];
177
+ }
124
178
  function typeNodeToParts(typeNode) {
125
179
  const parts = { members: [], nullable: false, optional: false };
126
180
  const add = (node) => {
@@ -155,8 +209,7 @@ function typeNodeToParts(typeNode) {
155
209
  add(typeNode);
156
210
  return parts;
157
211
  }
158
- function typeNodeToNestedNode(typeNode, context, walk) {
159
- const translated = walkToTranslatedType(typeNode, context, walk);
212
+ function translatedToNestedNode(translated, typeNode, context) {
160
213
  if (isDiagnostic(translated)) {
161
214
  return translated;
162
215
  }
@@ -217,8 +270,9 @@ function memberToTranslatedType(member, context, walk) {
217
270
  if (isNumericLiteralType(member)) {
218
271
  return { message: numericLiteralMessage(member.getText(), context.hints) };
219
272
  }
220
- if (ts.isArrayTypeNode(member)) {
221
- return arrayToTranslatedType(member.elementType, context, walk);
273
+ const items = memberToListItems(member, context);
274
+ if (items !== undefined) {
275
+ return arrayToTranslatedType(items, context, walk);
222
276
  }
223
277
  if (ts.isTypeOperatorNode(member) &&
224
278
  member.operator === ts.SyntaxKind.ReadonlyKeyword) {
@@ -291,10 +345,6 @@ function referenceToTranslatedType(reference, context, walk) {
291
345
  };
292
346
  }
293
347
  function libraryReferenceToTranslatedType(reference, name, typeArguments, context, walk) {
294
- if ((name === 'Array' || name === 'ReadonlyArray') &&
295
- typeArguments.length === 1) {
296
- return arrayToTranslatedType(typeArguments[0], context, walk);
297
- }
298
348
  if ((name === 'Record' || name === 'Object') && typeArguments.length === 2) {
299
349
  const [key, values] = typeArguments;
300
350
  if (!isStringType(key, context)) {
@@ -314,14 +364,14 @@ function libraryReferenceToTranslatedType(reference, name, typeArguments, contex
314
364
  };
315
365
  }
316
366
  function arrayToTranslatedType(items, context, walk) {
317
- const node = typeNodeToNestedNode(items, context, walk);
367
+ const node = translatedToNestedNode(walkToTranslatedType(items, context, walk), items, context);
318
368
  if (isDiagnostic(node)) {
319
369
  return node;
320
370
  }
321
371
  return { node: { type: 'array', items: node }, optional: false };
322
372
  }
323
373
  function mapToTranslatedType(values, context, walk) {
324
- const node = typeNodeToNestedNode(values, context, walk);
374
+ const node = translatedToNestedNode(walkToTranslatedType(values, context, walk), values, context);
325
375
  if (isDiagnostic(node)) {
326
376
  return node;
327
377
  }
@@ -1,12 +1,12 @@
1
1
  import { Document, Pair, Scalar, YAMLMap, YAMLSeq } from 'yaml';
2
2
  const header = ' Generated by @bidirekt/typescript-sdk. Do not edit.';
3
- export function contractToYaml(contract) {
3
+ export function contractToYaml(contract, protocols) {
4
4
  const root = new YAMLMap();
5
- if (contract.provides.length > 0) {
6
- root.add(new Pair('provides', providedToYaml(contract.provides)));
5
+ if (contract.provides.size > 0) {
6
+ root.add(new Pair('provides', blocksToYaml(contract.provides, protocols)));
7
7
  }
8
- if (contract.consumes.length > 0) {
9
- root.add(new Pair('consumes', consumedToYaml(contract.consumes)));
8
+ if (contract.consumes.size > 0) {
9
+ root.add(new Pair('consumes', consumedToYaml(contract.consumes, protocols)));
10
10
  }
11
11
  if (contract.schemas.length > 0) {
12
12
  root.add(new Pair('schemas', schemasToYaml(contract.schemas)));
@@ -19,89 +19,55 @@ export function contractToYaml(contract) {
19
19
  nullStr: '~',
20
20
  });
21
21
  }
22
- function compareBytes(a, b) {
22
+ export function compareBytes(a, b) {
23
23
  return Buffer.compare(Buffer.from(a), Buffer.from(b));
24
24
  }
25
- function sortedByKey(groups) {
25
+ export function sortedByKey(groups) {
26
26
  return [...groups].sort(([a], [b]) => compareBytes(a, b));
27
27
  }
28
- function providedToYaml(resources) {
29
- const rest = new YAMLMap();
30
- rest.add(new Pair('rest', resourcesToYaml(resources)));
31
- return rest;
32
- }
33
- function consumedToYaml(resources) {
28
+ function consumedToYaml(consumes, protocols) {
34
29
  const providers = new YAMLMap();
35
- const byProvider = Map.groupBy(resources, (resource) => resource.provider);
36
- for (const [name, own] of sortedByKey(byProvider)) {
37
- providers.add(new Pair(name, providedToYaml(own)));
30
+ for (const [name, blocks] of sortedByKey(consumes)) {
31
+ providers.add(new Pair(name, blocksToYaml(blocks, protocols)));
38
32
  }
39
33
  return providers;
40
34
  }
41
- function resourcesToYaml(resources) {
42
- const endpoints = new YAMLMap();
43
- const byPath = Map.groupBy(resources, (resource) => resource.path);
44
- for (const [path, own] of sortedByKey(byPath)) {
45
- const methods = new YAMLMap();
46
- const atPath = own
47
- .map((resource) => ({
48
- method: resource.method.toLowerCase(),
49
- resource,
50
- }))
51
- .sort((a, b) => compareBytes(a.method, b.method));
52
- for (const { method, resource } of atPath) {
53
- methods.add(new Pair(method, resourceToYaml(resource)));
35
+ function blocksToYaml(blocks, protocols) {
36
+ const byProtocol = new YAMLMap();
37
+ const sorted = [...protocols].sort((a, b) => compareBytes(a.name, b.name));
38
+ for (const protocol of sorted) {
39
+ if (blocks.has(protocol.name)) {
40
+ const block = protocol.toYaml(blocks.get(protocol.name));
41
+ byProtocol.add(new Pair(protocol.name, block));
54
42
  }
55
- endpoints.add(new Pair(path, methods));
56
- }
57
- return endpoints;
58
- }
59
- function resourceToYaml(resource) {
60
- const interaction = new YAMLMap();
61
- if (resource.request) {
62
- interaction.add(new Pair('request', bodyToYaml(resource.request)));
63
43
  }
64
- const responses = new YAMLMap();
65
- const byStatus = [...resource.responses].sort((a, b) => a.status - b.status);
66
- for (const response of byStatus) {
67
- responses.add(new Pair(response.status, bodyToYaml(response)));
68
- }
69
- interaction.add(new Pair('responses', responses));
70
- return interaction;
71
- }
72
- function bodyToYaml(body) {
73
- return new Scalar(body.schema);
44
+ return byProtocol;
74
45
  }
75
46
  function schemasToYaml(schemas) {
76
47
  const named = new YAMLMap();
77
48
  const sorted = [...schemas].sort((a, b) => compareBytes(a.name, b.name));
78
49
  for (const schema of sorted) {
79
- named.add(new Pair(schema.name, nodeToYaml(schema.node)));
50
+ named.add(new Pair(schema.name, nodeToYaml(schema.node, schema.vocabulary)));
80
51
  }
81
52
  return named;
82
53
  }
83
- function nodeToYaml(node) {
54
+ function nodeToYaml(node, vocabulary) {
84
55
  const fields = new YAMLMap();
85
56
  switch (node.type) {
86
57
  case 'ref':
87
58
  fields.add(new Pair('ref', node.schema));
88
59
  break;
89
- case 'object': {
60
+ case 'object':
90
61
  fields.add(new Pair('type', node.type));
91
- const properties = new YAMLMap();
92
- for (const property of node.properties) {
93
- properties.add(new Pair(property.name, nodeToYaml(property.node)));
94
- }
95
- fields.add(new Pair('properties', properties));
62
+ fields.add(new Pair('properties', propertiesToYaml(node.properties)));
96
63
  break;
97
- }
98
64
  case 'array':
99
65
  fields.add(new Pair('type', node.type));
100
- fields.add(new Pair('items', nodeToYaml(node.items)));
66
+ fields.add(new Pair('items', nodeToYaml(node.items, vocabulary)));
101
67
  break;
102
68
  case 'map':
103
69
  fields.add(new Pair('type', node.type));
104
- fields.add(new Pair('values', nodeToYaml(node.values)));
70
+ fields.add(new Pair('values', nodeToYaml(node.values, vocabulary)));
105
71
  break;
106
72
  case 'enum':
107
73
  fields.add(new Pair('type', node.type));
@@ -109,9 +75,12 @@ function nodeToYaml(node) {
109
75
  break;
110
76
  case 'union': {
111
77
  fields.add(new Pair('type', node.type));
78
+ if (node.properties !== undefined) {
79
+ fields.add(new Pair('properties', propertiesToYaml(node.properties)));
80
+ }
112
81
  const members = new YAMLMap();
113
82
  for (const member of node.members) {
114
- members.add(new Pair(member.key, nodeToYaml(member.node)));
83
+ members.add(new Pair(member.key, nodeToYaml(member.node, vocabulary)));
115
84
  }
116
85
  fields.add(new Pair('members', members));
117
86
  break;
@@ -119,6 +88,9 @@ function nodeToYaml(node) {
119
88
  default:
120
89
  fields.add(new Pair('type', node.type));
121
90
  }
91
+ if (node.extra !== undefined) {
92
+ vocabulary?.toYaml(node, fields);
93
+ }
122
94
  if (node.optional) {
123
95
  fields.add(new Pair('optional', true));
124
96
  }
@@ -130,6 +102,13 @@ function nodeToYaml(node) {
130
102
  }
131
103
  return fields;
132
104
  }
105
+ function propertiesToYaml(properties) {
106
+ const map = new YAMLMap();
107
+ for (const property of properties) {
108
+ map.add(new Pair(property.name, nodeToYaml(property.node, property.vocabulary)));
109
+ }
110
+ return map;
111
+ }
133
112
  function enumMembersToYaml(members) {
134
113
  const sequence = new YAMLSeq();
135
114
  sequence.flow = true;
@@ -0,0 +1,31 @@
1
+ import { Pair, YAMLMap } from 'yaml';
2
+ import { compareBytes } from "../../contract-to-yaml.js";
3
+ const operationKinds = ['query', 'mutation'];
4
+ export function blockToYaml(block) {
5
+ const graphql = new YAMLMap();
6
+ if (block.graph !== undefined) {
7
+ graphql.add(new Pair('graph', block.graph.name));
8
+ }
9
+ const byKind = Map.groupBy(block.operations, ({ kind }) => kind);
10
+ for (const kind of operationKinds) {
11
+ const operations = byKind.get(kind);
12
+ if (operations === undefined) {
13
+ continue;
14
+ }
15
+ const fields = new YAMLMap();
16
+ const sorted = [...operations].sort((a, b) => compareBytes(a.name, b.name));
17
+ for (const operation of sorted) {
18
+ fields.add(new Pair(operation.name, operationToYaml(operation)));
19
+ }
20
+ graphql.add(new Pair(kind, fields));
21
+ }
22
+ return graphql;
23
+ }
24
+ function operationToYaml(operation) {
25
+ const field = new YAMLMap();
26
+ if (operation.arguments !== undefined) {
27
+ field.add(new Pair('arguments', operation.arguments.schema));
28
+ }
29
+ field.add(new Pair('returns', operation.returns.schema));
30
+ return field;
31
+ }
@@ -0,0 +1,13 @@
1
+ import { Pair } from 'yaml';
2
+ import { nodeToArguments, nodeToScalar, } from "../../../model/protocols/graphql/field-extra.js";
3
+ export function fieldExtraToYaml(node, map) {
4
+ const scalar = nodeToScalar(node);
5
+ if (scalar !== undefined) {
6
+ map.set('type', 'scalar');
7
+ map.add(new Pair('name', scalar));
8
+ }
9
+ const schema = nodeToArguments(node);
10
+ if (schema !== undefined) {
11
+ map.add(new Pair('arguments', schema));
12
+ }
13
+ }
@@ -0,0 +1,36 @@
1
+ import { Pair, Scalar, YAMLMap } from 'yaml';
2
+ import { compareBytes, sortedByKey } from "../../contract-to-yaml.js";
3
+ export function resourcesToYaml(resources) {
4
+ const endpoints = new YAMLMap();
5
+ const byPath = Map.groupBy(resources, (resource) => resource.path);
6
+ for (const [path, own] of sortedByKey(byPath)) {
7
+ const methods = new YAMLMap();
8
+ const atPath = own
9
+ .map((resource) => ({
10
+ method: resource.method.toLowerCase(),
11
+ resource,
12
+ }))
13
+ .sort((a, b) => compareBytes(a.method, b.method));
14
+ for (const { method, resource } of atPath) {
15
+ methods.add(new Pair(method, resourceToYaml(resource)));
16
+ }
17
+ endpoints.add(new Pair(path, methods));
18
+ }
19
+ return endpoints;
20
+ }
21
+ function resourceToYaml(resource) {
22
+ const interaction = new YAMLMap();
23
+ if (resource.request) {
24
+ interaction.add(new Pair('request', bodyToYaml(resource.request)));
25
+ }
26
+ const responses = new YAMLMap();
27
+ const byStatus = [...resource.responses].sort((a, b) => a.status - b.status);
28
+ for (const response of byStatus) {
29
+ responses.add(new Pair(response.status, bodyToYaml(response)));
30
+ }
31
+ interaction.add(new Pair('responses', responses));
32
+ return interaction;
33
+ }
34
+ function bodyToYaml(body) {
35
+ return new Scalar(body.schema);
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bidirekt/typescript-sdk-cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "prepublishOnly": "npm run build"
26
26
  },
27
27
  "dependencies": {
28
- "@bidirekt/typescript-sdk": "0.2.0",
28
+ "@bidirekt/typescript-sdk": "0.4.0",
29
29
  "typescript": "~6.0.3",
30
30
  "yaml": "^2.9.1"
31
31
  }