apollo-conn-gen 0.0.2

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 (146) hide show
  1. package/dist/cli/json.d.ts +1 -0
  2. package/dist/cli/json.js +70 -0
  3. package/dist/cli/json.js.map +1 -0
  4. package/dist/cli/oas-helpers/index.d.ts +4 -0
  5. package/dist/cli/oas-helpers/index.js +54 -0
  6. package/dist/cli/oas-helpers/index.js.map +1 -0
  7. package/dist/cli/oas.d.ts +1 -0
  8. package/dist/cli/oas.js +49 -0
  9. package/dist/cli/oas.js.map +1 -0
  10. package/dist/index.d.ts +2 -0
  11. package/dist/index.js +4 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/json/index.d.ts +4 -0
  14. package/dist/json/index.js +5 -0
  15. package/dist/json/index.js.map +1 -0
  16. package/dist/json/io/index.d.ts +1 -0
  17. package/dist/json/io/index.js +2 -0
  18. package/dist/json/io/index.js.map +1 -0
  19. package/dist/json/io/writer.d.ts +15 -0
  20. package/dist/json/io/writer.js +45 -0
  21. package/dist/json/io/writer.js.map +1 -0
  22. package/dist/json/walker/index.d.ts +2 -0
  23. package/dist/json/walker/index.js +3 -0
  24. package/dist/json/walker/index.js.map +1 -0
  25. package/dist/json/walker/jsonContext.d.ts +12 -0
  26. package/dist/json/walker/jsonContext.js +42 -0
  27. package/dist/json/walker/jsonContext.js.map +1 -0
  28. package/dist/json/walker/jsonGen.d.ts +19 -0
  29. package/dist/json/walker/jsonGen.js +209 -0
  30. package/dist/json/walker/jsonGen.js.map +1 -0
  31. package/dist/json/walker/log/trace.d.ts +3 -0
  32. package/dist/json/walker/log/trace.js +11 -0
  33. package/dist/json/walker/log/trace.js.map +1 -0
  34. package/dist/json/walker/naming.d.ts +8 -0
  35. package/dist/json/walker/naming.js +66 -0
  36. package/dist/json/walker/naming.js.map +1 -0
  37. package/dist/json/walker/types/index.d.ts +4 -0
  38. package/dist/json/walker/types/index.js +5 -0
  39. package/dist/json/walker/types/index.js.map +1 -0
  40. package/dist/json/walker/types/jsonArray.d.ts +13 -0
  41. package/dist/json/walker/types/jsonArray.js +70 -0
  42. package/dist/json/walker/types/jsonArray.js.map +1 -0
  43. package/dist/json/walker/types/jsonObj.d.ts +17 -0
  44. package/dist/json/walker/types/jsonObj.js +76 -0
  45. package/dist/json/walker/types/jsonObj.js.map +1 -0
  46. package/dist/json/walker/types/jsonScalar.d.ts +12 -0
  47. package/dist/json/walker/types/jsonScalar.js +39 -0
  48. package/dist/json/walker/types/jsonScalar.js.map +1 -0
  49. package/dist/json/walker/types/jsonType.d.ts +16 -0
  50. package/dist/json/walker/types/jsonType.js +30 -0
  51. package/dist/json/walker/types/jsonType.js.map +1 -0
  52. package/dist/oas/index.d.ts +14 -0
  53. package/dist/oas/index.js +15 -0
  54. package/dist/oas/index.js.map +1 -0
  55. package/dist/oas/io/writer.d.ts +25 -0
  56. package/dist/oas/io/writer.js +313 -0
  57. package/dist/oas/io/writer.js.map +1 -0
  58. package/dist/oas/log/trace.d.ts +3 -0
  59. package/dist/oas/log/trace.js +7 -0
  60. package/dist/oas/log/trace.js.map +1 -0
  61. package/dist/oas/nodes/arr.d.ts +15 -0
  62. package/dist/oas/nodes/arr.js +47 -0
  63. package/dist/oas/nodes/arr.js.map +1 -0
  64. package/dist/oas/nodes/circularRef.d.ts +13 -0
  65. package/dist/oas/nodes/circularRef.js +39 -0
  66. package/dist/oas/nodes/circularRef.js.map +1 -0
  67. package/dist/oas/nodes/comp.d.ts +18 -0
  68. package/dist/oas/nodes/comp.js +156 -0
  69. package/dist/oas/nodes/comp.js.map +1 -0
  70. package/dist/oas/nodes/en.d.ts +14 -0
  71. package/dist/oas/nodes/en.js +57 -0
  72. package/dist/oas/nodes/en.js.map +1 -0
  73. package/dist/oas/nodes/factory.d.ts +17 -0
  74. package/dist/oas/nodes/factory.js +174 -0
  75. package/dist/oas/nodes/factory.js.map +1 -0
  76. package/dist/oas/nodes/get.d.ts +24 -0
  77. package/dist/oas/nodes/get.js +167 -0
  78. package/dist/oas/nodes/get.js.map +1 -0
  79. package/dist/oas/nodes/obj.d.ts +15 -0
  80. package/dist/oas/nodes/obj.js +177 -0
  81. package/dist/oas/nodes/obj.js.map +1 -0
  82. package/dist/oas/nodes/param/param.d.ts +17 -0
  83. package/dist/oas/nodes/param/param.js +64 -0
  84. package/dist/oas/nodes/param/param.js.map +1 -0
  85. package/dist/oas/nodes/props/prop.d.ts +12 -0
  86. package/dist/oas/nodes/props/prop.js +33 -0
  87. package/dist/oas/nodes/props/prop.js.map +1 -0
  88. package/dist/oas/nodes/props/propArray.d.ts +15 -0
  89. package/dist/oas/nodes/props/propArray.js +75 -0
  90. package/dist/oas/nodes/props/propArray.js.map +1 -0
  91. package/dist/oas/nodes/props/propObj.d.ts +16 -0
  92. package/dist/oas/nodes/props/propObj.js +70 -0
  93. package/dist/oas/nodes/props/propObj.js.map +1 -0
  94. package/dist/oas/nodes/props/propRef.d.ts +19 -0
  95. package/dist/oas/nodes/props/propRef.js +108 -0
  96. package/dist/oas/nodes/props/propRef.js.map +1 -0
  97. package/dist/oas/nodes/props/propScalar.d.ts +16 -0
  98. package/dist/oas/nodes/props/propScalar.js +47 -0
  99. package/dist/oas/nodes/props/propScalar.js.map +1 -0
  100. package/dist/oas/nodes/props/referenceObject.d.ts +3 -0
  101. package/dist/oas/nodes/props/referenceObject.js +2 -0
  102. package/dist/oas/nodes/props/referenceObject.js.map +1 -0
  103. package/dist/oas/nodes/ref.d.ts +17 -0
  104. package/dist/oas/nodes/ref.js +70 -0
  105. package/dist/oas/nodes/ref.js.map +1 -0
  106. package/dist/oas/nodes/response.d.ts +14 -0
  107. package/dist/oas/nodes/response.js +48 -0
  108. package/dist/oas/nodes/response.js.map +1 -0
  109. package/dist/oas/nodes/scalar.d.ts +12 -0
  110. package/dist/oas/nodes/scalar.js +26 -0
  111. package/dist/oas/nodes/scalar.js.map +1 -0
  112. package/dist/oas/nodes/type.d.ts +43 -0
  113. package/dist/oas/nodes/type.js +107 -0
  114. package/dist/oas/nodes/type.js.map +1 -0
  115. package/dist/oas/nodes/union.d.ts +16 -0
  116. package/dist/oas/nodes/union.js +133 -0
  117. package/dist/oas/nodes/union.js.map +1 -0
  118. package/dist/oas/oasContext.d.ts +23 -0
  119. package/dist/oas/oasContext.js +73 -0
  120. package/dist/oas/oasContext.js.map +1 -0
  121. package/dist/oas/oasGen.d.ts +28 -0
  122. package/dist/oas/oasGen.js +166 -0
  123. package/dist/oas/oasGen.js.map +1 -0
  124. package/dist/oas/prompts/base/theme.d.ts +1 -0
  125. package/dist/oas/prompts/base/theme.js +50 -0
  126. package/dist/oas/prompts/base/theme.js.map +1 -0
  127. package/dist/oas/prompts/base/utils.d.ts +3 -0
  128. package/dist/oas/prompts/base/utils.js +8 -0
  129. package/dist/oas/prompts/base/utils.js.map +1 -0
  130. package/dist/oas/prompts/prompt.d.ts +19 -0
  131. package/dist/oas/prompts/prompt.js +176 -0
  132. package/dist/oas/prompts/prompt.js.map +1 -0
  133. package/dist/oas/prompts/theme.d.ts +126 -0
  134. package/dist/oas/prompts/theme.js +2 -0
  135. package/dist/oas/prompts/theme.js.map +1 -0
  136. package/dist/oas/utils/gql.d.ts +5 -0
  137. package/dist/oas/utils/gql.js +35 -0
  138. package/dist/oas/utils/gql.js.map +1 -0
  139. package/dist/oas/utils/naming.d.ts +16 -0
  140. package/dist/oas/utils/naming.js +143 -0
  141. package/dist/oas/utils/naming.js.map +1 -0
  142. package/dist/oas/utils/typeUtils.d.ts +6 -0
  143. package/dist/oas/utils/typeUtils.js +25 -0
  144. package/dist/oas/utils/typeUtils.js.map +1 -0
  145. package/package.json +77 -0
  146. package/readme.md +383 -0
@@ -0,0 +1,166 @@
1
+ import Oas from 'oas';
2
+ import OASNormalize from 'oas-normalize';
3
+ import fs from 'fs';
4
+ import { OasContext } from './oasContext.js';
5
+ import { Factory } from './nodes/factory.js';
6
+ import { Writer } from './io/writer.js';
7
+ import { trace } from './log/trace.js';
8
+ export class OasGen {
9
+ static async fromData(data, options = {
10
+ skipValidation: false,
11
+ }) {
12
+ const normalizer = new OASNormalize(data, {
13
+ enablePaths: true,
14
+ });
15
+ const _loaded = await normalizer.load();
16
+ console.log('loaded file');
17
+ const _normalised = await normalizer.bundle();
18
+ console.log('loaded bundle');
19
+ if (!options.skipValidation) {
20
+ const validated = await normalizer.validate();
21
+ if (!validated) {
22
+ console.log('validated', validated);
23
+ throw new Error('Could not validate source file');
24
+ }
25
+ }
26
+ const json = await normalizer.convert();
27
+ console.log('converted');
28
+ const parser = new Oas(json);
29
+ // return new ConnectorGen(oas, prompt);
30
+ return new OasGen(parser);
31
+ }
32
+ static async fromFile(sourceFile, options = {
33
+ skipValidation: false,
34
+ }) {
35
+ if (!fs.existsSync(sourceFile)) {
36
+ throw new Error('Source not found: ' + sourceFile);
37
+ }
38
+ // const options = { resolve: true, resolveCombinators: false };
39
+ // const oas = new OpenAPIV3Parser().read(source, null, options);
40
+ const normalizer = new OASNormalize(sourceFile, {
41
+ enablePaths: true,
42
+ });
43
+ const _loaded = await normalizer.load();
44
+ console.log('loaded file');
45
+ const _normalised = await normalizer.bundle();
46
+ console.log('loaded bundle');
47
+ if (!options.skipValidation) {
48
+ const validated = await normalizer.validate();
49
+ if (!validated) {
50
+ console.log('validated', validated);
51
+ throw new Error('Could not validate source file');
52
+ }
53
+ }
54
+ const json = await normalizer.convert();
55
+ console.log('converted');
56
+ const parser = new Oas(json);
57
+ // return new ConnectorGen(oas, prompt);
58
+ return new OasGen(parser);
59
+ }
60
+ parser;
61
+ // public prompt: Prompt;
62
+ context;
63
+ paths = new Map();
64
+ constructor(parser) {
65
+ this.parser = parser;
66
+ // this.prompt = prompt;
67
+ }
68
+ title() {
69
+ return this.parser.getDefinition().info.title;
70
+ }
71
+ version() {
72
+ return this.parser.getDefinition().info.version;
73
+ }
74
+ generateSchema(paths) {
75
+ const writer = new Writer(this);
76
+ writer.generate(paths);
77
+ return writer.flush();
78
+ }
79
+ async visit() {
80
+ const parser = this.parser;
81
+ const context = this.getContext();
82
+ const paths = parser.getPaths();
83
+ const filtered = Object.entries(paths)
84
+ .filter(([_key, pathItem]) => pathItem.get !== undefined)
85
+ .sort((a, b) => a[0].localeCompare(b[0], undefined, { sensitivity: 'base' }));
86
+ const collected = new Map();
87
+ for (const [key, pathItem] of filtered) {
88
+ const result = this.visitPath(context, key, pathItem);
89
+ collected.set(key, result);
90
+ }
91
+ this.paths = collected;
92
+ }
93
+ getContext() {
94
+ if (!this.context) {
95
+ this.context = new OasContext(this.parser);
96
+ }
97
+ return this.context;
98
+ }
99
+ expand(type) {
100
+ const ctx = this.getContext();
101
+ const path = type.path();
102
+ trace(ctx, '-> [expand]', `in: path: ${path}`);
103
+ type.visit(ctx);
104
+ trace(ctx, '<- [expand]', `out: path: ${path}`);
105
+ return type.children;
106
+ }
107
+ find(path) {
108
+ for (const [_name, type] of this.paths) {
109
+ if (type.path() === path) {
110
+ return type;
111
+ }
112
+ type.visit(this.getContext());
113
+ const result = type.find(path, type.children);
114
+ if (result) {
115
+ return result;
116
+ }
117
+ }
118
+ return false;
119
+ }
120
+ findPath(path) {
121
+ let collection = Array.from(this.paths.values());
122
+ let current;
123
+ let last;
124
+ let i = 0;
125
+ const parts = path.split('>');
126
+ do {
127
+ const part = parts[i].replace(/#\/c\/s/g, '#/components/schemas');
128
+ current = collection.find((t) => t.id === part);
129
+ if (!current) {
130
+ throw new Error('Could not find type: ' + part + ' from ' + path + ', last: ' + last?.pathToRoot());
131
+ }
132
+ // make sure we expand it before we move on to the next part
133
+ this.expand(current);
134
+ last = current;
135
+ collection = Array.from(current.children.values()) || Array.from(current.props.values()) || [];
136
+ i++;
137
+ } while (i < parts.length);
138
+ return current;
139
+ }
140
+ writer() {
141
+ return new Writer(this);
142
+ }
143
+ // private methods
144
+ visitGet(_context, name, op) {
145
+ // TODO
146
+ // operation.visit(context);
147
+ return Factory.createGet(name, op);
148
+ }
149
+ printRefs(values) {
150
+ console.log('----------- ref count -------------- ');
151
+ values.forEach((value, key) => {
152
+ console.log(key + ' -> ' + value);
153
+ });
154
+ }
155
+ visitPath(context, name, pathItem) {
156
+ const operation = pathItem.get;
157
+ if (operation.constructor.name === 'Webhook') {
158
+ throw new Error('Webhook not supported');
159
+ }
160
+ trace(context, '-> [visitPath]', `in: [${name}] id: ${operation.getOperationId()}`);
161
+ const type = this.visitGet(context, name, operation);
162
+ trace(context, '<- [visitPath]', `out: [${name}] id: ${operation.getOperationId()}`);
163
+ return type;
164
+ }
165
+ }
166
+ //# sourceMappingURL=oasGen.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oasGen.js","sourceRoot":"","sources":["../../src/oas/oasGen.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,YAAY,MAAM,eAAe,CAAC;AAKzC,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE7C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAMvC,MAAM,OAAO,MAAM;IACV,MAAM,CAAC,KAAK,CAAC,QAAQ,CAC1B,IAAiB,EACjB,UAAuB;QACrB,cAAc,EAAE,KAAK;KACtB;QAED,MAAM,UAAU,GAAiB,IAAI,YAAY,CAAC,IAAI,EAAE;YACtD,WAAW,EAAE,IAAI;SAClB,CAAC,CAAC;QAEH,MAAM,OAAO,GAA4B,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;QACjE,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAE3B,MAAM,WAAW,GAAqB,MAAM,UAAU,CAAC,MAAM,EAAE,CAAC;QAChE,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAE7B,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,CAAC;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AS,SAAS,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC;QAErF,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import Oas from 'oas';\nimport OASNormalize from 'oas-normalize';\nimport { Operation, Webhook } from 'oas/operation';\nimport { OASDocument } from 'oas/types';\nimport { OpenAPI } from 'openapi-types';\n\nimport fs from 'fs';\nimport { OasContext } from './oasContext.js';\nimport { Factory } from './nodes/factory.js';\nimport { IType } from './nodes/type.js';\nimport { Writer } from './io/writer.js';\nimport { trace } from './log/trace.js';\n\ninterface IGenOptions {\n skipValidation: boolean;\n}\n\nexport class OasGen {\n public static async fromData(\n data: ArrayBuffer,\n options: IGenOptions = {\n skipValidation: false,\n },\n ): Promise<OasGen> {\n const normalizer: OASNormalize = new OASNormalize(data, {\n enablePaths: true,\n });\n\n const _loaded: Record<string, unknown> = await normalizer.load();\n console.log('loaded file');\n\n const _normalised: OpenAPI.Document = await normalizer.bundle();\n console.log('loaded bundle');\n\n if (!options.skipValidation) {\n const validated: boolean = await normalizer.validate();\n if (!validated) {\n console.log('validated', validated);\n throw new Error('Could not validate source file');\n }\n }\n\n const json = await normalizer.convert();\n console.log('converted');\n\n const parser: Oas = new Oas(json as OASDocument);\n // return new ConnectorGen(oas, prompt);\n return new OasGen(parser);\n }\n\n public static async fromFile(\n sourceFile: string,\n options: IGenOptions = {\n skipValidation: false,\n },\n // prompt: Prompt\n ): Promise<OasGen> {\n if (!fs.existsSync(sourceFile)) {\n throw new Error('Source not found: ' + sourceFile);\n }\n\n // const options = { resolve: true, resolveCombinators: false };\n // const oas = new OpenAPIV3Parser().read(source, null, options);\n const normalizer: OASNormalize = new OASNormalize(sourceFile, {\n enablePaths: true,\n });\n\n const _loaded: Record<string, unknown> = await normalizer.load();\n console.log('loaded file');\n\n const _normalised: OpenAPI.Document = await normalizer.bundle();\n console.log('loaded bundle');\n\n if (!options.skipValidation) {\n const validated: boolean = await normalizer.validate();\n if (!validated) {\n console.log('validated', validated);\n throw new Error('Could not validate source file');\n }\n }\n\n const json = await normalizer.convert();\n console.log('converted');\n\n const parser: Oas = new Oas(json as OASDocument);\n // return new ConnectorGen(oas, prompt);\n return new OasGen(parser);\n }\n\n public parser: Oas;\n // public prompt: Prompt;\n public context?: OasContext;\n public paths: Map<string, IType> = new Map();\n\n constructor(parser: Oas) {\n this.parser = parser;\n // this.prompt = prompt;\n }\n\n public title(): string {\n return this.parser.getDefinition().info.title;\n }\n\n public version(): string {\n return this.parser.getDefinition().info.version;\n }\n\n public generateSchema(paths: string[]): string {\n const writer: Writer = new Writer(this);\n writer.generate(paths);\n return writer.flush();\n }\n\n public async visit(): Promise<void> {\n const parser = this.parser;\n const context = this.getContext();\n\n const paths = parser.getPaths();\n const filtered = Object.entries(paths)\n .filter(([_key, pathItem]) => pathItem.get !== undefined)\n .sort((a, b) => a[0].localeCompare(b[0], undefined, { sensitivity: 'base' }));\n\n const collected = new Map<string, IType>();\n for (const [key, pathItem] of filtered) {\n const result = this.visitPath(context, key, pathItem);\n collected.set(key, result);\n }\n\n this.paths = collected;\n }\n\n public getContext(): OasContext {\n if (!this.context) {\n this.context = new OasContext(this.parser);\n }\n return this.context;\n }\n\n public expand(type: IType): IType[] {\n const ctx = this.getContext();\n const path = type.path();\n\n trace(ctx, '-> [expand]', `in: path: ${path}`);\n type.visit(ctx);\n trace(ctx, '<- [expand]', `out: path: ${path}`);\n\n return type.children;\n }\n\n public find(path: string): IType | boolean {\n for (const [_name, type] of this.paths) {\n if (type.path() === path) {\n return type;\n }\n\n type.visit(this.getContext());\n\n const result = type.find(path, type.children);\n if (result) {\n return result;\n }\n }\n\n return false;\n }\n\n public findPath(path: string): IType | boolean {\n let collection = Array.from(this.paths.values());\n let current: IType | undefined;\n let last: IType | undefined;\n\n let i = 0;\n const parts = path.split('>');\n do {\n const part = parts[i].replace(/#\\/c\\/s/g, '#/components/schemas');\n current = collection.find((t) => t.id === part);\n if (!current) {\n throw new Error('Could not find type: ' + part + ' from ' + path + ', last: ' + last?.pathToRoot());\n }\n\n // make sure we expand it before we move on to the next part\n this.expand(current);\n last = current;\n\n collection = Array.from(current!.children.values()) || Array.from(current!.props.values()) || [];\n\n i++;\n } while (i < parts.length);\n\n return current;\n }\n\n public writer(): Writer {\n return new Writer(this);\n }\n\n // private methods\n\n private visitGet(_context: OasContext, name: string, op: Operation): IType {\n // TODO\n // operation.visit(context);\n return Factory.createGet(name, op);\n }\n\n private printRefs(values: Map<string, number>): void {\n console.log('----------- ref count -------------- ');\n values.forEach((value, key) => {\n console.log(key + ' -> ' + value);\n });\n }\n\n private visitPath(context: OasContext, name: string, pathItem: Record<string, Webhook | Operation>): IType {\n const operation = pathItem.get;\n if (operation.constructor.name === 'Webhook') {\n throw new Error('Webhook not supported');\n }\n\n trace(context, '-> [visitPath]', `in: [${name}] id: ${operation.getOperationId()}`);\n const type = this.visitGet(context, name, operation);\n trace(context, '<- [visitPath]', `out: [${name}] id: ${operation.getOperationId()}`);\n\n return type;\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,50 @@
1
+ export {};
2
+ // const theme: CustomTheme = {
3
+ // prefix: {
4
+ // idle: colors.cyan('?'),
5
+ // done: colors.green(figures.tick),
6
+ // canceled: colors.red(figures.cross)
7
+ // },
8
+ // style: {
9
+ // disabled: (text: string) => colors.dim(text),
10
+ // active: (text: string) => colors.cyan(text),
11
+ // cancelText: (text: string) => colors.red(text),
12
+ // emptyText: (text: string) => colors.red(text),
13
+ // directory: (text: string) => colors.yellow(text),
14
+ // file: (text: string) => colors.white(text),
15
+ // currentDir: (text: string) => colors.magenta(text),
16
+ // message: (text: string, _status: Status) => colors.bold(text),
17
+ // help: (text: string) => colors.white(text),
18
+ // key: (text: string) => colors.cyan(text)
19
+ // },
20
+ // labels: {
21
+ // disabled: '(not allowed)'
22
+ // },
23
+ // hierarchySymbols: {
24
+ // branch: figures.lineUpDownRight + figures.line,
25
+ // leaf: figures.lineUpRight + figures.line
26
+ // },
27
+ // renderItem(item: IType, context: RenderContext) {
28
+ // const isLast = context.index === context.items.length - 1
29
+ // const linePrefix =
30
+ // isLast && !context.loop
31
+ // ? this.hierarchySymbols.leaf
32
+ // : this.hierarchySymbols.branch
33
+ //
34
+ // const isDirectory = !(item instanceof PropScalar)
35
+ // const line = isDirectory
36
+ // ? `${linePrefix} ${item.name}+`
37
+ // : `${linePrefix} ${item.name}`
38
+ //
39
+ // // if (item.isDisabled) {
40
+ // // return this.style.disabled(`${line} ${this.labels.disabled}`)
41
+ // // }
42
+ //
43
+ // const baseColor = isDirectory ? this.style.directory : this.style.file
44
+ // const color = context.isActive ? this.style.active : baseColor
45
+ //
46
+ // return color(line)
47
+ // }
48
+ // }
49
+ // export default theme;
50
+ //# sourceMappingURL=theme.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"theme.js","sourceRoot":"","sources":["../../../../src/oas/prompts/base/theme.ts"],"names":[],"mappings":";AAGA,+BAA+B;AAC/B,cAAc;AACd,8BAA8B;AAC9B,wCAAwC;AACxC,0CAA0C;AAC1C,OAAO;AACP,aAAa;AACb,oDAAoD;AACpD,mDAAmD;AACnD,sDAAsD;AACtD,qDAAqD;AACrD,wDAAwD;AACxD,kDAAkD;AAClD,0DAA0D;AAC1D,qEAAqE;AACrE,kDAAkD;AAClD,+CAA+C;AAC/C,OAAO;AACP,cAAc;AACd,gCAAgC;AAChC,OAAO;AACP,wBAAwB;AACxB,sDAAsD;AACtD,+CAA+C;AAC/C,OAAO;AACP,sDAAsD;AACtD,gEAAgE;AAChE,yBAAyB;AACzB,gCAAgC;AAChC,uCAAuC;AACvC,yCAAyC;AACzC,EAAE;AACF,wDAAwD;AACxD,+BAA+B;AAC/B,wCAAwC;AACxC,uCAAuC;AACvC,EAAE;AACF,gCAAgC;AAChC,yEAAyE;AACzE,WAAW;AACX,EAAE;AACF,6EAA6E;AAC7E,qEAAqE;AACrE,EAAE;AACF,yBAAyB;AACzB,MAAM;AACN,IAAI;AAEJ,wBAAwB","sourcesContent":["import { Status } from '@inquirer/core';\nimport figures from '@inquirer/figures';\n\n// const theme: CustomTheme = {\n// prefix: {\n// idle: colors.cyan('?'),\n// done: colors.green(figures.tick),\n// canceled: colors.red(figures.cross)\n// },\n// style: {\n// disabled: (text: string) => colors.dim(text),\n// active: (text: string) => colors.cyan(text),\n// cancelText: (text: string) => colors.red(text),\n// emptyText: (text: string) => colors.red(text),\n// directory: (text: string) => colors.yellow(text),\n// file: (text: string) => colors.white(text),\n// currentDir: (text: string) => colors.magenta(text),\n// message: (text: string, _status: Status) => colors.bold(text),\n// help: (text: string) => colors.white(text),\n// key: (text: string) => colors.cyan(text)\n// },\n// labels: {\n// disabled: '(not allowed)'\n// },\n// hierarchySymbols: {\n// branch: figures.lineUpDownRight + figures.line,\n// leaf: figures.lineUpRight + figures.line\n// },\n// renderItem(item: IType, context: RenderContext) {\n// const isLast = context.index === context.items.length - 1\n// const linePrefix =\n// isLast && !context.loop\n// ? this.hierarchySymbols.leaf\n// : this.hierarchySymbols.branch\n//\n// const isDirectory = !(item instanceof PropScalar)\n// const line = isDirectory\n// ? `${linePrefix} ${item.name}+`\n// : `${linePrefix} ${item.name}`\n//\n// // if (item.isDisabled) {\n// // return this.style.disabled(`${line} ${this.labels.disabled}`)\n// // }\n//\n// const baseColor = isDirectory ? this.style.directory : this.style.file\n// const color = context.isActive ? this.style.active : baseColor\n//\n// return color(line)\n// }\n// }\n\n// export default theme;\n"]}
@@ -0,0 +1,3 @@
1
+ import { KeypressEvent } from '@inquirer/core';
2
+ export declare function isEscapeKey(key: KeypressEvent): boolean;
3
+ export declare function getMaxLength(arr: string[]): number;
@@ -0,0 +1,8 @@
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ export function isEscapeKey(key) {
3
+ return key.name === 'escape';
4
+ }
5
+ export function getMaxLength(arr) {
6
+ return arr.reduce((maxLength, str) => Math.max(maxLength, stripVTControlCharacters(str).length), 0);
7
+ }
8
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/oas/prompts/base/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAErD,MAAM,UAAU,WAAW,CAAC,GAAkB;IAC5C,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC;AAC/B,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAa;IACxC,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,wBAAwB,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;AACtG,CAAC","sourcesContent":["import { KeypressEvent } from '@inquirer/core';\nimport { stripVTControlCharacters } from 'node:util';\n\nexport function isEscapeKey(key: KeypressEvent): boolean {\n return key.name === 'escape';\n}\n\nexport function getMaxLength(arr: string[]): number {\n return arr.reduce((maxLength, str) => Math.max(maxLength, stripVTControlCharacters(str).length), 0);\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import { Theme } from '@inquirer/core';
2
+ import type { PartialDeep } from '@inquirer/type';
3
+ import { OasContext } from '../oasContext.js';
4
+ import { IType } from '../nodes/type.js';
5
+ interface PromptConfig {
6
+ message: string;
7
+ context: OasContext;
8
+ types: IType[];
9
+ pageSize?: number;
10
+ loop?: boolean;
11
+ allowCancel?: boolean;
12
+ cancelText?: string;
13
+ expandFn: (type?: IType) => IType[];
14
+ theme?: PartialDeep<Theme<IPromptTheme>>;
15
+ }
16
+ interface IPromptTheme {
17
+ }
18
+ export declare const typesPrompt: import("@inquirer/type").Prompt<string[] | [], PromptConfig>;
19
+ export {};
@@ -0,0 +1,176 @@
1
+ import colors from 'yoctocolors-cjs';
2
+ import { createPrompt, isBackspaceKey, isDownKey, isEnterKey, isSpaceKey, isUpKey, makeTheme, useKeypress, useMemo, usePagination, usePrefix, useState, } from '@inquirer/core';
3
+ import figures from '@inquirer/figures';
4
+ import _ from 'lodash';
5
+ import { CircularRef } from '../nodes/circularRef.js';
6
+ import { Composed } from '../nodes/comp.js';
7
+ import { En } from '../nodes/en.js';
8
+ import { PropArray } from '../nodes/props/propArray.js';
9
+ import { PropScalar } from '../nodes/props/propScalar.js';
10
+ import { getMaxLength, isEscapeKey } from './base/utils.js';
11
+ const baseTheme = {
12
+ prefix: {
13
+ idle: colors.cyan('?'),
14
+ done: colors.green(figures.tick),
15
+ canceled: colors.red(figures.cross),
16
+ },
17
+ style: {
18
+ disabled: (text) => colors.dim(text),
19
+ active: (text) => colors.cyan(text),
20
+ cancelText: (text) => colors.red(text),
21
+ emptyText: (text) => colors.red(text),
22
+ directory: (text) => colors.yellow(text),
23
+ file: (text) => colors.white(text),
24
+ currentDir: (text) => colors.magenta(text),
25
+ message: (text, _status) => colors.bold(text),
26
+ help: (text) => colors.white(text),
27
+ key: (text) => colors.cyan(text),
28
+ },
29
+ labels: {
30
+ disabled: '(not allowed)',
31
+ },
32
+ hierarchySymbols: {
33
+ branch: figures.lineUpDownRight + figures.line,
34
+ leaf: figures.lineUpRight + figures.line,
35
+ },
36
+ renderItem(item, context) {
37
+ const isLast = context.index === context.items.length - 1;
38
+ const linePrefix = isLast && !context.loop ? this.hierarchySymbols.leaf : this.hierarchySymbols.branch;
39
+ const isLeaf = isTypeLeaf(item);
40
+ let line = !isLeaf
41
+ ? `${item.forPrompt(context.context)} ${figures.triangleRight}`
42
+ : `${item.forPrompt(context.context)}`;
43
+ if (isLeaf) {
44
+ line = context.selected.includes(item.path()) ? `${figures.radioOn} ${line}` : `${figures.radioOff} ${line}`;
45
+ }
46
+ line = `${linePrefix} ${line}`;
47
+ const baseColor = !isLeaf ? this.style.directory : this.style.file;
48
+ const color = context.isActive ? this.style.active : baseColor;
49
+ const isDisabled = item instanceof CircularRef;
50
+ return isDisabled ? this.style.disabled(`${line} ${this.labels.disabled}`) : color(line);
51
+ },
52
+ };
53
+ const ANSI_HIDE_CURSOR = '\x1B[?25l';
54
+ const isTypeLeaf = (type) => {
55
+ return (type instanceof PropScalar ||
56
+ type instanceof En ||
57
+ type instanceof CircularRef ||
58
+ (type instanceof PropArray && type.items instanceof PropScalar));
59
+ };
60
+ export const typesPrompt = createPrompt((config, done) => {
61
+ const { pageSize = 40, loop = false, allowCancel = false, cancelText = 'Canceled.' } = config;
62
+ const [status, setStatus] = useState('idle');
63
+ const theme = makeTheme(baseTheme, config.theme);
64
+ const prefix = usePrefix({ status, theme });
65
+ const [current, setCurrent] = useState();
66
+ const [selected, setSelected] = useState([]);
67
+ const items = useMemo(() => {
68
+ // console.log('expanding', current);
69
+ if (!current) {
70
+ return config.types;
71
+ }
72
+ return config.expandFn(current);
73
+ }, [current]);
74
+ const bounds = useMemo(() => {
75
+ const first = 0; // items.findIndex(item => !item.isDisabled)
76
+ const last = items.length - 1; // items.findLastIndex(item => !item.isDisabled)
77
+ return { first, last };
78
+ }, [items]);
79
+ const [active, setActive] = useState(bounds.first);
80
+ const activeItem = items[active];
81
+ useKeypress((key, rl) => {
82
+ if (isEnterKey(key)) {
83
+ setStatus('done');
84
+ done(selected);
85
+ }
86
+ else if (isSelectKey(key)) {
87
+ if (activeItem instanceof CircularRef) {
88
+ return;
89
+ }
90
+ if (selected.includes(activeItem.path())) {
91
+ setSelected(selected.filter((path) => path !== activeItem.path()));
92
+ }
93
+ else {
94
+ setSelected([...selected, activeItem.path()]);
95
+ }
96
+ }
97
+ else if (isSelectAllKey(key)) {
98
+ const children = current instanceof Composed ? current.props.values() : current.children.values();
99
+ const filtered = Array.from(children)
100
+ .filter((child) => isTypeLeaf(child) && !selected.includes(child.path()))
101
+ .map((child) => child.path()) ?? [];
102
+ setSelected([...selected, ...filtered]);
103
+ }
104
+ else if (isSelectNoneKey(key)) {
105
+ const filtered = activeItem.parent?.children
106
+ .filter((child) => isTypeLeaf(child) && selected.includes(child.path()))
107
+ .map((child) => child.path()) ?? [];
108
+ setSelected(selected.filter((path) => !filtered.includes(path)));
109
+ }
110
+ else {
111
+ const isLeaf = isTypeLeaf(activeItem);
112
+ if ((isSpaceKey(key) || isRightKey(key)) && !isLeaf) {
113
+ setCurrent(activeItem);
114
+ setActive(bounds.first);
115
+ }
116
+ // up and down
117
+ else if (isUpKey(key) || isDownKey(key)) {
118
+ rl.clearLine(0);
119
+ if (loop || (isUpKey(key) && active !== bounds.first) || (isDownKey(key) && active !== bounds.last)) {
120
+ const offset = isUpKey(key) ? -1 : 1;
121
+ let next = active;
122
+ next = (next + offset + items.length) % items.length;
123
+ setActive(next);
124
+ }
125
+ }
126
+ else if (isBackspaceKey(key) || isLeftKey(key)) {
127
+ setCurrent(current?.parent);
128
+ setActive(bounds.first);
129
+ }
130
+ else if (isEscapeKey(key) && allowCancel) {
131
+ setStatus('canceled');
132
+ done([]);
133
+ }
134
+ }
135
+ });
136
+ const page = usePagination({
137
+ items,
138
+ active,
139
+ renderItem: ({ item, index, isActive }) => theme.renderItem(item, { items, index, isActive, loop, selected, context: config.context }),
140
+ pageSize,
141
+ loop,
142
+ });
143
+ const message = theme.style.message(config.message, status);
144
+ if (status === 'canceled') {
145
+ return `${prefix} ${message} ${theme.style.cancelText(cancelText)}`;
146
+ }
147
+ if (status === 'done') {
148
+ return `${prefix} ${message} ${theme.style.answer(activeItem.path())}`;
149
+ }
150
+ const header = _.replace(theme.style.currentDir(current?.path() ?? 'Get operations:'), />/g, ` ${figures.triangleRight} `);
151
+ const helpTip = useMemo(() => {
152
+ const helpTipLines = [
153
+ `${theme.style.key(figures.arrowUp + figures.arrowDown)} navigate, ${theme.style.key('<x>')} select field, ${theme.style.key('<a>')} select all fields, ${theme.style.key('<n>')} deselect all fields, ${theme.style.key('<enter>')} finish${allowCancel ? `, ${theme.style.key('<esc>')} cancel` : ''}`,
154
+ `${theme.style.key('<space>')} expand type, ${theme.style.key('<backspace>')} go back`,
155
+ ];
156
+ const helpTipMaxLength = getMaxLength(helpTipLines);
157
+ const delimiter = figures.lineBold.repeat(helpTipMaxLength);
158
+ return `${delimiter}\n${helpTipLines.join('\n')}`;
159
+ }, []);
160
+ return `${prefix} ${message}\n${header}\n${!page.length ? theme.style.emptyText('emptyText') : page}\n${helpTip}${ANSI_HIDE_CURSOR}`;
161
+ });
162
+ const isLeftKey = (key) =>
163
+ // The left key
164
+ key.name === 'left' ||
165
+ // Vim keybinding
166
+ key.name === 'j';
167
+ const isRightKey = (key) =>
168
+ // The right key
169
+ key.name === 'right' ||
170
+ // Vim keybinding
171
+ key.name === 'l';
172
+ const isSelectKey = (key) => key.name === 'x';
173
+ const isSelectAllKey = (key) => key.name === 'a';
174
+ const isSelectNoneKey = (key) => key.name === 'n';
175
+ const isInvertKey = (key) => key.name === 'a';
176
+ //# sourceMappingURL=prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../../src/oas/prompts/prompt.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,iBAAiB,CAAC;AAErC,OAAO,EACL,YAAY,EACZ,cAAc,EACd,SAAS,EACT,UAAU,EACV,UAAU,EACV,OAAO,EAEP,SAAS,EAGT,WAAW,EACX,OAAO,EACP,aAAa,EACb,SAAS,EACT,QAAQ,GACT,MAAM,gBAAgB,CAAC;AACxB,OAAO,OAAO,MAAM,mBAAmB,CAAC;AAExC,OAAO,CAAC,MAAM,QAAQ,CAAC;AAGvB,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,EAAE,EAAE,MAAM,gBAAgB,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG5D,MAAM,SAAS,GAAgB;IAC7B,MAAM,EAAE;QACN,IAAI,EAAE,MAAM,CAA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,GAAkB,EAAW,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC;AAE1E,MAAM,WAAW,GAAG,CAAC,GAAkB,EAAW,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC","sourcesContent":["import colors from 'yoctocolors-cjs';\n\nimport {\n createPrompt,\n isBackspaceKey,\n isDownKey,\n isEnterKey,\n isSpaceKey,\n isUpKey,\n KeypressEvent,\n makeTheme,\n Theme,\n type Status,\n useKeypress,\n useMemo,\n usePagination,\n usePrefix,\n useState,\n} from '@inquirer/core';\nimport figures from '@inquirer/figures';\nimport type { PartialDeep } from '@inquirer/type';\nimport _ from 'lodash';\n\nimport { OasContext } from '../oasContext.js';\nimport { CircularRef } from '../nodes/circularRef.js';\nimport { Composed } from '../nodes/comp.js';\nimport { En } from '../nodes/en.js';\nimport { PropArray } from '../nodes/props/propArray.js';\nimport { PropScalar } from '../nodes/props/propScalar.js';\nimport { IType } from '../nodes/type.js';\nimport { getMaxLength, isEscapeKey } from './base/utils.js';\nimport { CustomTheme, RenderContext } from './theme.js';\n\nconst baseTheme: CustomTheme = {\n prefix: {\n idle: colors.cyan('?'),\n done: colors.green(figures.tick),\n canceled: colors.red(figures.cross),\n },\n style: {\n disabled: (text: string) => colors.dim(text),\n active: (text: string) => colors.cyan(text),\n cancelText: (text: string) => colors.red(text),\n emptyText: (text: string) => colors.red(text),\n directory: (text: string) => colors.yellow(text),\n file: (text: string) => colors.white(text),\n currentDir: (text: string) => colors.magenta(text),\n message: (text: string, _status: Status) => colors.bold(text),\n help: (text: string) => colors.white(text),\n key: (text: string) => colors.cyan(text),\n },\n labels: {\n disabled: '(not allowed)',\n },\n hierarchySymbols: {\n branch: figures.lineUpDownRight + figures.line,\n leaf: figures.lineUpRight + figures.line,\n },\n renderItem(item: IType, context: RenderContext) {\n const isLast = context.index === context.items.length - 1;\n\n const linePrefix = isLast && !context.loop ? this.hierarchySymbols.leaf : this.hierarchySymbols.branch;\n\n const isLeaf = isTypeLeaf(item);\n let line = !isLeaf\n ? `${item.forPrompt(context.context)} ${figures.triangleRight}`\n : `${item.forPrompt(context.context)}`;\n\n if (isLeaf) {\n line = context.selected.includes(item.path()) ? `${figures.radioOn} ${line}` : `${figures.radioOff} ${line}`;\n }\n\n line = `${linePrefix} ${line}`;\n\n const baseColor = !isLeaf ? this.style.directory : this.style.file;\n const color = context.isActive ? this.style.active : baseColor;\n\n const isDisabled = item instanceof CircularRef;\n return isDisabled ? this.style.disabled(`${line} ${this.labels.disabled}`) : color(line);\n },\n};\n\ninterface PromptConfig {\n message: string;\n context: OasContext;\n types: IType[];\n pageSize?: number;\n loop?: boolean;\n allowCancel?: boolean;\n cancelText?: string;\n expandFn: (type?: IType) => IType[];\n theme?: PartialDeep<Theme<IPromptTheme>>;\n}\n\nconst ANSI_HIDE_CURSOR = '\\x1B[?25l';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\ninterface IPromptTheme {}\n\nconst isTypeLeaf = (type: IType): boolean => {\n return (\n type instanceof PropScalar ||\n type instanceof En ||\n type instanceof CircularRef ||\n (type instanceof PropArray && type.items instanceof PropScalar)\n );\n};\n\nexport const typesPrompt = createPrompt<string[] | [], PromptConfig>((config, done) => {\n const { pageSize = 40, loop = false, allowCancel = false, cancelText = 'Canceled.' } = config;\n\n const [status, setStatus] = useState<Status>('idle');\n const theme = makeTheme<CustomTheme>(baseTheme, config.theme);\n const prefix = usePrefix({ status, theme });\n\n const [current, setCurrent] = useState<IType>();\n const [selected, setSelected] = useState<string[]>([]);\n\n const items = useMemo(() => {\n // console.log('expanding', current);\n if (!current) {\n return config.types;\n }\n return config.expandFn(current!);\n }, [current]);\n\n const bounds = useMemo(() => {\n const first = 0; // items.findIndex(item => !item.isDisabled)\n const last = items.length - 1; // items.findLastIndex(item => !item.isDisabled)\n\n return { first, last };\n }, [items]);\n\n const [active, setActive] = useState(bounds.first);\n const activeItem: IType = items[active];\n\n useKeypress((key, rl) => {\n if (isEnterKey(key)) {\n setStatus('done');\n done(selected);\n } else if (isSelectKey(key)) {\n if (activeItem instanceof CircularRef) {\n return;\n }\n\n if (selected.includes(activeItem.path())) {\n setSelected(selected.filter((path) => path !== activeItem.path()));\n } else {\n setSelected([...selected, activeItem.path()]);\n }\n } else if (isSelectAllKey(key)) {\n const children = current instanceof Composed ? current.props.values() : current!.children.values();\n\n const filtered =\n Array.from(children)\n .filter((child) => isTypeLeaf(child) && !selected.includes(child.path()))\n .map((child) => child.path()) ?? [];\n\n setSelected([...selected, ...filtered]);\n } else if (isSelectNoneKey(key)) {\n const filtered =\n activeItem.parent?.children\n .filter((child) => isTypeLeaf(child) && selected.includes(child.path()))\n .map((child) => child.path()) ?? [];\n\n setSelected(selected.filter((path) => !filtered.includes(path)));\n } else {\n const isLeaf = isTypeLeaf(activeItem);\n\n if ((isSpaceKey(key) || isRightKey(key)) && !isLeaf) {\n setCurrent(activeItem);\n setActive(bounds.first);\n }\n // up and down\n else if (isUpKey(key) || isDownKey(key)) {\n rl.clearLine(0);\n if (loop || (isUpKey(key) && active !== bounds.first) || (isDownKey(key) && active !== bounds.last)) {\n const offset = isUpKey(key) ? -1 : 1;\n let next = active;\n next = (next + offset + items.length) % items.length;\n setActive(next);\n }\n } else if (isBackspaceKey(key) || isLeftKey(key)) {\n setCurrent(current?.parent);\n setActive(bounds.first);\n } else if (isEscapeKey(key) && allowCancel) {\n setStatus('canceled');\n done([]);\n }\n }\n });\n\n const page = usePagination({\n items,\n active,\n renderItem: ({ item, index, isActive }) =>\n theme.renderItem(item, { items, index, isActive, loop, selected, context: config.context }),\n pageSize,\n loop,\n });\n\n const message = theme.style.message(config.message, status);\n\n if (status === 'canceled') {\n return `${prefix} ${message} ${theme.style.cancelText(cancelText)}`;\n }\n\n if (status === 'done') {\n return `${prefix} ${message} ${theme.style.answer(activeItem.path())}`;\n }\n\n const header = _.replace(\n theme.style.currentDir(current?.path() ?? 'Get operations:'),\n />/g,\n ` ${figures.triangleRight} `,\n );\n\n const helpTip = useMemo(() => {\n const helpTipLines = [\n `${theme.style.key(figures.arrowUp + figures.arrowDown)} navigate, ${theme.style.key('<x>')} select field, ${theme.style.key('<a>')} select all fields, ${theme.style.key('<n>')} deselect all fields, ${theme.style.key('<enter>')} finish${allowCancel ? `, ${theme.style.key('<esc>')} cancel` : ''}`,\n `${theme.style.key('<space>')} expand type, ${theme.style.key('<backspace>')} go back`,\n ];\n\n const helpTipMaxLength = getMaxLength(helpTipLines);\n const delimiter = figures.lineBold.repeat(helpTipMaxLength);\n\n return `${delimiter}\\n${helpTipLines.join('\\n')}`;\n }, []);\n\n return `${prefix} ${message}\\n${header}\\n${!page.length ? theme.style.emptyText('emptyText') : page}\\n${helpTip}${ANSI_HIDE_CURSOR}`;\n});\n\nconst isLeftKey = (key: KeypressEvent): boolean =>\n // The left key\n key.name === 'left' ||\n // Vim keybinding\n key.name === 'j';\n\nconst isRightKey = (key: KeypressEvent): boolean =>\n // The right key\n key.name === 'right' ||\n // Vim keybinding\n key.name === 'l';\n\nconst isSelectKey = (key: KeypressEvent): boolean => key.name === 'x';\n\nconst isSelectAllKey = (key: KeypressEvent): boolean => key.name === 'a';\n\nconst isSelectNoneKey = (key: KeypressEvent): boolean => key.name === 'n';\n\nconst isInvertKey = (key: KeypressEvent): boolean => key.name === 'a';\n"]}
@@ -0,0 +1,126 @@
1
+ import { Status } from '@inquirer/core';
2
+ import { OasContext } from '../oasContext.js';
3
+ import { IType } from '../nodes/type.js';
4
+ export interface RenderContext {
5
+ /**
6
+ * List of items to render.
7
+ */
8
+ items: IType[];
9
+ /**
10
+ * Index of the item in the list.
11
+ */
12
+ index: number;
13
+ /**
14
+ * Whether the item is currently active.
15
+ */
16
+ isActive: boolean;
17
+ /**
18
+ * List is displayed in loop mode.
19
+ */
20
+ loop: boolean;
21
+ /**
22
+ * List of selected paths
23
+ */
24
+ selected: string[];
25
+ /**
26
+ * The Context used by the oas
27
+ */
28
+ context: OasContext;
29
+ }
30
+ export interface CustomTheme {
31
+ prefix: {
32
+ /**
33
+ * Prefix displayed when the prompt is idle.
34
+ * @default chalk.cyan('?')
35
+ */
36
+ idle: string;
37
+ /**
38
+ * Prefix displayed when the prompt is done.
39
+ * @default chalk.green(figures.tick)
40
+ */
41
+ done: string;
42
+ /**
43
+ * Prefix displayed when the prompt is canceled.
44
+ * @default chalk.red(figures.cross)
45
+ */
46
+ canceled: string;
47
+ };
48
+ style: {
49
+ /**
50
+ * Style for disabled items.
51
+ * @default chalk.dim
52
+ */
53
+ disabled: (text: string) => string;
54
+ /**
55
+ * Style for the currently active item.
56
+ * @default chalk.cyan
57
+ */
58
+ active: (text: string) => string;
59
+ /**
60
+ * Style for the cancel text.
61
+ * @default chalk.red
62
+ */
63
+ cancelText: (text: string) => string;
64
+ /**
65
+ * Style for empty text.
66
+ * @default chalk.red
67
+ */
68
+ emptyText: (text: string) => string;
69
+ /**
70
+ * Style for items of type `'directory'`.
71
+ * @default chalk.yellow
72
+ */
73
+ directory: (text: string) => string;
74
+ /**
75
+ * Style for items of type `'file'`.
76
+ * @default chalk.white
77
+ */
78
+ file: (text: string) => string;
79
+ /**
80
+ * Style for the current directory header.
81
+ * @default chalk.magenta
82
+ */
83
+ currentDir: (text: string) => string;
84
+ /**
85
+ * Style applied to the main message, defined in `config.message`.
86
+ * @default chalk.bold
87
+ */
88
+ message: (text: string, status: Status) => string;
89
+ /**
90
+ * Style for the key binding help section.
91
+ * @default chalk.white
92
+ */
93
+ help: (text: string) => string;
94
+ /**
95
+ * Style for key labels in the help section.
96
+ * @default chalk.cyan
97
+ */
98
+ key: (text: string) => string;
99
+ };
100
+ labels: {
101
+ /**
102
+ * Label displayed next to an item when it is disabled.
103
+ * @default '(not allowed)'
104
+ */
105
+ disabled: string;
106
+ };
107
+ hierarchySymbols: {
108
+ /**
109
+ * Symbol representing branches in the tree hierarchy.
110
+ * @default '├─'
111
+ */
112
+ branch: string;
113
+ /**
114
+ * Symbol representing leaves, marking the end of the tree hierarchy.
115
+ * @default '└─'
116
+ */
117
+ leaf: string;
118
+ };
119
+ /**
120
+ * Function to render an item in the list.
121
+ * @param item - The item to render.
122
+ * @param context - Context information about the item.
123
+ * @returns The rendered item as a string.
124
+ */
125
+ renderItem: (item: IType, context: RenderContext) => string;
126
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=theme.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"theme.js","sourceRoot":"","sources":["../../../src/oas/prompts/theme.ts"],"names":[],"mappings":"","sourcesContent":["import { Status } from '@inquirer/core';\nimport { OasContext } from '../oasContext.js';\nimport { IType } from '../nodes/type.js';\n\nexport interface RenderContext {\n /**\n * List of items to render.\n */\n items: IType[];\n /**\n * Index of the item in the list.\n */\n index: number;\n /**\n * Whether the item is currently active.\n */\n isActive: boolean;\n /**\n * List is displayed in loop mode.\n */\n loop: boolean;\n /**\n * List of selected paths\n */\n selected: string[];\n /**\n * The Context used by the oas\n */\n context: OasContext;\n}\n\nexport interface CustomTheme {\n prefix: {\n /**\n * Prefix displayed when the prompt is idle.\n * @default chalk.cyan('?')\n */\n idle: string;\n /**\n * Prefix displayed when the prompt is done.\n * @default chalk.green(figures.tick)\n */\n done: string;\n /**\n * Prefix displayed when the prompt is canceled.\n * @default chalk.red(figures.cross)\n */\n canceled: string;\n };\n style: {\n /**\n * Style for disabled items.\n * @default chalk.dim\n */\n disabled: (text: string) => string;\n /**\n * Style for the currently active item.\n * @default chalk.cyan\n */\n active: (text: string) => string;\n /**\n * Style for the cancel text.\n * @default chalk.red\n */\n cancelText: (text: string) => string;\n /**\n * Style for empty text.\n * @default chalk.red\n */\n emptyText: (text: string) => string;\n /**\n * Style for items of type `'directory'`.\n * @default chalk.yellow\n */\n directory: (text: string) => string;\n /**\n * Style for items of type `'file'`.\n * @default chalk.white\n */\n file: (text: string) => string;\n /**\n * Style for the current directory header.\n * @default chalk.magenta\n */\n currentDir: (text: string) => string;\n /**\n * Style applied to the main message, defined in `config.message`.\n * @default chalk.bold\n */\n message: (text: string, status: Status) => string;\n /**\n * Style for the key binding help section.\n * @default chalk.white\n */\n help: (text: string) => string;\n /**\n * Style for key labels in the help section.\n * @default chalk.cyan\n */\n key: (text: string) => string;\n };\n labels: {\n /**\n * Label displayed next to an item when it is disabled.\n * @default '(not allowed)'\n */\n disabled: string;\n };\n hierarchySymbols: {\n /**\n * Symbol representing branches in the tree hierarchy.\n * @default '├─'\n */\n branch: string;\n /**\n * Symbol representing leaves, marking the end of the tree hierarchy.\n * @default '└─'\n */\n leaf: string;\n };\n /**\n * Function to render an item in the list.\n * @param item - The item to render.\n * @param context - Context information about the item.\n * @returns The rendered item as a string.\n */\n renderItem: (item: IType, context: RenderContext) => string;\n}\n"]}