@sap/cli-core 2023.12.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 (179) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +44 -0
  3. package/README.md +13 -0
  4. package/assets/error.html +20 -0
  5. package/assets/success.html +20 -0
  6. package/cache/cache.d.ts +6 -0
  7. package/cache/cache.js +82 -0
  8. package/cache/index.d.ts +2 -0
  9. package/cache/index.js +12 -0
  10. package/cache/utils.d.ts +1 -0
  11. package/cache/utils.js +16 -0
  12. package/commands/cache.command/clean.command.d.ts +3 -0
  13. package/commands/cache.command/clean.command.js +15 -0
  14. package/commands/cache.command/index.d.ts +3 -0
  15. package/commands/cache.command/index.js +15 -0
  16. package/commands/cache.command/init.command.d.ts +3 -0
  17. package/commands/cache.command/init.command.js +36 -0
  18. package/commands/cache.command/show.command.d.ts +3 -0
  19. package/commands/cache.command/show.command.js +30 -0
  20. package/commands/handler/authentication/index.d.ts +2 -0
  21. package/commands/handler/authentication/index.js +21 -0
  22. package/commands/handler/authentication/oauth/index.d.ts +2 -0
  23. package/commands/handler/authentication/oauth/index.js +18 -0
  24. package/commands/handler/authentication/oauth/secretsProvider/cache.d.ts +2 -0
  25. package/commands/handler/authentication/oauth/secretsProvider/cache.js +19 -0
  26. package/commands/handler/authentication/oauth/secretsProvider/file.d.ts +2 -0
  27. package/commands/handler/authentication/oauth/secretsProvider/file.js +25 -0
  28. package/commands/handler/authentication/oauth/secretsProvider/index.d.ts +2 -0
  29. package/commands/handler/authentication/oauth/secretsProvider/index.js +10 -0
  30. package/commands/handler/authentication/oauth/secretsProvider/options.d.ts +2 -0
  31. package/commands/handler/authentication/oauth/secretsProvider/options.js +30 -0
  32. package/commands/handler/authentication/oauth/tokenProvider/getToken.d.ts +2 -0
  33. package/commands/handler/authentication/oauth/tokenProvider/getToken.js +88 -0
  34. package/commands/handler/authentication/oauth/tokenProvider/index.d.ts +2 -0
  35. package/commands/handler/authentication/oauth/tokenProvider/index.js +11 -0
  36. package/commands/handler/authentication/oauth/tokenProvider/refreshToken.d.ts +2 -0
  37. package/commands/handler/authentication/oauth/tokenProvider/refreshToken.js +15 -0
  38. package/commands/handler/authentication/oauth/tokenProvider/setAuthorization.d.ts +3 -0
  39. package/commands/handler/authentication/oauth/tokenProvider/setAuthorization.js +35 -0
  40. package/commands/handler/authentication/oauth/tokenProvider/utils.d.ts +1 -0
  41. package/commands/handler/authentication/oauth/tokenProvider/utils.js +27 -0
  42. package/commands/handler/authentication/oauth/utils.d.ts +15 -0
  43. package/commands/handler/authentication/oauth/utils.js +58 -0
  44. package/commands/handler/authentication/passcode/function.d.ts +2 -0
  45. package/commands/handler/authentication/passcode/function.js +22 -0
  46. package/commands/handler/authentication/passcode/index.d.ts +2 -0
  47. package/commands/handler/authentication/passcode/index.js +19 -0
  48. package/commands/handler/authentication/passcode/input.d.ts +2 -0
  49. package/commands/handler/authentication/passcode/input.js +42 -0
  50. package/commands/handler/authentication/passcode/setPasscode.d.ts +2 -0
  51. package/commands/handler/authentication/passcode/setPasscode.js +16 -0
  52. package/commands/handler/authentication/passcode/types.d.ts +1 -0
  53. package/commands/handler/authentication/passcode/types.js +2 -0
  54. package/commands/handler/authentication/technicalJWT/cf.d.ts +4 -0
  55. package/commands/handler/authentication/technicalJWT/cf.js +133 -0
  56. package/commands/handler/authentication/technicalJWT/exec.d.ts +9 -0
  57. package/commands/handler/authentication/technicalJWT/exec.js +196 -0
  58. package/commands/handler/authentication/technicalJWT/index.d.ts +2 -0
  59. package/commands/handler/authentication/technicalJWT/index.js +15 -0
  60. package/commands/handler/authentication/technicalJWT/types.d.ts +2 -0
  61. package/commands/handler/authentication/technicalJWT/types.js +8 -0
  62. package/commands/handler/authentication/technicalJWT/utils.d.ts +1 -0
  63. package/commands/handler/authentication/technicalJWT/utils.js +70 -0
  64. package/commands/handler/authentication/utils.d.ts +3 -0
  65. package/commands/handler/authentication/utils.js +8 -0
  66. package/commands/handler/checkOptionsExistence.d.ts +2 -0
  67. package/commands/handler/checkOptionsExistence.js +17 -0
  68. package/commands/handler/error.d.ts +2 -0
  69. package/commands/handler/error.js +21 -0
  70. package/commands/handler/fail.d.ts +2 -0
  71. package/commands/handler/fail.js +10 -0
  72. package/commands/handler/fetch/fetch.d.ts +2 -0
  73. package/commands/handler/fetch/fetch.js +83 -0
  74. package/commands/handler/fetch/index.d.ts +2 -0
  75. package/commands/handler/fetch/index.js +25 -0
  76. package/commands/handler/fetch/utils.d.ts +14 -0
  77. package/commands/handler/fetch/utils.js +152 -0
  78. package/commands/handler/force.d.ts +2 -0
  79. package/commands/handler/force.js +35 -0
  80. package/commands/handler/index.d.ts +18 -0
  81. package/commands/handler/index.js +39 -0
  82. package/commands/handler/input/file.d.ts +2 -0
  83. package/commands/handler/input/file.js +34 -0
  84. package/commands/handler/input/index.d.ts +2 -0
  85. package/commands/handler/input/index.js +8 -0
  86. package/commands/handler/input/input.d.ts +2 -0
  87. package/commands/handler/input/input.js +44 -0
  88. package/commands/handler/mandatoryOptions.d.ts +2 -0
  89. package/commands/handler/mandatoryOptions.js +25 -0
  90. package/commands/handler/next.d.ts +2 -0
  91. package/commands/handler/next.js +19 -0
  92. package/commands/handler/options/env.d.ts +2 -0
  93. package/commands/handler/options/env.js +18 -0
  94. package/commands/handler/options/file.d.ts +2 -0
  95. package/commands/handler/options/file.js +21 -0
  96. package/commands/handler/options/index.d.ts +7 -0
  97. package/commands/handler/options/index.js +32 -0
  98. package/commands/handler/options/option.d.ts +2 -0
  99. package/commands/handler/options/option.js +20 -0
  100. package/commands/handler/options/pipe.d.ts +2 -0
  101. package/commands/handler/options/pipe.js +34 -0
  102. package/commands/handler/options/utils.d.ts +6 -0
  103. package/commands/handler/options/utils.js +63 -0
  104. package/commands/handler/or.d.ts +2 -0
  105. package/commands/handler/or.js +37 -0
  106. package/commands/handler/parseArguments.d.ts +4 -0
  107. package/commands/handler/parseArguments.js +22 -0
  108. package/commands/handler/resilient.d.ts +2 -0
  109. package/commands/handler/resilient.js +18 -0
  110. package/commands/handler/root/index.d.ts +2 -0
  111. package/commands/handler/root/index.js +18 -0
  112. package/commands/handler/stackTrace.d.ts +2 -0
  113. package/commands/handler/stackTrace.js +22 -0
  114. package/commands/handler/succeed.d.ts +2 -0
  115. package/commands/handler/succeed.js +9 -0
  116. package/commands/handler/utils.d.ts +7 -0
  117. package/commands/handler/utils.js +56 -0
  118. package/commands/host.command.d.ts +2 -0
  119. package/commands/host.command.js +68 -0
  120. package/commands/login.command.d.ts +3 -0
  121. package/commands/login.command.js +16 -0
  122. package/commands/logout.command.d.ts +3 -0
  123. package/commands/logout.command.js +21 -0
  124. package/commands/openAPI.command/index.d.ts +2 -0
  125. package/commands/openAPI.command/index.js +102 -0
  126. package/commands/openAPI.command/utils.d.ts +19 -0
  127. package/commands/openAPI.command/utils.js +334 -0
  128. package/commands/passcode.command.d.ts +2 -0
  129. package/commands/passcode.command.js +26 -0
  130. package/commands/secrets.command/index.d.ts +3 -0
  131. package/commands/secrets.command/index.js +13 -0
  132. package/commands/secrets.command/show.command.d.ts +3 -0
  133. package/commands/secrets.command/show.command.js +25 -0
  134. package/config/core.d.ts +10 -0
  135. package/config/core.js +23 -0
  136. package/config/index.d.ts +5 -0
  137. package/config/index.js +90 -0
  138. package/configureLoggers.d.ts +1 -0
  139. package/configureLoggers.js +11 -0
  140. package/constants.d.ts +43 -0
  141. package/constants.js +175 -0
  142. package/discovery/index.d.ts +10 -0
  143. package/discovery/index.js +142 -0
  144. package/discovery/utils.d.ts +7 -0
  145. package/discovery/utils.js +27 -0
  146. package/dwc/dwc.d.ts +10 -0
  147. package/dwc/dwc.js +180 -0
  148. package/dwc/run.d.ts +1 -0
  149. package/dwc/run.js +37 -0
  150. package/dwc/utils.d.ts +4 -0
  151. package/dwc/utils.js +37 -0
  152. package/index.d.ts +16 -0
  153. package/index.js +59 -0
  154. package/logger/index.d.ts +28 -0
  155. package/logger/index.js +63 -0
  156. package/module.d.ts +4 -0
  157. package/module.js +45 -0
  158. package/package.json +32 -0
  159. package/result/ResultHandlerFactory.d.ts +6 -0
  160. package/result/ResultHandlerFactory.js +12 -0
  161. package/result/ResultHandlerImpl.d.ts +6 -0
  162. package/result/ResultHandlerImpl.js +12 -0
  163. package/result/types.d.ts +4 -0
  164. package/result/types.js +2 -0
  165. package/schemas/discovery.json +347 -0
  166. package/settings/index.d.ts +4 -0
  167. package/settings/index.js +34 -0
  168. package/types.d.ts +182 -0
  169. package/types.js +67 -0
  170. package/utils/commands.d.ts +8 -0
  171. package/utils/commands.js +115 -0
  172. package/utils/http/index.d.ts +7 -0
  173. package/utils/http/index.js +69 -0
  174. package/utils/http/utils.d.ts +7 -0
  175. package/utils/http/utils.js +47 -0
  176. package/utils/options.d.ts +3 -0
  177. package/utils/options.js +25 -0
  178. package/utils/utils.d.ts +24 -0
  179. package/utils/utils.js +163 -0
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.create = void 0;
4
+ const logger_1 = require("../../logger");
5
+ const create = () => () => async () => {
6
+ const { debug } = (0, logger_1.get)("commands.handler.succeed");
7
+ debug(`running succeed handler`);
8
+ };
9
+ exports.create = create;
@@ -0,0 +1,7 @@
1
+ import { AuthenticationMethod } from "../../constants";
2
+ export declare const getBooleanOption: (value: unknown) => boolean;
3
+ export declare const parseOption: (value: string) => string;
4
+ export declare const setAuthenticationMethod: (authenticationMethod: AuthenticationMethod) => void;
5
+ export declare const getAuthenticationMethod: () => AuthenticationMethod;
6
+ export declare const setTargetHost: (targetHost: string) => void;
7
+ export declare const getTargetHost: () => string;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTargetHost = exports.setTargetHost = exports.getAuthenticationMethod = exports.setAuthenticationMethod = exports.parseOption = exports.getBooleanOption = void 0;
4
+ const logger_1 = require("../../logger");
5
+ const config_1 = require("../../config");
6
+ const constants_1 = require("../../constants");
7
+ const getLogger = () => (0, logger_1.get)("commands.handler.utils");
8
+ const getBooleanOption = (value) => !!value;
9
+ exports.getBooleanOption = getBooleanOption;
10
+ const decodeURIComponentInt = (value) => {
11
+ const { error } = getLogger();
12
+ try {
13
+ return decodeURIComponent(value);
14
+ }
15
+ catch (err) {
16
+ error(`Failed to decode URI for value '${value}'`, err);
17
+ throw err;
18
+ }
19
+ };
20
+ const replaceLeadingTrailingSingleQuotes = (value) => value.replace(/^'/, "").replace(/'$/, "");
21
+ const parseOption = (value) => {
22
+ if (typeof value !== "string") {
23
+ return value;
24
+ }
25
+ let v = value.trim();
26
+ v = decodeURIComponentInt(v);
27
+ v = replaceLeadingTrailingSingleQuotes(v);
28
+ return v;
29
+ };
30
+ exports.parseOption = parseOption;
31
+ const setAuthenticationMethod = (authenticationMethod) => {
32
+ (0, config_1.set)({ authenticationMethod });
33
+ };
34
+ exports.setAuthenticationMethod = setAuthenticationMethod;
35
+ const getAuthenticationMethod = () => (0, config_1.get)().authenticationMethod;
36
+ exports.getAuthenticationMethod = getAuthenticationMethod;
37
+ const setTargetHost = (targetHost) => {
38
+ (0, config_1.set)({ targetHost });
39
+ };
40
+ exports.setTargetHost = setTargetHost;
41
+ const getTargetHost = () => {
42
+ const config = (0, config_1.get)();
43
+ if (!config.targetHost) {
44
+ throw new Error("no target host set");
45
+ }
46
+ if (config.hostSetFromCustomConfig) {
47
+ const authenticationMethod = (0, exports.getAuthenticationMethod)();
48
+ if (authenticationMethod === constants_1.AuthenticationMethod.oauth) {
49
+ const { warn } = getLogger();
50
+ warn("Are you sure you want to use a custom configuration in combination with OAuth-based authentication?");
51
+ }
52
+ return config.host;
53
+ }
54
+ return config.targetHost;
55
+ };
56
+ exports.getTargetHost = getTargetHost;
@@ -0,0 +1,2 @@
1
+ import { AddCommands } from "../types";
2
+ export declare const addCommands: AddCommands;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addCommands = void 0;
4
+ const config_1 = require("../config");
5
+ const constants_1 = require("../constants");
6
+ const logger_1 = require("../logger");
7
+ const settings_1 = require("../settings");
8
+ const commands_1 = require("../utils/commands");
9
+ const utils_1 = require("../utils/utils");
10
+ const handler_1 = require("./handler");
11
+ const getLogger = () => (0, logger_1.get)("commands.host");
12
+ const set = () => async () => {
13
+ const config = (0, config_1.get)();
14
+ try {
15
+ // throws if host is not valid
16
+ (0, utils_1.getInfoFromTenant)(config.arguments.host, config.verbose, false);
17
+ await (0, settings_1.set)(constants_1.OPTION_HOST.longName, config.arguments.host);
18
+ }
19
+ catch (err) {
20
+ const { debug, output } = getLogger();
21
+ debug("failed to set host", err);
22
+ output(`error: invalid value '${config.arguments.host}' for argument '<host>'`);
23
+ throw new Error("failed to set host");
24
+ }
25
+ };
26
+ const show = () => async () => {
27
+ const { output } = getLogger();
28
+ const settings = await (0, settings_1.get)();
29
+ if (settings[constants_1.OPTION_HOST.longName]) {
30
+ output(settings[constants_1.OPTION_HOST.longName]);
31
+ }
32
+ else {
33
+ output("no global host set. use dwc host set <host> to set a global host");
34
+ throw new Error("no global host set");
35
+ }
36
+ };
37
+ const clean = () => async () => {
38
+ await (0, settings_1.remove)(constants_1.OPTION_HOST.longName);
39
+ };
40
+ const addCommands = async (program) => {
41
+ (0, commands_1.buildCommand)(program, {
42
+ type: "topCommand",
43
+ command: "host",
44
+ description: "configure host properties",
45
+ subCommands: [
46
+ {
47
+ type: "command",
48
+ command: "set",
49
+ description: "set global host",
50
+ args: [{ argument: "host", description: "global host" }],
51
+ handler: (0, handler_1.createNextHandler)((0, handler_1.createParseArgumentsHandler)([{ argument: "host" }]), set),
52
+ },
53
+ {
54
+ type: "command",
55
+ command: "show",
56
+ description: "show global host",
57
+ handler: show,
58
+ },
59
+ {
60
+ type: "command",
61
+ command: "clean",
62
+ description: "clean global host",
63
+ handler: clean,
64
+ },
65
+ ],
66
+ });
67
+ };
68
+ exports.addCommands = addCommands;
@@ -0,0 +1,3 @@
1
+ import { LeafCommand } from "../types";
2
+ declare const loginCommand: LeafCommand;
3
+ export default loginCommand;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const handler_1 = require("./handler");
4
+ const constants_1 = require("../constants");
5
+ const utils_1 = require("./handler/authentication/oauth/utils");
6
+ const store = () => async () => {
7
+ await (0, utils_1.storeSecrets)();
8
+ };
9
+ const loginCommand = {
10
+ type: "command",
11
+ command: "login",
12
+ description: "log in to your account using interactive OAuth authentication",
13
+ options: [],
14
+ handler: (0, handler_1.createNextHandler)((0, handler_1.createParseArgumentsHandler)(), (0, handler_1.createOptionsHandler)([constants_1.OPTION_VERBOSE, constants_1.OPTION_OPTIONS_FILE]), (0, handler_1.createOauthHandler)(), store),
15
+ };
16
+ exports.default = loginCommand;
@@ -0,0 +1,3 @@
1
+ import { LeafCommand } from "../types";
2
+ declare const logoutCommand: LeafCommand;
3
+ export default logoutCommand;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const cache_1 = require("../cache");
4
+ const constants_1 = require("../constants");
5
+ const logger_1 = require("../logger");
6
+ const handler = () => async () => {
7
+ try {
8
+ await (0, cache_1.deleteFile)(constants_1.CACHE_SECRETS_FILE);
9
+ }
10
+ catch (err) {
11
+ const { error } = (0, logger_1.get)("commands.logout");
12
+ error("failed to delete secrets file from cache", err);
13
+ }
14
+ };
15
+ const logoutCommand = {
16
+ type: "command",
17
+ command: "logout",
18
+ description: "log out from your account",
19
+ handler,
20
+ };
21
+ exports.default = logoutCommand;
@@ -0,0 +1,2 @@
1
+ import { AddCommands } from "../../types";
2
+ export declare const addCommands: AddCommands;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addCommands = void 0;
4
+ const discovery_1 = require("../../discovery");
5
+ const logger_1 = require("../../logger");
6
+ const constants_1 = require("../../constants");
7
+ const handler_1 = require("../handler");
8
+ const commands_1 = require("../../utils/commands");
9
+ const utils_1 = require("./utils");
10
+ const getLogger = () => (0, logger_1.get)("commands.openAPI");
11
+ const getCommandDescription = (document, segments, index) => {
12
+ const segment = segments
13
+ .slice(0, index + 1)
14
+ .reduce((prev, curr) => (prev !== "" ? `${prev} ${curr}` : curr), "");
15
+ return document.tags.find((t) => t.name === segment)?.description || "";
16
+ };
17
+ const addCommandToArray = (document, commands, segments, index) => {
18
+ const segment = segments[index];
19
+ let command = commands.find((c) => c.command === segment);
20
+ if (command?.type === "topCommand") {
21
+ return addCommandToArray(document, command.subCommands, segments, index + 1);
22
+ }
23
+ if (index + 1 < segments.length) {
24
+ command = {
25
+ type: "topCommand",
26
+ description: getCommandDescription(document, segments, index),
27
+ command: segment,
28
+ subCommands: [],
29
+ options: [constants_1.OPTION_HOST],
30
+ };
31
+ commands.push(command);
32
+ return addCommandToArray(document, command.subCommands, segments, index + 1);
33
+ }
34
+ // @ts-expect-error ts(2322) handler is missing - OK
35
+ command = {
36
+ type: "command",
37
+ description: getCommandDescription(document, segments, index),
38
+ command: segment,
39
+ options: [],
40
+ };
41
+ // @ts-expect-error ts(2345) handler is missing - OK
42
+ commands.push(command);
43
+ // @ts-expect-error ts(2345) handler is missing - OK
44
+ return { command, remove: () => commands.splice(commands.length - 1, 1) };
45
+ };
46
+ const setHandler = (command, method, path, parameterMappings, readPathResponseHandler, ...handler) => {
47
+ // eslint-disable-next-line
48
+ command.handler = (0, handler_1.createNextHandler)((0, handler_1.createParseArgumentsHandler)(), (0, handler_1.createMandatoryOptionsHandler)(), (0, handler_1.createAuthenticationHandler)(), ...handler, (0, handler_1.createFetchHandler)(method, path, parameterMappings, readPathResponseHandler));
49
+ };
50
+ const addCommands = async (program) => {
51
+ const { error, debug, trace } = getLogger();
52
+ try {
53
+ const doc = await (0, discovery_1.init)();
54
+ const commands = [];
55
+ for (const path of Object.keys(doc.paths)) {
56
+ const pathItem = doc.paths[path];
57
+ for (const method of Object.keys(pathItem).filter((i) => i !== "parameters")) {
58
+ const handler = [];
59
+ let remove;
60
+ try {
61
+ const parameterMappings = [];
62
+ // eslint-disable-next-line
63
+ const operation = pathItem[method];
64
+ const cmd = addCommandToArray(doc, commands, operation.operationId.split(" "), 0);
65
+ remove = cmd.remove;
66
+ const { command } = cmd;
67
+ command.description = (0, utils_1.getDescriptionForCommand)(command, operation);
68
+ (0, utils_1.handleRequestBody)(operation, handler, doc, parameterMappings, command);
69
+ (0, utils_1.handleForceOption)(operation, handler);
70
+ (0, utils_1.handleResponses)(operation, command);
71
+ (0, utils_1.handleParameters)(operation, doc, parameterMappings, command, (0, utils_1.getSchema)(pathItem.parameters || [], doc));
72
+ const readPathResponseHandler = (0, utils_1.handleReadPathHandler)(doc, operation);
73
+ setHandler(command, method, (0, utils_1.updatePath)(doc, path), parameterMappings, readPathResponseHandler, ...[
74
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
75
+ (0, handler_1.createOptionsHandler)(command.options),
76
+ ...handler,
77
+ ]);
78
+ delete command.options;
79
+ }
80
+ catch (err) {
81
+ error("cannot add command", err.stack);
82
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
83
+ remove();
84
+ }
85
+ }
86
+ }
87
+ for (const command of commands) {
88
+ trace("adding command %s", JSON.stringify(command));
89
+ try {
90
+ (0, commands_1.buildCommand)(program, command);
91
+ }
92
+ catch (err) {
93
+ error("error while adding command %s", JSON.stringify(command, null, 2), err.stack);
94
+ }
95
+ }
96
+ }
97
+ catch (err) {
98
+ debug("error while initializing discovery", err.stack);
99
+ throw err;
100
+ }
101
+ };
102
+ exports.addCommands = addCommands;
@@ -0,0 +1,19 @@
1
+ import { Command, Discovery, Handler, In, JSONReference, JSONSchema, Operation, Option, ParameterMappings, Parameters, ResponsePostProcessor } from "../../types";
2
+ type ExtendedType = {
3
+ allowEmptyValue?: boolean;
4
+ required?: boolean;
5
+ };
6
+ export declare const updatePath: (doc: Discovery, path: string) => string;
7
+ export declare const isPathParameter: (segment: string) => boolean;
8
+ export declare const writeParameter: (parameter: string, value: string) => string;
9
+ export declare const getSegments: (value: string) => Array<string>;
10
+ export declare const handleReadPathHandler: (doc: Discovery, operation: Operation) => ResponsePostProcessor;
11
+ export declare const getDescriptionForCommand: (command: Command, operation: Operation) => string;
12
+ export declare const getSchema: <T>(obj: JSONReference | T, doc: Discovery) => T;
13
+ export declare const addOptionToCommand: (option: Option, options: Array<Option>) => void;
14
+ export declare const buildOptionFromType: (doc: Discovery, parameterIn: In, name: string, type: JSONSchema & ExtendedType, parameterMappings: ParameterMappings, options: Array<Option>, description?: string) => void;
15
+ export declare const handleRequestBody: (operation: Operation, handler: Array<Handler>, doc: Discovery, parameterMappings: ParameterMappings, command: Command) => void;
16
+ export declare const handleForceOption: (operation: Operation, handler: Array<Handler>) => void;
17
+ export declare const handleResponses: (operation: Operation, command: Command) => void;
18
+ export declare const handleParameters: (operation: Operation, doc: Discovery, parameterMappings: ParameterMappings, command: Command, topLevelParameters?: Parameters) => void;
19
+ export {};
@@ -0,0 +1,334 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.handleParameters = exports.handleResponses = exports.handleForceOption = exports.handleRequestBody = exports.buildOptionFromType = exports.addOptionToCommand = exports.getSchema = exports.getDescriptionForCommand = exports.handleReadPathHandler = exports.getSegments = exports.writeParameter = exports.isPathParameter = exports.updatePath = void 0;
27
+ const lodash_1 = __importStar(require("lodash"));
28
+ const constants_1 = require("../../constants");
29
+ const logger_1 = require("../../logger");
30
+ const utils_1 = require("../../utils/utils");
31
+ const config_1 = require("../../config");
32
+ const handler_1 = require("../handler");
33
+ const getLogger = () => (0, logger_1.get)("commands.openAPI.utils");
34
+ const updatePath = (doc, path) => {
35
+ const version = (0, utils_1.parseVersion)(doc.info.version);
36
+ if (version.major < 2023) {
37
+ return `/dwaas-core${path}`;
38
+ }
39
+ return path;
40
+ };
41
+ exports.updatePath = updatePath;
42
+ const isPathParameter = (segment) => /^{.*}$/.test(segment);
43
+ exports.isPathParameter = isPathParameter;
44
+ const writeParameter = (parameter, value) => `--${(0, lodash_1.kebabCase)(parameter.slice(1, -1))} ${value}`;
45
+ exports.writeParameter = writeParameter;
46
+ const getSegments = (value) => {
47
+ const segments = value.split("/");
48
+ return segments.filter((segment) => {
49
+ const s = segment.trim();
50
+ return s !== "" && s !== "marketplace";
51
+ });
52
+ };
53
+ exports.getSegments = getSegments;
54
+ const handleParameter = (params, pathSegment, locationSegment) => {
55
+ if ((0, exports.isPathParameter)(pathSegment)) {
56
+ return params
57
+ ? `${params} ${(0, exports.writeParameter)(pathSegment, locationSegment)}`
58
+ : (0, exports.writeParameter)(pathSegment, locationSegment);
59
+ }
60
+ return params;
61
+ };
62
+ const getPathItem = (doc, operation, path) => {
63
+ const pathItem = doc.paths[path];
64
+ if (pathItem.get) {
65
+ return pathItem;
66
+ }
67
+ throw new Error(`path ${operation["x-read-path"]} does not support GET operation`);
68
+ };
69
+ const outputReadCommand = (doc, operation, response, path) => {
70
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
71
+ const locationSegments = (0, exports.getSegments)(response.headers.location);
72
+ const pathSegments = (0, exports.getSegments)(path);
73
+ let params = "";
74
+ for (let i = 0; i < pathSegments.length; i++) {
75
+ params = handleParameter(params, pathSegments[i], locationSegments[i]);
76
+ }
77
+ const pathItem = getPathItem(doc, operation, path);
78
+ const { output } = getLogger();
79
+ output(`Use ${(0, config_1.get)()[constants_1.CLI_NAME]} ${
80
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
81
+ pathItem.get.operationId} ${params} to retrieve the entity you just created`);
82
+ };
83
+ const readPathHandlerFunction = (doc, operation, path) => async (response) => {
84
+ const { debug } = getLogger();
85
+ if (!response.headers.location) {
86
+ debug("response contains no location header");
87
+ }
88
+ else {
89
+ outputReadCommand(doc, operation, response, path);
90
+ }
91
+ };
92
+ const dummyFunction = async () => {
93
+ // This is intentional
94
+ };
95
+ const handleReadPathHandler = (doc, operation) => {
96
+ const path = operation["x-read-path"];
97
+ if (path) {
98
+ return readPathHandlerFunction(doc, operation, path);
99
+ }
100
+ return dummyFunction;
101
+ };
102
+ exports.handleReadPathHandler = handleReadPathHandler;
103
+ const getDescriptionForCommand = (command, operation) => command.description || operation.description || operation.summary || "";
104
+ exports.getDescriptionForCommand = getDescriptionForCommand;
105
+ const getReferenceFromDocument = (reference, document) => {
106
+ const { trace } = getLogger();
107
+ const segments = reference.$ref.split("/");
108
+ if (segments.length < 4 || // #(1)/components(2)/(parameters|schemas|responses|...)(3)/<name>(4)
109
+ segments[0] !== "#" ||
110
+ segments[1] !== "components") {
111
+ throw new Error(`invalid reference ${reference.$ref}`);
112
+ }
113
+ const path = segments
114
+ .slice(1)
115
+ .reduce((prev, curr) => (prev !== "" ? `${prev}.${curr}` : curr), "");
116
+ trace("reading reference %s, path %s", reference.$ref, path);
117
+ return lodash_1.default.get(document, path);
118
+ };
119
+ const getSchema = (obj, doc) => {
120
+ if (obj.$ref) {
121
+ return getReferenceFromDocument(obj, doc);
122
+ }
123
+ return obj;
124
+ };
125
+ exports.getSchema = getSchema;
126
+ const getKeysFromSchema = (schema, doc, key = "", required = false) => {
127
+ const { trace } = getLogger();
128
+ trace(`retrieving keys for key ${key} from schema ${JSON.stringify(schema)}`);
129
+ if (schema.$ref) {
130
+ // eslint-disable-next-line no-param-reassign
131
+ schema = (0, exports.getSchema)(schema, doc);
132
+ }
133
+ if (schema.type === "object" && schema.properties) {
134
+ let keys = [];
135
+ Object.keys(schema.properties).forEach((property) => {
136
+ keys = keys.concat(getKeysFromSchema(schema.properties[property], doc, key ? `${key}.${property}` : property, schema.required?.includes(property)));
137
+ });
138
+ return keys;
139
+ }
140
+ return [{ key, schema, required }];
141
+ };
142
+ const flattenType = (type, doc) => {
143
+ if (type.oneOf) {
144
+ let result = [];
145
+ type.oneOf.forEach((t) => {
146
+ result = result.concat(flattenType(t, doc));
147
+ });
148
+ return result;
149
+ }
150
+ if (type.$ref) {
151
+ const schema = (0, exports.getSchema)(type, doc);
152
+ return flattenType({
153
+ ...schema,
154
+ allowEmptyValue: type.allowEmptyValue,
155
+ required: type.required,
156
+ }, doc);
157
+ }
158
+ if (type.type === "object") {
159
+ throw new Error("type: Object not supported");
160
+ }
161
+ return [type];
162
+ };
163
+ const addOptionToCommand = (option, options) => {
164
+ const { trace } = getLogger();
165
+ options.push(option);
166
+ trace("added option %s", JSON.stringify(option));
167
+ };
168
+ exports.addOptionToCommand = addOptionToCommand;
169
+ const checkTypes = (types) => {
170
+ for (const t of types) {
171
+ if (types.length > 1 && t.enum?.length === 1) {
172
+ throw new Error("constants not allowed for multiple types");
173
+ }
174
+ }
175
+ };
176
+ const initParams = (types) => {
177
+ const params = { booleanAvailable: false, choices: [] };
178
+ for (const t of types) {
179
+ if (t.type === "boolean") {
180
+ params.booleanAvailable = true;
181
+ }
182
+ else {
183
+ t.enum?.forEach((e) => params.choices.push(e.toString()));
184
+ }
185
+ params.default = t.default;
186
+ }
187
+ return params;
188
+ };
189
+ const handleOptionName = (name, params, description) => {
190
+ let optionName = lodash_1.default.kebabCase(name);
191
+ let def;
192
+ let newDescription = description;
193
+ if (params.default !== undefined) {
194
+ if (params.booleanAvailable && params.default === true) {
195
+ // see npmjs.com/package/commander#other-option-types-negatable-boolean-and-booleanvalue
196
+ optionName = `no-${optionName}`;
197
+ if (description) {
198
+ newDescription = `do not ${description}`;
199
+ }
200
+ }
201
+ else {
202
+ def = params.default.toString();
203
+ }
204
+ }
205
+ return {
206
+ optionName,
207
+ def,
208
+ description: newDescription,
209
+ };
210
+ };
211
+ const buildOption = (longName, types, params, description, def) => {
212
+ const option = {
213
+ longName,
214
+ required: !types[0].allowEmptyValue && types[0].required,
215
+ description: description || "",
216
+ default: def === "false" ? undefined : def,
217
+ args: params.booleanAvailable && types.length === 1
218
+ ? undefined
219
+ : [
220
+ {
221
+ name: longName,
222
+ optional: params.booleanAvailable && types.length > 1,
223
+ },
224
+ ],
225
+ choices: params.choices.length > 0 ? params.choices : undefined,
226
+ };
227
+ if (option.required) {
228
+ const desc = option.description ? ` (${option.description})` : "";
229
+ option.prompts = {
230
+ message: `Provide a value for option ${option.longName}${desc}:`,
231
+ type: params.choices.length > 0 ? "select" : "text",
232
+ };
233
+ }
234
+ return option;
235
+ };
236
+ const handleOption = (name, params, types, options, description) => {
237
+ const { optionName, def, description: newDescription, } = handleOptionName(name, params, description);
238
+ const option = buildOption(optionName, types, params, newDescription, def);
239
+ (0, exports.addOptionToCommand)(option, options);
240
+ };
241
+ const requiresUserInput = (name) => name !== constants_1.X_CSRF_TOKEN;
242
+ const buildOptionFromType = (doc, parameterIn, name, type, parameterMappings, options, description) => {
243
+ try {
244
+ const types = flattenType(type, doc);
245
+ checkTypes(types);
246
+ if (types[0].enum?.length === 1) {
247
+ parameterMappings.push({
248
+ in: parameterIn,
249
+ name,
250
+ source: { type: "value", value: types[0].enum[0] },
251
+ });
252
+ }
253
+ else {
254
+ const params = initParams(types);
255
+ if (requiresUserInput(name)) {
256
+ handleOption(name, params, types, options, description);
257
+ }
258
+ parameterMappings.push({
259
+ in: parameterIn,
260
+ name,
261
+ source: {
262
+ type: "option",
263
+ name: (0, lodash_1.kebabCase)(name),
264
+ dataType: params.booleanAvailable ? "boolean" : "string", // we don't care whether it's a string or number, it simply must not be boolean in this case
265
+ },
266
+ });
267
+ }
268
+ }
269
+ catch (err) {
270
+ if (!type.required) {
271
+ const { trace } = getLogger();
272
+ trace(`option ${name} silently ignored since not required`, err.stack);
273
+ }
274
+ else {
275
+ throw err;
276
+ }
277
+ }
278
+ };
279
+ exports.buildOptionFromType = buildOptionFromType;
280
+ const handleRequestBody = (operation, handler, doc, parameterMappings, command) => {
281
+ if (operation["x-requestbody-fileonly"]) {
282
+ handler.push((0, handler_1.createInputHandler)());
283
+ }
284
+ else if (operation.requestBody) {
285
+ const schema = (0, exports.getSchema)(Object.values(operation.requestBody.content)[0].schema, doc);
286
+ const keys = getKeysFromSchema(schema, doc);
287
+ keys.forEach((key) => {
288
+ if (key.schema.oneOf) {
289
+ throw new Error("invalid request body parameter resolution, oneOf not supported");
290
+ }
291
+ (0, exports.buildOptionFromType)(doc, "body", key.key, {
292
+ ...key.schema,
293
+ required: key.required,
294
+ }, parameterMappings,
295
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
296
+ command.options, key.schema.description);
297
+ });
298
+ }
299
+ };
300
+ exports.handleRequestBody = handleRequestBody;
301
+ const handleForceOption = (operation, handler) => {
302
+ if (operation["x-user-to-confirm"]) {
303
+ handler.push((0, handler_1.createForceHandler)(operation["x-user-to-confirm"]));
304
+ }
305
+ };
306
+ exports.handleForceOption = handleForceOption;
307
+ const handleResponses = (operation, command) => {
308
+ if (operation.responses?.[200]) {
309
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
310
+ (0, exports.addOptionToCommand)(constants_1.OPTION_OUTPUT, command.options);
311
+ }
312
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
313
+ (0, exports.addOptionToCommand)(constants_1.OPTION_PRETTY, command.options);
314
+ };
315
+ exports.handleResponses = handleResponses;
316
+ const handleParameters = (operation, doc, parameterMappings, command, topLevelParameters = []) => {
317
+ const { error } = getLogger();
318
+ (operation.parameters || []).concat(topLevelParameters).forEach((p) => {
319
+ try {
320
+ const parameter = (0, exports.getSchema)(p, doc);
321
+ (0, exports.buildOptionFromType)(doc, parameter.in, parameter.name, {
322
+ ...parameter.schema,
323
+ allowEmptyValue: parameter.allowEmptyValue,
324
+ required: parameter.required,
325
+ }, parameterMappings,
326
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
327
+ command.options, parameter.description);
328
+ }
329
+ catch (err) {
330
+ error("cannot add option", err.stack);
331
+ }
332
+ });
333
+ };
334
+ exports.handleParameters = handleParameters;
@@ -0,0 +1,2 @@
1
+ import { AddCommands } from "../types";
2
+ export declare const addCommands: AddCommands;