@halospv3/hce.shared-config 3.0.0-develop.2 → 3.0.0-develop.21

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 (188) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/dotnet/.github/workflows/_unit_test.yml +0 -3
  3. package/dotnet/.github/workflows/dotnet-release.yml +0 -3
  4. package/dotnet/.github/workflows/sample-dotnet-build.yml +0 -3
  5. package/dotnet/PublishAll.targets +3 -2
  6. package/dotnet/ZipPublishDir.targets +24 -29
  7. package/mjs/CaseInsensitiveMap.d.ts +12 -0
  8. package/mjs/CaseInsensitiveMap.d.ts.map +1 -0
  9. package/mjs/CaseInsensitiveMap.mjs +33 -0
  10. package/mjs/CaseInsensitiveMap.mjs.map +1 -0
  11. package/mjs/commitlintConfig.d.ts +12 -0
  12. package/mjs/commitlintConfig.d.ts.map +1 -0
  13. package/mjs/commitlintConfig.mjs +13 -0
  14. package/mjs/commitlintConfig.mjs.map +1 -0
  15. package/mjs/debug.d.ts +6 -0
  16. package/mjs/debug.d.ts.map +1 -0
  17. package/mjs/debug.mjs +9 -0
  18. package/mjs/debug.mjs.map +1 -0
  19. package/mjs/dotnet/GithubNugetRegistryInfo.d.ts +38 -0
  20. package/mjs/dotnet/GithubNugetRegistryInfo.d.ts.map +1 -0
  21. package/mjs/dotnet/GithubNugetRegistryInfo.mjs +43 -0
  22. package/mjs/dotnet/GithubNugetRegistryInfo.mjs.map +1 -0
  23. package/mjs/dotnet/GitlabNugetRegistryInfo.d.ts +62 -0
  24. package/mjs/dotnet/GitlabNugetRegistryInfo.d.ts.map +1 -0
  25. package/mjs/dotnet/GitlabNugetRegistryInfo.mjs +99 -0
  26. package/mjs/dotnet/GitlabNugetRegistryInfo.mjs.map +1 -0
  27. package/mjs/dotnet/IsNextVersionAlreadyPublished.cli.d.ts +2 -0
  28. package/mjs/dotnet/IsNextVersionAlreadyPublished.cli.d.ts.map +1 -0
  29. package/mjs/dotnet/IsNextVersionAlreadyPublished.cli.mjs +41 -0
  30. package/mjs/dotnet/IsNextVersionAlreadyPublished.cli.mjs.map +1 -0
  31. package/mjs/dotnet/MSBuildProject.d.ts +256 -0
  32. package/mjs/dotnet/MSBuildProject.d.ts.map +1 -0
  33. package/mjs/dotnet/MSBuildProject.mjs +447 -0
  34. package/mjs/dotnet/MSBuildProject.mjs.map +1 -0
  35. package/mjs/dotnet/MSBuildProjectProperties.d.ts +170 -0
  36. package/mjs/dotnet/MSBuildProjectProperties.d.ts.map +1 -0
  37. package/mjs/dotnet/MSBuildProjectProperties.mjs +260 -0
  38. package/mjs/dotnet/MSBuildProjectProperties.mjs.map +1 -0
  39. package/mjs/dotnet/NugetProjectProperties.d.ts +379 -0
  40. package/mjs/dotnet/NugetProjectProperties.d.ts.map +1 -0
  41. package/mjs/dotnet/NugetProjectProperties.mjs +577 -0
  42. package/mjs/dotnet/NugetProjectProperties.mjs.map +1 -0
  43. package/mjs/dotnet/NugetRegistryInfo.d.ts +384 -0
  44. package/mjs/dotnet/NugetRegistryInfo.d.ts.map +1 -0
  45. package/mjs/dotnet/NugetRegistryInfo.mjs +752 -0
  46. package/mjs/dotnet/NugetRegistryInfo.mjs.map +1 -0
  47. package/mjs/dotnet/helpers.d.ts +63 -0
  48. package/mjs/dotnet/helpers.d.ts.map +1 -0
  49. package/mjs/dotnet/helpers.mjs +354 -0
  50. package/mjs/dotnet/helpers.mjs.map +1 -0
  51. package/mjs/dotnet/index.d.ts +9 -0
  52. package/mjs/dotnet/index.d.ts.map +1 -0
  53. package/mjs/dotnet/index.mjs +9 -0
  54. package/mjs/dotnet/index.mjs.map +1 -0
  55. package/mjs/dotnet.d.ts +2 -0
  56. package/mjs/dotnet.d.ts.map +1 -0
  57. package/mjs/dotnet.mjs +9 -0
  58. package/mjs/dotnet.mjs.map +1 -0
  59. package/mjs/eslintConfig.d.ts +4 -0
  60. package/mjs/eslintConfig.d.ts.map +1 -0
  61. package/mjs/eslintConfig.mjs +98 -0
  62. package/mjs/eslintConfig.mjs.map +1 -0
  63. package/mjs/index.d.ts +3 -0
  64. package/mjs/index.d.ts.map +1 -0
  65. package/mjs/index.mjs +4 -0
  66. package/mjs/index.mjs.map +1 -0
  67. package/mjs/insertPlugins.d.ts +18 -0
  68. package/mjs/insertPlugins.d.ts.map +1 -0
  69. package/mjs/insertPlugins.mjs +73 -0
  70. package/mjs/insertPlugins.mjs.map +1 -0
  71. package/mjs/semantic-release__commit-analyzer.d.mjs +2 -0
  72. package/mjs/semantic-release__commit-analyzer.d.mjs.map +1 -0
  73. package/mjs/semantic-release__exec.d.mjs +2 -0
  74. package/mjs/semantic-release__exec.d.mjs.map +1 -0
  75. package/mjs/semantic-release__git.d.mjs +2 -0
  76. package/mjs/semantic-release__git.d.mjs.map +1 -0
  77. package/mjs/semantic-release__github.d.mjs +2 -0
  78. package/mjs/semantic-release__github.d.mjs.map +1 -0
  79. package/mjs/semanticReleaseConfig.d.ts +97 -0
  80. package/mjs/semanticReleaseConfig.d.ts.map +1 -0
  81. package/mjs/semanticReleaseConfig.mjs +63 -0
  82. package/mjs/semanticReleaseConfig.mjs.map +1 -0
  83. package/mjs/semanticReleaseConfigDotnet.d.ts +109 -0
  84. package/mjs/semanticReleaseConfigDotnet.d.ts.map +1 -0
  85. package/mjs/semanticReleaseConfigDotnet.mjs +268 -0
  86. package/mjs/semanticReleaseConfigDotnet.mjs.map +1 -0
  87. package/mjs/setupGitPluginSpec.d.ts +22 -0
  88. package/mjs/setupGitPluginSpec.d.ts.map +1 -0
  89. package/mjs/setupGitPluginSpec.mjs +144 -0
  90. package/mjs/setupGitPluginSpec.mjs.map +1 -0
  91. package/mjs/utils/Exact.d.ts +20 -0
  92. package/mjs/utils/Exact.d.ts.map +1 -0
  93. package/mjs/utils/Exact.mjs +75 -0
  94. package/mjs/utils/Exact.mjs.map +1 -0
  95. package/mjs/utils/GracefulRecursion.d.mjs +2 -0
  96. package/mjs/utils/GracefulRecursion.d.mjs.map +1 -0
  97. package/mjs/utils/env.d.ts +24 -0
  98. package/mjs/utils/env.d.ts.map +1 -0
  99. package/mjs/utils/env.mjs +39 -0
  100. package/mjs/utils/env.mjs.map +1 -0
  101. package/mjs/utils/execAsync.d.ts +37 -0
  102. package/mjs/utils/execAsync.d.ts.map +1 -0
  103. package/mjs/utils/execAsync.mjs +59 -0
  104. package/mjs/utils/execAsync.mjs.map +1 -0
  105. package/mjs/utils/miscTypes.d.ts +13 -0
  106. package/mjs/utils/miscTypes.d.ts.map +1 -0
  107. package/mjs/utils/miscTypes.mjs +10 -0
  108. package/mjs/utils/miscTypes.mjs.map +1 -0
  109. package/mjs/utils/reflection/FunctionLike.d.mjs +2 -0
  110. package/mjs/utils/reflection/FunctionLike.d.mjs.map +1 -0
  111. package/mjs/utils/reflection/GetterDescriptor.d.mjs +2 -0
  112. package/mjs/utils/reflection/GetterDescriptor.d.mjs.map +1 -0
  113. package/mjs/utils/reflection/InstancePropertyDescriptorMap.d.mjs +2 -0
  114. package/mjs/utils/reflection/InstancePropertyDescriptorMap.d.mjs.map +1 -0
  115. package/mjs/utils/reflection/InstanceTypeOrSelfPropertyDescriptorMap.d.mjs +2 -0
  116. package/mjs/utils/reflection/InstanceTypeOrSelfPropertyDescriptorMap.d.mjs.map +1 -0
  117. package/mjs/utils/reflection/OwnGetterDescriptorMap.d.mjs +2 -0
  118. package/mjs/utils/reflection/OwnGetterDescriptorMap.d.mjs.map +1 -0
  119. package/mjs/utils/reflection/OwnKeyOf.d.mjs +2 -0
  120. package/mjs/utils/reflection/OwnKeyOf.d.mjs.map +1 -0
  121. package/mjs/utils/reflection/OwnPropertyDescriptorMap.d.mjs +2 -0
  122. package/mjs/utils/reflection/OwnPropertyDescriptorMap.d.mjs.map +1 -0
  123. package/mjs/utils/reflection/PropertyDescriptorMap.d.mjs +2 -0
  124. package/mjs/utils/reflection/PropertyDescriptorMap.d.mjs.map +1 -0
  125. package/mjs/utils/reflection/filterForGetters.d.ts +7 -0
  126. package/mjs/utils/reflection/filterForGetters.d.ts.map +1 -0
  127. package/mjs/utils/reflection/filterForGetters.mjs +27 -0
  128. package/mjs/utils/reflection/filterForGetters.mjs.map +1 -0
  129. package/mjs/utils/reflection/getOwnPropertyDescriptors.d.ts +22 -0
  130. package/mjs/utils/reflection/getOwnPropertyDescriptors.d.ts.map +1 -0
  131. package/mjs/utils/reflection/getOwnPropertyDescriptors.mjs +34 -0
  132. package/mjs/utils/reflection/getOwnPropertyDescriptors.mjs.map +1 -0
  133. package/mjs/utils/reflection/getOwnPropertyDescriptorsRecursively.d.ts +56 -0
  134. package/mjs/utils/reflection/getOwnPropertyDescriptorsRecursively.d.ts.map +1 -0
  135. package/mjs/utils/reflection/getOwnPropertyDescriptorsRecursively.mjs +72 -0
  136. package/mjs/utils/reflection/getOwnPropertyDescriptorsRecursively.mjs.map +1 -0
  137. package/mjs/utils/reflection/getPrototypeChainOf.d.ts +16 -0
  138. package/mjs/utils/reflection/getPrototypeChainOf.d.ts.map +1 -0
  139. package/mjs/utils/reflection/getPrototypeChainOf.mjs +55 -0
  140. package/mjs/utils/reflection/getPrototypeChainOf.mjs.map +1 -0
  141. package/mjs/utils/reflection/getPrototypeOf.d.ts +8 -0
  142. package/mjs/utils/reflection/getPrototypeOf.d.ts.map +1 -0
  143. package/mjs/utils/reflection/getPrototypeOf.mjs +10 -0
  144. package/mjs/utils/reflection/getPrototypeOf.mjs.map +1 -0
  145. package/mjs/utils/reflection/inheritance.d.ts +180 -0
  146. package/mjs/utils/reflection/inheritance.d.ts.map +1 -0
  147. package/mjs/utils/reflection/inheritance.mjs +148 -0
  148. package/mjs/utils/reflection/inheritance.mjs.map +1 -0
  149. package/mjs/utils/reflection/isConstructor.d.ts +17 -0
  150. package/mjs/utils/reflection/isConstructor.d.ts.map +1 -0
  151. package/mjs/utils/reflection/isConstructor.mjs +63 -0
  152. package/mjs/utils/reflection/isConstructor.mjs.map +1 -0
  153. package/mjs/utils/reflection/isGetterDescriptor.d.ts +9 -0
  154. package/mjs/utils/reflection/isGetterDescriptor.d.ts.map +1 -0
  155. package/mjs/utils/reflection/isGetterDescriptor.mjs +12 -0
  156. package/mjs/utils/reflection/isGetterDescriptor.mjs.map +1 -0
  157. package/mjs/utils/reflection/listOwnGetters.d.ts +26 -0
  158. package/mjs/utils/reflection/listOwnGetters.d.ts.map +1 -0
  159. package/mjs/utils/reflection/listOwnGetters.mjs +39 -0
  160. package/mjs/utils/reflection/listOwnGetters.mjs.map +1 -0
  161. package/mjs/utils/reflection.d.ts +18 -0
  162. package/mjs/utils/reflection.d.ts.map +1 -0
  163. package/mjs/utils/reflection.mjs +10 -0
  164. package/mjs/utils/reflection.mjs.map +1 -0
  165. package/package.json +17 -17
  166. package/src/debug.ts +5 -4
  167. package/src/dotnet/GithubNugetRegistryInfo.ts +17 -9
  168. package/src/dotnet/GitlabNugetRegistryInfo.ts +19 -5
  169. package/src/dotnet/IsNextVersionAlreadyPublished.cli.ts +53 -36
  170. package/src/dotnet/MSBuildProject.ts +150 -5
  171. package/src/dotnet/MSBuildProjectProperties.ts +2 -1
  172. package/src/dotnet/NugetProjectProperties.ts +3 -2
  173. package/src/dotnet/NugetRegistryInfo.ts +94 -8
  174. package/src/dotnet/helpers.ts +87 -53
  175. package/src/dotnet/index.ts +8 -0
  176. package/src/dotnet.ts +1 -0
  177. package/src/insertPlugins.ts +116 -0
  178. package/src/semantic-release__exec.d.ts +1 -1
  179. package/src/semanticReleaseConfig.ts +8 -3
  180. package/src/semanticReleaseConfigDotnet.ts +90 -88
  181. package/src/setupGitPluginSpec.ts +4 -1
  182. package/src/tsconfig.json +1 -1
  183. package/src/utils/execAsync.ts +13 -1
  184. package/src/utils/miscTypes.ts +4 -3
  185. package/src/utils/reflection/inheritance.ts +1 -1
  186. package/tsconfig.base.json +54 -0
  187. package/tsconfig.json +22 -0
  188. package/tsconfig.mjs.json +8 -0
@@ -0,0 +1,752 @@
1
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
4
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
5
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
6
+ import { config } from '@dotenvx/dotenvx';
7
+ import { type } from 'arktype';
8
+ import { detectFile, detectFileSync } from 'chardet';
9
+ import { ok } from 'node:assert/strict';
10
+ import { existsSync, writeFileSync } from 'node:fs';
11
+ import { writeFile } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import node_path from 'node:path';
14
+ import { env, cwd } from 'node:process';
15
+ import { setTimeout } from 'node:timers/promises';
16
+ import { isNativeError } from 'node:util/types';
17
+ import sanitizeFileName from 'sanitize-filename';
18
+ import { getEnvVarValue } from '../utils/env.mjs';
19
+ import { execAsync } from '../utils/execAsync.mjs';
20
+ import { MSBuildProject, catchCsc2012, MSBuildEvaluationOutput } from './MSBuildProject.mjs';
21
+
22
+ /* JSDoc Types */
23
+ /* eslint-disable @typescript-eslint/no-unused-vars */
24
+
25
+ const tmpDirNamespace = node_path.join(tmpdir(), 'HCE.Shared', '.NET', 'Dummies');
26
+ const defaultNugetSource = 'https://api.nuget.org/v3/index.json';
27
+ const key_OutputPackItems = '_OutputPackItems';
28
+ /**
29
+ * Read the contents of $GITHUB_OUTPUT (if its value is a file path) or $TEMP/GITHUB_OUTPUT.
30
+ * If the file doesn't exist, it is created.
31
+ * @returns If successful, a promised object with a parsed key.
32
+ */
33
+ async function getGithubOutput() {
34
+ if (env['GITHUB_OUTPUT'] === undefined || !existsSync(env['GITHUB_OUTPUT'])) {
35
+ const githubOutputPath = node_path.join(tmpdir(), 'GITHUB_OUTPUT');
36
+ if (!existsSync(githubOutputPath)) await writeFile(githubOutputPath, '');
37
+ env['GITHUB_OUTPUT'] = githubOutputPath;
38
+ }
39
+ const encoding = await detectFile(env['GITHUB_OUTPUT']);
40
+ const envOutput = config({
41
+ path: env['GITHUB_OUTPUT'],
42
+ override: true,
43
+ encoding: encoding ?? undefined,
44
+ processEnv: {}
45
+ });
46
+ if (isNativeError(envOutput.error)) throw envOutput.error;
47
+ return envOutput.parsed;
48
+ }
49
+
50
+ /**
51
+ * Read the contents of $GITHUB_OUTPUT (if its value is a file path) or $TEMP/GITHUB_OUTPUT.
52
+ * If the file doesn't exist, it is created.
53
+ * @returns An object with a parsed key if successful.
54
+ */
55
+ function getGithubOutputSync() {
56
+ if (env['GITHUB_OUTPUT'] === undefined || !existsSync(env['GITHUB_OUTPUT'])) {
57
+ const githubOutputPath = node_path.join(tmpdir(), 'GITHUB_OUTPUT');
58
+ if (!existsSync(githubOutputPath)) writeFileSync(githubOutputPath, '');
59
+ env['GITHUB_OUTPUT'] = githubOutputPath;
60
+ }
61
+ const encoding = detectFileSync(env['GITHUB_OUTPUT']);
62
+ const envOutput = config({
63
+ path: env['GITHUB_OUTPUT'],
64
+ override: true,
65
+ encoding: encoding ?? undefined,
66
+ processEnv: {}
67
+ });
68
+ if ('error' in envOutput) throw envOutput.error;
69
+ return envOutput.parsed;
70
+ }
71
+ /**
72
+ * Get HCE.Shared's temporary directory for .NET projects' dummy packages.
73
+ * @param project The MSBuild project whose PackageId will be used to create a
74
+ * directory for its dummy packages.
75
+ * @returns a platform-specific path like
76
+ * `${tmpdir()}/HCE.Shared/.NET/Dummies/${project.Properties.PackageId}` if
77
+ * {@link project} is defined. Else `${tmpdir()}/HCE.Shared/.NET/Dummies`
78
+ */
79
+ function getDummiesDir(project) {
80
+ switch (true) {
81
+ case project === undefined:
82
+ {
83
+ return node_path.join(tmpDirNamespace, node_path.sep);
84
+ }
85
+ case project instanceof MSBuildProject:
86
+ {
87
+ return node_path.join(tmpDirNamespace, project.Properties.PackageId, node_path.sep);
88
+ }
89
+ default:
90
+ {
91
+ throw new Error('The type of argument `project` must be `undefined` or `MSBuildProject`.');
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Get the environment variables as key-value pairs.
98
+ * @param tokenEnvVars The name of the environment variables whose values are
99
+ * NuGet API keys.
100
+ * @returns an array of key-value pairs of the given environment variables and
101
+ * their values, filtered to only those whose values are not undefined.
102
+ * @throws {Error} when none of the provided environment variables are defined.
103
+ */
104
+ function _GetTokenEnvVariables(tokenEnvVars) {
105
+ const definedTokens = Object.freeze(tokenEnvVars.map(key => [key, getEnvVarValue(key)]).filter(envVarTuple => envVarTuple[1] !== undefined));
106
+ if (definedTokens.length > 0) return definedTokens;
107
+ return undefined;
108
+ }
109
+ class NugetRegistryInfo {
110
+ _canPushPackagesToSource = undefined;
111
+ _project;
112
+ _resolvedEnvVariable;
113
+ _source;
114
+ static DefaultTokenEnvVars = Object.freeze(['NUGET_TOKEN']);
115
+
116
+ /**
117
+ * Convert a URL string to a filesystem folder name.
118
+ *
119
+ * Intended usage: modify the output path of `dotnet pack` based on the NuGet
120
+ * Source the package should be pushed to. This is extra work is usually
121
+ * unnecessary and you'd typically push the same file to multiple sources.
122
+ * This is for the edge-case scenario of creating multiple nupkgs and signing
123
+ * each one with a different certificate corresponding to a given NuGet
124
+ * Source. This is only useful if the Sources have different certificates
125
+ * registered for a given package/user/organization.
126
+ * @param source The URL of the NuGet Source
127
+ * @returns A string suitable for a local filesystem folder name, formatted as
128
+ * `${hostname}_${pathname.replace('/', '_')}`.
129
+ */
130
+ static GetDirNameForSource(source) {
131
+ return sanitizeFileName(source.replaceAll(/\/index.json$/g, ''), {
132
+ replacement: '_'
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Creates an instance of NugetRegistryInfo.\
138
+ * This class enables the ability to push a given {@link project}'s
139
+ * package(s) to the {@link source} of a given NuGet Source's API endpoint with
140
+ * a user-defined API key. This API key, herein referred to as a "token", is
141
+ * derived from the {@link tokenEnvVars} array. This array is iterated through
142
+ * until one of the items is discovered to be an existing environment variable
143
+ * (or is defined in a file named '.env' in the current working directory for
144
+ * LOCAL TESTING ONLY! Do NOT `git add` your private keys!).
145
+ * \
146
+ * WARNING:
147
+ * - The token value is stored privately within this class, but it is plain text.
148
+ * - This private key may be copied to command line strings stored in Semantic
149
+ * Release's config object for later use by `@semantic-release/exec`.
150
+ * - Other EcmaScript modules can access the environment variable(s) and steal
151
+ * your key. Be aware of malicious dependencies!
152
+ * @param opts The input type of {@link NRIOpts.from}
153
+ * @param opts.project The project whose package(s) will be
154
+ * pushed.\
155
+ * - Its {@link NugetProjectProperties#PackageId} will be read.\
156
+ * - Its {@link NugetProjectProperties#PackageVersion} will be overridden via CLI args when creating a dummy package. The real package's
157
+ * `PackageVersion` will *not* be overridden.
158
+ * @param [opts.tokenEnvVars] The environment variables
159
+ * whose values are tokens with permission to push a package to the NuGet
160
+ * package registry. The array is iterated through until one token is found.
161
+ * If none of the environment variables are defined, this constructor will
162
+ * throw an {@link Error}.
163
+ * @param [opts.source] A NuGet package registry's API endpoint URL or name. Default: 'https://api.nuget.org/v3/index.json'
164
+ */
165
+ constructor(opts) {
166
+ // note: you can reassign `opts` only when typeof `inferOut` is assignable
167
+ // to typeof `inferIn`.
168
+ const validOpts = NRIOpts.from(opts);
169
+ this._project = validOpts.project;
170
+ /**
171
+ * May throw! Assign key of the first key-value pair to
172
+ * {@link resolvedEnvVariable}
173
+ */
174
+ const tokenVars = _GetTokenEnvVariables(validOpts.tokenEnvVars);
175
+ if (tokenVars) this._resolvedEnvVariable = tokenVars[0][0];
176
+ this._source = validOpts.source;
177
+ }
178
+ get project() {
179
+ return this._project;
180
+ }
181
+
182
+ /**
183
+ * This is not useful without it being executed as part of a Semantic Release
184
+ * plugin. Deferring this to @semantic-release/exec's prepareCmd is possible,
185
+ * but impractical. You'd need to configure prepareCmd to invoke something
186
+ * like `node customScriptFile.mjs`. It's not worth the hassle.
187
+ * @returns `true` if the token can be used to push nupkg to the given Nuget registry
188
+ * @throws {TypeError | Error | import('../utils/execAsync.js').ChildProcessSpawnException }
189
+ * - {@link Error} | {@link module:utils/execAsync:ChildProcessSpawnException ChildProcessSpawnException}
190
+ * - The token is invalid, of the wrong token type, or lacks permission to push packages
191
+ * - The URL does not exist or a connection could not be established
192
+ * - The command line string is malformed.
193
+ * @deprecated Call during the `verifyConditions` step of Semantic Release! Additionally, {@link GetIsNextVersionAlreadyPublishedCommand}'s return value should be assigned to `prepareCmd` to prevent package version collision errors.
194
+ */
195
+ get canPushPackagesToSource() {
196
+ if (this._canPushPackagesToSource !== undefined) return this._canPushPackagesToSource;
197
+ let tokenValue;
198
+ if (this.resolvedEnvVariable !== undefined) tokenValue = NRI._GetTokenValue(this.resolvedEnvVariable);
199
+ if (tokenValue?.startsWith('github_pat_')) {
200
+ const errMsg = `The value of the token in 'resolvedEnvVariable' ${String(this.resolvedEnvVariable)} begins with 'github_pat_', indicating it's a Fine-Grained token. At the time of writing, GitHub Fine-Grained tokens cannot push packages. If you believe this is statement is outdated, report the issue at https://github.com/halospv3/hce.shared/issues/new. For more information, see https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry.`;
201
+ const err = new Error(errMsg);
202
+ return this._canPushPackagesToSource = Promise.reject(err);
203
+ }
204
+ return this._canPushPackagesToSource = this.PackDummyPackage({}).then(async () => await this._PushDummyPackages({
205
+ apiKey: tokenValue
206
+ })).then(execAsyncReturn => {
207
+ ok(execAsyncReturn);
208
+ return true;
209
+ });
210
+ }
211
+
212
+ /**
213
+ * The first environment variable found to have a defined value. Set by
214
+ * {@link _GetTokenEnvVariables} in the constructor.
215
+ * @returns The first environment variable found to have a defined value.
216
+ */
217
+ get resolvedEnvVariable() {
218
+ return this._resolvedEnvVariable;
219
+ }
220
+ get source() {
221
+ return this._source;
222
+ }
223
+
224
+ /**
225
+ * Get the API token from {@link NugetRegistryInfo#resolvedEnvVariable}
226
+ * @param resolvedEnvVariable The name of the environment variable(s) whose
227
+ * value is a NuGet API key. Typically, the value of
228
+ * {@link NugetRegistryInfo#resolvedEnvVariable}.
229
+ * @returns The value of the first defined environment variable.
230
+ * @throws {Error} when none of the provided environment variables are defined.
231
+ */
232
+ static _GetTokenValue(resolvedEnvVariable) {
233
+ type.string.assert(resolvedEnvVariable);
234
+ const tokenValue = getEnvVarValue(resolvedEnvVariable);
235
+ if (tokenValue === undefined) {
236
+ throw new Error(`\
237
+ The environment variable ${resolvedEnvVariable} was specified \
238
+ as the source of the token to push a NuGet package, \
239
+ but the environment variable is empty or undefined.`);
240
+ }
241
+ return tokenValue;
242
+ }
243
+
244
+ // #region Pack
245
+
246
+ /**
247
+ * The type for options and arguments of `dotnet pack`. See https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-pack.
248
+ *
249
+ * {@link NRI.PackPackagesOptionsType.t.propertyOverrides `propertyOverrides`}
250
+ * is a wrapper for MSBuild's `-property:<n>=<v>` properties override arg.
251
+ */
252
+ static PackPackagesOptionsType = Object.freeze(type({
253
+ /**
254
+ * a custom arg for handling MSBuild's `-property:<n>=<v>` argument for overriding MSBuild properties.
255
+ */
256
+ 'propertyOverrides?': type('Record<string,string>'),
257
+ 'artifactsPath?': 'string',
258
+ 'configuration?': '"Release" | "Debug"',
259
+ 'disableBuildServers?': 'boolean',
260
+ 'force?': 'boolean',
261
+ 'includeSource?': 'boolean',
262
+ 'includeSymbols?': 'boolean',
263
+ 'interactive?': 'boolean',
264
+ 'noBuild?': 'boolean',
265
+ 'noLogo?': 'boolean',
266
+ 'noRestore?': 'boolean',
267
+ 'output?': 'string',
268
+ 'runtime?': 'string',
269
+ 'serviceable?': 'boolean',
270
+ 'terminalLogger?': '"auto" | "on" | "off"',
271
+ 'useCurrentRuntime?': 'boolean',
272
+ 'verbosity?': '"quiet" | "minimal" | "normal" | "detailed" | "diagnostic"',
273
+ 'versionSuffix?': 'string',
274
+ /**
275
+ * MSBuild evaluation option. Added to get the output Nupkgs' file paths.
276
+ * @todo consider adding -GetProperty, -GetTarget
277
+ */
278
+ '-GetItem?': type.string.array().readonly().or('string[]')
279
+ }));
280
+ static PackDummyPackagesOptionsType = this.PackPackagesOptionsType.omit('output');
281
+
282
+ /**
283
+ * Get a `dotnet pack` command line string, outputting the package(s) to a
284
+ * path determined by this method's parameters.
285
+ * When pushing the package(s), you only need to supply the main .nupkg's path
286
+ * or its directory to the dotnet CLI—by default, it will also push the
287
+ * symbols package, if present.
288
+ * @param opts Options passed to
289
+ * `dotnet pack`, excluding the required `<PROJECT | SOLUTION>` argument. The
290
+ * {@link PackPackagesOptionsType.t.output} path is modified according to the
291
+ * {@link usePerSourceSubfolder} and {@link usePerPackageIdSubfolder}
292
+ * arguments.
293
+ * @param usePerSourceSubfolder If true, the path of the package output will
294
+ * include a subfolder named after the NuGet Source.
295
+ * @param usePerPackageIdSubfolder If true, the path of the package output
296
+ * will include a subfolder named after the NuGet package's ID.
297
+ * @returns `dotnet pack "${this.project.Properties.MSBuildProjectFullPath}"
298
+ * -o "${outDir}"` where outDir may be `${cwd()}/publish/${NugetRegistryInfo.GetNameForURL(this.source)}/${this._project.Properties.PackageId}`
299
+ */
300
+ GetPackCommand(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
301
+ const validOpts = NRI.PackPackagesOptionsType.from(opts);
302
+ type.boolean.assert(usePerSourceSubfolder);
303
+ type.boolean.assert(usePerPackageIdSubfolder);
304
+ validOpts.output ??= node_path.join(cwd(), 'publish');
305
+ if (usePerSourceSubfolder) validOpts.output = node_path.join(validOpts.output, NugetRegistryInfo.GetDirNameForSource(this.source), node_path.sep);
306
+ if (usePerPackageIdSubfolder) validOpts.output = node_path.join(validOpts.output, this._project.Properties.PackageId, node_path.sep);
307
+ const packCmdArr = ['dotnet', 'pack', `"${this._project.Properties.MSBuildProjectFullPath}"`];
308
+ if (validOpts.artifactsPath !== undefined) packCmdArr.push('--artifactsPath', `"${validOpts.artifactsPath}"`);
309
+ if (validOpts.configuration !== undefined) packCmdArr.push('--configuration', validOpts.configuration);
310
+ if (validOpts.disableBuildServers === true) packCmdArr.push('--disable-build-servers');
311
+ if (validOpts.force === true) packCmdArr.push('--force');
312
+ if (validOpts.includeSource === true) packCmdArr.push('--include-source');
313
+ if (validOpts.includeSymbols === true) packCmdArr.push('--include-symbols');
314
+ if (validOpts.interactive === true) packCmdArr.push('--interactive');
315
+ if (validOpts.noBuild === true) packCmdArr.push('--no-build');
316
+ if (validOpts.noLogo === true) packCmdArr.push('--nologo');
317
+ if (validOpts.noRestore === true) packCmdArr.push('--no-restore');
318
+ if (validOpts.runtime !== undefined) packCmdArr.push('--runtime', validOpts.runtime);
319
+ if (validOpts.serviceable === true) packCmdArr.push('--serviceable');
320
+ if (validOpts.terminalLogger !== undefined) packCmdArr.push('--tl', validOpts.terminalLogger);
321
+ if (validOpts.useCurrentRuntime === true) packCmdArr.push('--use-current-runtime');
322
+ if (validOpts.verbosity !== undefined) packCmdArr.push('--verbosity', validOpts.verbosity);
323
+ if (validOpts.versionSuffix !== undefined) packCmdArr.push('--version-suffix', validOpts.versionSuffix);
324
+ /**
325
+ * Haphazard. I need to override the Version and I'm not considering side
326
+ * effects of arbitrary overrides.
327
+ */
328
+ if (validOpts.propertyOverrides) {
329
+ /** convert propertyOverrides record to "-p:n0=v0;n1=v1;n2=v2" et cetera */
330
+ const assignments = '-p:' + Object.entries(validOpts.propertyOverrides).map(v => `${v[0]}=${v[1]}`).join(';');
331
+ packCmdArr.push(`"${assignments}"`);
332
+ }
333
+ if (validOpts['-GetItem'] && validOpts['-GetItem'].length > 0) {
334
+ // -GetItem:_OutputPackItems,MyCustomItem
335
+ packCmdArr.push(`-GetItem:${validOpts['-GetItem'].join(',')}`);
336
+ }
337
+ // MSBuild parses everything after -o as the path.
338
+ packCmdArr.push('-o', `"${validOpts.output}"`);
339
+ return packCmdArr.join(' ');
340
+ }
341
+
342
+ /**
343
+ * !Not ready for use! Remove private modifier and commit as `feat(dotnet)` when ready for release!
344
+ * Blocking Issue: convert all dotnet-related functionality to a Semantic Release plugin!
345
+ * The current {@link SemanticReleaseConfigDotnet} leverages
346
+ * `@semantic-release/exec` to invoke dotnet commands. This is fine for
347
+ * relatively short command lines, but chaining commands with ' && ' results
348
+ * in quickly-growing complexity.
349
+ * NuGet packages should be created during the `prepare` step, but complex
350
+ * configuration of `dotnet pack` via command lines intended to be invoked by
351
+ * `@semantic-release/exec` is impractical.
352
+ * @param opts `dotnet pack` options. See `dotnet pack -h`,
353
+ * https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-pack, and
354
+ * {@link PackPackagesOptionsType}.
355
+ * {@link opts['-GetItem']} will _always_ have '_OutputPackItems'.
356
+ * @param [usePerSourceSubfolder] If `true`, modify the output path to
357
+ * include a subfolder bearing a path-safe encoding of the NuGet Source that
358
+ * will receive the nupkg.
359
+ * @param [usePerPackageIdSubfolder] If `true`, modify the output path
360
+ * to include a subfolder named after the the PackageId.
361
+ * @returns a string[] containing the full file paths of all new packages i.e.
362
+ * .nupkg, .symbols.nupkg, .snupkg
363
+ */
364
+ // @ts-expect-error Todo: publicize to dismiss this "unused" error.
365
+ async _PackPackages(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
366
+ opts['-GetItem'] = [...(opts['-GetItem'] ?? []), key_OutputPackItems];
367
+ const packCmd = this.GetPackCommand(opts, usePerSourceSubfolder, usePerPackageIdSubfolder);
368
+ let packOutput = undefined;
369
+ while (packOutput === undefined) {
370
+ packOutput = await setTimeout(1000, execAsync(packCmd, true)).then(async p => await p).catch(catchCsc2012);
371
+ }
372
+ // may include .snupkg
373
+ const nupkgFullPaths = new MSBuildEvaluationOutput(packOutput.stdout).Items?.[key_OutputPackItems]?.filter(item => item.Extension !== '.nuspec').map(item => item.FullPath);
374
+ return nupkgFullPaths ?? [];
375
+ }
376
+
377
+ /**
378
+ * Create a dummy package for the current {@link project} by executing a
379
+ * command line like \``dotnet pack ${this.project.Properties.MSBuildProjectFullPath} -p:Version=0.0.1-DUMMY -output ${getDummiesDir(this._project)}/${GetNameForURL(this.source)}`\`
380
+ * @param opts Options passed to
381
+ * `dotnet pack`, excluding the required `<PROJECT | SOLUTION>` argument.
382
+ * - The `output` field is ignored and overwritten. It is replaced with
383
+ * ${{@link getDummiesDir}({@link project})}/${{@link GetDirNameForSource}({@link source})}
384
+ * - The `output` path will be affixed with a folder named after this
385
+ * {@link NugetRegistryInfo#source}, but will not include a subfolder for the
386
+ * {@link NugetRegistryInfo#project NugetRegistryInfo.project}.{@link MSBuildProject#Properties Properties}.{@link MSBuildProject#Properties#PackageId PackageId}.
387
+ * @returns the full paths of all nupkg, symbols.nupkg, and snupkg files
388
+ * created by the Pack target, as extracted from the dotnet process's STDOUT.
389
+ * If mixed with other nupkgs, filter for the {@link NugetProjectProperties#PackageId}
390
+ */
391
+ async PackDummyPackage(opts) {
392
+ const packCmd = this.GetPackCommand(_objectSpread(_objectSpread({}, opts), {}, {
393
+ output: getDummiesDir(this._project),
394
+ propertyOverrides: _objectSpread(_objectSpread({}, opts.propertyOverrides), {}, {
395
+ Version: '0.0.1-DUMMY'
396
+ }),
397
+ '-GetItem': [...(opts['-GetItem'] ?? []), key_OutputPackItems]
398
+ }), true);
399
+ let packOutput = undefined;
400
+ while (packOutput === undefined) {
401
+ packOutput = await setTimeout(1000, execAsync(packCmd, true)).then(async p => await p).catch(catchCsc2012);
402
+ }
403
+ // may include .snupkg
404
+ const nupkgFullPaths = new MSBuildEvaluationOutput(packOutput.stdout).Items?.['outputPackItems']?.filter(item => item.Extension !== '.nuspec').map(item => item.FullPath);
405
+ return nupkgFullPaths ?? [];
406
+ }
407
+
408
+ // #endregion Pack
409
+ // #region Push
410
+
411
+ /**
412
+ * Also includes required argument 'ROOT': the directory in which packages
413
+ * should be present and ready to be pushed the default or specified Source.
414
+ * The ROOT may also include wildcards e.g. `*.nupkg`, `**\\*.nupkg`
415
+ * See https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-push
416
+ *
417
+ * Specific to this API:
418
+ * If you want to use this API's default root value (\`${cwd()}/publish`), assign an empty string.
419
+ */
420
+ static PushPackagesOptionsType = Object.freeze(type({
421
+ /** If an empty string is passed, this property is overridden to `./publish` */
422
+ root: 'string',
423
+ /** The API key for the server. NOTE: if `undefined` or an empty string, the `dotnet nuget` client will lookup credentials set via `dotnet nuget {add|update} source`. */
424
+ 'apiKey?': 'string',
425
+ /** The NuGet configuration file (nuget.config) to use. If specified, only the settings from this file will be used. If not specified, the hierarchy of configuration files from the current directory will be used. For more information, see {@link https://learn.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior Common NuGet Configurations}. */
426
+ 'configFile?': 'string',
427
+ /** Disables buffering when pushing to an HTTP(S) server to reduce memory usage. */
428
+ 'disableBuffering?': 'boolean',
429
+ /** Forces the application to run using an invariant, English-based culture. */
430
+ 'forceEnglishOutput?': 'boolean',
431
+ /** Allows the command to stop and wait for user input or action. For example, to complete authentication. Available since .NET Core 3.0 SDK. */
432
+ 'interactive?': 'boolean',
433
+ /** Doesn't append "api/v2/package" to the source URL. */
434
+ 'noServiceEndpoint?': 'boolean',
435
+ 'noSymbols?': 'boolean',
436
+ /** When pushing multiple packages to an HTTP(S) server, treats any 409 Conflict response as a warning so that other pushes can continue. */
437
+ 'skipDuplicate?': 'boolean',
438
+ /**
439
+ * Specifies the server URL. NuGet identifies a UNC or local folder source and simply copies the file there instead of pushing it using HTTP.
440
+ *
441
+ * ### Important
442
+ * > Starting with NuGet 3.4.2, this is a mandatory parameter unless the NuGet config file specifies a `DefaultPushSource` value. For more information, see {@link https://learn.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior Configuring NuGet behavior}.
443
+ */
444
+ 'source?': 'string',
445
+ /** The API key for the symbol server. NOTE: if `undefined`, the `dotnet nuget` client will lookup credentials set via `dotnet nuget {add|update} source`.` */
446
+ 'symbolApiKey?': 'string',
447
+ /** Specifies the symbol server URL. */
448
+ 'symbolSource?': 'string',
449
+ /** Specifies the timeout for pushing to a server in seconds. Defaults to 300 seconds (5 minutes). Specifying 0 applies the default value. */
450
+ 'timeout?': 'number'
451
+ }));
452
+
453
+ /**
454
+ * {@link NRI.PushPackagesOptionsType} sans {@link NRI.PushPackagesOptionsType.t.root}.
455
+ * The result of {@link getDummiesDir} is used, instead.
456
+ */
457
+ static PushDummyPackagesOptionsType = NugetRegistryInfo.PushPackagesOptionsType.merge({
458
+ skipDuplicate: 'true = true'
459
+ }).omit('root');
460
+
461
+ /**
462
+ * Create a `dotnet nuget push` command line from the given options and
463
+ * optional boolean parameters.
464
+ * @param opts See {@link PushPackagesOptionsType}
465
+ * @param usePerSourceSubfolder If `true`, the NuGet Source name or URL is formatted
466
+ * to a folder name and appended to the ROOT as a subfolder. Do not use
467
+ * wildcards in ROOT with this set to `true`!
468
+ * @param usePerPackageIdSubfolder If `true`, the
469
+ * {@link project}'s {@link NugetProjectProperties#PackageId}
470
+ * is appended to the ROOT as a subfolder. Do not use wildcards in
471
+ * ROOT with this set to `true`!
472
+ * @returns A `dotnet nuget push` command line formatted with the
473
+ * appropriate arguments.
474
+ */
475
+ GetPushCommand(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
476
+ const validOpts = NRI.PushPackagesOptionsType.from(opts);
477
+ type.boolean.assert(usePerSourceSubfolder);
478
+ type.boolean.assert(usePerPackageIdSubfolder);
479
+ validOpts.root = validOpts.root === '' ? `${cwd()}/publish` : validOpts.root;
480
+ if (usePerSourceSubfolder) validOpts.root = node_path.join(validOpts.root, NugetRegistryInfo.GetDirNameForSource(this.source), node_path.sep);
481
+ if (usePerPackageIdSubfolder) validOpts.root = node_path.join(validOpts.root, this._project.Properties.PackageId, node_path.sep);
482
+ const packCmdArr = ['dotnet', 'nuget', 'push', `"${node_path.join(validOpts.root, '*.nupkg')}"`];
483
+ if (this.resolvedEnvVariable) validOpts.apiKey ??= NRI._GetTokenValue(this.resolvedEnvVariable);
484
+ /**
485
+ * If apiKey is an empty string, defer to the dotnet CLI's NuGet client
486
+ * ability to lookup API keys saved via `dotnet nuget add source` or NuGet config
487
+ * files.
488
+ */
489
+ if (validOpts.apiKey && validOpts.apiKey !== '') packCmdArr.push('--api-key', validOpts.apiKey);
490
+ if (validOpts.configFile) packCmdArr.push('--configfile', validOpts.configFile);
491
+ if (validOpts.disableBuffering === true) packCmdArr.push('--disable-buffering');
492
+ if (validOpts.forceEnglishOutput === true) packCmdArr.push('--force-english-output');
493
+ if (validOpts.interactive === true) packCmdArr.push('--interactive');
494
+ if (validOpts.noServiceEndpoint === true) packCmdArr.push('--no-service-endpoint');
495
+ if (validOpts.noSymbols === true) packCmdArr.push('--no-symbols');
496
+ if (validOpts.skipDuplicate === true) packCmdArr.push('--skip-duplicate');
497
+ validOpts.source ??= this.source;
498
+ packCmdArr.push('--source', validOpts.source);
499
+ if (validOpts.symbolApiKey !== undefined) packCmdArr.push('--symbol-api-key', validOpts.symbolApiKey);
500
+ if (validOpts.symbolSource !== undefined) packCmdArr.push('--symbol-source', validOpts.symbolSource);
501
+ if (validOpts.timeout !== undefined) packCmdArr.push('--timeout', validOpts.timeout.toString());
502
+ return packCmdArr.join(' ');
503
+ }
504
+
505
+ /**
506
+ * Immediately push packages. The input path may be modified according to the
507
+ * {@link usePerSourceSubfolder} and {@link usePerPackageIdSubfolder}
508
+ * arguments.
509
+ * @param opts The `dotnet nuget push` command line options, including the
510
+ * ROOT argument, the directory containing local nuget packages ready to be
511
+ * pushed.
512
+ * @param usePerSourceSubfolder If `true`, the NuGet Source name or URL is formatted
513
+ * to a folder name and appended to the ROOT as a subfolder. Do not use
514
+ * wildcards in ROOT with this set to `true`!
515
+ * @param usePerPackageIdSubfolder If `true`, the current {@link project}'s
516
+ * PackageId is appended to the ROOT as a subfolder. Do not use wildcards in
517
+ * ROOT with this set to `true`!
518
+ */
519
+ // @ts-expect-error Todo: publicize to dismiss this "unused" error.
520
+ async _PushPackages(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
521
+ // const pushOutput =
522
+ await execAsync(this.GetPushCommand(opts, usePerSourceSubfolder, usePerPackageIdSubfolder), true).catch(error => {
523
+ const _error = isNativeError(error) ? error : new Error(JSON.stringify(error));
524
+ throw opts.apiKey ? _censorTokenInError(_error, opts.apiKey) : _error;
525
+ });
526
+ }
527
+
528
+ /**
529
+ *
530
+ * Get a `dotnet nuget push` command for pushing one or more nupkg/snupkg
531
+ * files created by {@link GetPackCommand} or {@link _PackPackages}.\
532
+ * Like {@link PackDummyPackage}, the output/ROOT path will include a
533
+ * folder named after this NRI instance's {@link NugetRegistryInfo#source},
534
+ * but will not include a subfolder for the
535
+ * {@link NugetRegistryInfo#project NugetRegistryInfo.project}.{@link MSBuildProject#Properties Properties}.{@link MSBuildProject#Properties#PackageId PackageId}
536
+ * @example
537
+ * ```ts
538
+ * const packAndPushDummyCmd = [
539
+ * nri.GetPackCommand(
540
+ * NugetRegistryInfo.PackPackagesOptionsType.from({ root: '' }),
541
+ * false,
542
+ * false,
543
+ * ),
544
+ * nri.GetPushDummyPackageCommand(pushOpts, false, false),
545
+ * ].join(' && ')
546
+ * ```
547
+ * @param opts options for `dotnet nuget push`. The following
548
+ * fields are overwritten:
549
+ * - root: getDummiesDir(this.project)
550
+ * - skipDuplicates: true
551
+ * @returns a `dotnet nuget push` command to push a dummy package
552
+ * (created by executing {@link PackDummyPackage}) to {@link source}
553
+ */
554
+ GetPushDummyCommand(opts) {
555
+ return this.GetPushCommand(_objectSpread(_objectSpread({}, NRI.PushDummyPackagesOptionsType.from(opts)), {}, {
556
+ root: getDummiesDir(this._project)
557
+ }), true);
558
+ }
559
+
560
+ /**
561
+ * Call {@link GetPushDummyCommand} and immediately execute it.
562
+ * @throws {Error} when the process exits with an error code indicating
563
+ * failure i.e. the command line is invalid, the process fails to start,
564
+ * the push fails, et cetera.
565
+ * @param opts the ROOT arg and options for `dotnet nuget push`. The following
566
+ * fields are overwritten:
567
+ * - root: getDummiesDir(this.project)
568
+ * - skipDuplicates: true
569
+ * @returns The return type of {@link execAsync} i.e. a {@link Promise} resolving to `{ stdout: string; stderr: string }`.
570
+ */
571
+ async _PushDummyPackages(opts) {
572
+ const pushCmd = this.GetPushDummyCommand(opts);
573
+ return await execAsync(pushCmd, true).catch(error => {
574
+ const _error = isNativeError(error) ? error : new Error(String(error));
575
+ throw opts.apiKey ? _censorTokenInError(_error, opts.apiKey) : _error;
576
+ });
577
+ }
578
+
579
+ // #endregion Push
580
+
581
+ // if non-exact-match is needed, learn how to make a parameter-driven type.
582
+ static _NugetSearchReturnTypes = {
583
+ ExactMatch: {
584
+ v2: type({
585
+ version: '2',
586
+ problems: 'unknown[]',
587
+ searchResult: [{
588
+ sourceName: 'string',
589
+ packages: type({
590
+ id: 'string',
591
+ version: type.keywords.string.semver
592
+ }).array()
593
+ }]
594
+ })
595
+ }
596
+ };
597
+ static _ParseNugetSearchReturn = type('string.json.parse').to(this._NugetSearchReturnTypes.ExactMatch.v2);
598
+
599
+ /**
600
+ * !WARNING: this method requires the Nuget Source to be configured via `dotnet nuget add source` or `dotnet nuget update source`. `NUGET_TOKEN` works, but it may be vulnerable to supply chain attacks.\
601
+ * Call during the `prepare` step of a Semantic Release run.\
602
+ * Determine if the `nextVersion` generated during the `analyze` Semantic
603
+ * Release step was already published to the NuGet {@link source}.
604
+ * @param source The name or URI of the NuGet Source to search. If this API
605
+ * endpoint does not support searches, the operation will fail. If this API
606
+ * endpoint requires authentication (e.g. GitHub), it must be configured via
607
+ * `dotnet nuget add source` or `dotnet nuget update source` before calling
608
+ * this method.
609
+ * @param packageId The ID of the NuGet package to search for.
610
+ * @param nextVersion The nextVersion value generated by semantic-release's hidden ["Create Git tag" step](https://semantic-release.gitbook.io/semantic-release#:~:text=the%20last%20release.-,Create%20Git%20tag,-Create%20a%20Git).
611
+ * @returns A promised boolean.
612
+ * If the promise resolves to `true`, the semantic release run should be
613
+ * cancelled immediately.
614
+ * Otherwise, the release should proceed.
615
+ * @todo utilize in custom plugin inserted at the beginning of `prepare`
616
+ */
617
+ static async IsNextVersionAlreadyPublished(source, packageId, nextVersion) {
618
+ if (nextVersion === '') throw new Error('The value of nextVersion is empty');
619
+ return await execAsync(`dotnet package search --format JSON --exact-match --source ${source} --prerelease ${packageId}`, true).then(stdPair => stdPair.stdout).then(json => this._ParseNugetSearchReturn(json)).then(errsOrObj => errsOrObj instanceof type.errors ? errsOrObj.throw() : errsOrObj).then(obj => obj.searchResult).then(results => results[0].packages).then(pkgs => pkgs.find(p => p.version === type('string.semver').from(nextVersion))).then(pkg => pkg !== undefined);
620
+ }
621
+
622
+ /**
623
+ * !WARNING: GITHUB_OUTPUT must be the full path to an environment file.
624
+ * The plugin "semantic-release-output-variables" next-release-version
625
+ *
626
+ * !WARNING: NuGet Source API Key mus tbe configured via `dotnet nuget add source` or `dotnet nuget update source`.
627
+ * Some Sources (e.g. GitHub) require authentication for package searches.
628
+ *
629
+ * # Authenticating NuGet Package Searches
630
+ *
631
+ * ## GitHub NuGet Registry authentication
632
+ * - {@link https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry#authenticating-in-a-github-actions-workflow Authenticating in a GitHub Actions workflow}
633
+ * - {@link https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry#authenticating-with-a-personal-access-token Authenticating with a personal access token}.
634
+ * ## For GitLab NuGet Registry authentication, see
635
+ * - {@link https://docs.gitlab.com/ee/user/packages/nuget_repository/#add-a-source-with-the-net-cli Add a source with the .NET CLI}
636
+ * @returns a string containing a Node.JS command line invoking {@link ./IsNextVersionAlreadyPublished.cli.ts}
637
+ * @see {@link ./IsNextVersionAlreadyPublished.cli.ts}, {@link ./IsNextVersionAlreadyPublished.cli.js}
638
+ */
639
+ GetIsNextVersionAlreadyPublishedCommand() {
640
+ // if GITHUB_OUTPUT unset or its file does not exist, create it. ''
641
+ getGithubOutputSync();
642
+ // The script will run
643
+ return `node ${node_path.join(import.meta.dirname, './IsNextVersionAlreadyPublished.cli.js')} --packageId ${this._project.Properties.PackageId} --source ${this.source}`;
644
+ }
645
+
646
+ /*
647
+ * Copy https://github.com/joelharkes/nuget-push when we split off our dotnet
648
+ * modules to a semantic-release plugin.
649
+ */
650
+
651
+ /*
652
+ * If you want a deterministic nupkg, do so with a custom MSBuild target with
653
+ * AfterTargets="Pack" to restore and execute the dotnet tool "Kuinox.NupkgDeterministicator" .
654
+ */
655
+ }
656
+
657
+ // shorthand/alias for NugetRegistryInfo
658
+ const NRI = NugetRegistryInfo;
659
+
660
+ /**
661
+ * The base type for {@link NRIOpts} and related types. Extend this type while
662
+ * overriding member types via {@link NRIOptsBase.merge}
663
+ */
664
+ const NRIOptsBase = type({
665
+ /**
666
+ * The environment variables whose values are tokens with permission to push a
667
+ * package to the NuGet package registry. The array is iterated through until
668
+ * one token is found. If none of the environment variables are defined,
669
+ * {@link NugetRegistryInfo}'s constructor will throw an {@link Error}.
670
+ */
671
+ project: type.instanceOf(MSBuildProject).or(type.instanceOf(MSBuildProject).readonly()),
672
+ /**
673
+ * A NuGet package registry's API endpoint URL -OR- the name assigned via the
674
+ * client e.g. `dotnet nuget add source --name ${source} ${source's URL}`
675
+ */
676
+ source: type.string,
677
+ /**
678
+ * WARNING: If possible, set credentials via `dotnet nuget {add|update}
679
+ * source` as recommended by Microsoft! This is more secure than exposing
680
+ * credentials to the Node.JS runtime and all its loaded modules.
681
+ *
682
+ * The environment variables whose values are tokens with permission to push a
683
+ * package to the NuGet package registry.The array is iterated through until
684
+ * one token is found.If none of the environment variables are defined,
685
+ * {@link NugetRegistryInfo}'s constructor will throw an {@link Error}.
686
+ *
687
+ * If none of these are defined in the `.env` or process environment variables (.vault.env is impractical in CI), the `--api-key/-k` argument is excluded from `dotnet nuget push` commands.
688
+ * Instead, the NuGet client relies on credentials configured for the
689
+ * given NuGet source. If the NuGet client does not find credentials saved for the
690
+ * NuGet {@link NRIOptsBase.t.source source} and they are required, the command will fail.
691
+ *
692
+ * Use the `dotnet` CLI to configure credentials for existing NuGet sources
693
+ * ({@link https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-update-source `dotnet nuget update source`})
694
+ * -OR- configure credentials for non-default NuGet sources
695
+ * ({@link https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-add-source `dotnet nuget add source`}).\
696
+ * Alternatively, use the `nuget.exe` CLI to add/update sources. See
697
+ * {@link https://learn.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-sources `nuget sources` (NuGet CLI)}.
698
+ *
699
+ * The credentials will be validated during the `verifyConditions` step of Semantic Release.
700
+ */
701
+ tokenEnvVars: type.string.array().readonly()
702
+ });
703
+
704
+ /**
705
+ * The type of the parameter for {@link NugetRegistryInfo}'s constructor.
706
+ */
707
+ const NRIOpts = NRIOptsBase.merge({
708
+ /**
709
+ * Defaults to {@link NugetRegistryInfo.DefaultTokenEnvVars}
710
+ * @see {@link NRIOptsBase.t.tokenEnvVars}
711
+ */
712
+ tokenEnvVars: NRIOptsBase.get('tokenEnvVars').default(() => NugetRegistryInfo.DefaultTokenEnvVars),
713
+ /**
714
+ * A NuGet package registry's API endpoint URL -OR- the name assigned to it
715
+ * via your NuGet client.
716
+ * @default 'https://api.nuget.org/v3/index.json' (name: 'nuget.org')
717
+ * @see {@link NRIOptsBase.t.source}
718
+ */
719
+ source: NRIOptsBase.get('source').default(() => defaultNugetSource)
720
+ });
721
+
722
+ // #region token censorship
723
+
724
+ /**
725
+ * Replace all occurrences of {@link token} in the {@link string} with '***'.
726
+ * @param string The string in which a {@link token} may be found.
727
+ * @param token The NuGet API token you definitely don't want to leak!
728
+ * @returns A modified copy of the {@link string} with all occurrences of the
729
+ * {@link token} replaced with '***'.
730
+ */
731
+ function _censorToken(string, token) {
732
+ return string.replaceAll(token, '***');
733
+ }
734
+
735
+ /**
736
+ * Censor all occurrences of an API {@link token} in an {@link error}.
737
+ * @param error A {@link ExecException} in which the NuGet API {@link token} may be found.
738
+ * @param token The value of the NuGet API token
739
+ * @returns A modified copy of the provided exception sans any occurrence of the
740
+ * NuGet API token.
741
+ */
742
+ function _censorTokenInError(error, token) {
743
+ return Object.assign(error, JSON.parse(_censorToken(JSON.stringify(_objectSpread(_objectSpread({}, error), {}, {
744
+ message: error.message,
745
+ stack: error.stack
746
+ })), token)));
747
+ }
748
+
749
+ // #endregion token censorship
750
+
751
+ export { NRIOpts, NRIOptsBase, NugetRegistryInfo, getGithubOutput, getGithubOutputSync };
752
+ //# sourceMappingURL=NugetRegistryInfo.mjs.map