@pitcher/cli-scripts 2.1.2 → 2.2.1

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.
@@ -1,257 +0,0 @@
1
- import { Command } from "commander";
2
- import archiver from "archiver";
3
- import axios from "axios";
4
- import fs from "fs";
5
- import path from "path";
6
- import FormData from "form-data";
7
- import { fileURLToPath } from "url";
8
- async function fetchAllInstances(baseUrl, apiKey) {
9
- const pageSize = 100;
10
- const maxPages = 50;
11
- try {
12
- console.log("Fetching instances page 1 to determine total count...");
13
- const firstResponse = await axios.get(`${baseUrl}/api/v1/instances`, {
14
- headers: {
15
- accept: "application/json",
16
- "x-api-key": apiKey,
17
- },
18
- params: {
19
- page_size: pageSize,
20
- page: 1,
21
- },
22
- });
23
- const firstData = firstResponse.data;
24
- const firstInstances = firstData.results || [];
25
- if (firstInstances.length === 0) {
26
- console.log("No instances found");
27
- return [];
28
- }
29
- const totalCount = firstData.count || firstInstances.length;
30
- const totalPages = Math.min(Math.ceil(totalCount / pageSize), maxPages);
31
- console.log(`Found ${totalCount} instance(s) across ${totalPages} page(s)`);
32
- if (totalPages === 1) {
33
- console.log(`✓ Fetched ${firstInstances.length} total instance(s) from API`);
34
- return firstInstances;
35
- }
36
- const remainingPageNumbers = Array.from({ length: totalPages - 1 }, (_, i) => i + 2);
37
- console.log(`Fetching remaining ${totalPages - 1} pages in parallel...`);
38
- const remainingPagePromises = remainingPageNumbers.map((page) => axios.get(`${baseUrl}/api/v1/instances`, {
39
- headers: {
40
- accept: "application/json",
41
- "x-api-key": apiKey,
42
- },
43
- params: {
44
- page_size: pageSize,
45
- page: page,
46
- },
47
- }));
48
- const remainingResponses = await Promise.all(remainingPagePromises);
49
- const remainingInstances = remainingResponses.flatMap((response) => response.data.results || []);
50
- const allInstances = [...firstInstances, ...remainingInstances];
51
- if (totalPages >= maxPages) {
52
- console.warn(`⚠ Warning: Reached maximum page limit (${maxPages}). There may be more instances.`);
53
- }
54
- console.log(`✓ Fetched ${allInstances.length} total instance(s) from API`);
55
- return allInstances;
56
- }
57
- catch (error) {
58
- const axiosError = error;
59
- console.error("Error fetching instances:", axiosError?.response?.data?.detail ?? axiosError.message);
60
- return [];
61
- }
62
- }
63
- function filterInstancesByEnvName(instances, envName) {
64
- const filtered = instances.filter((instance) => {
65
- return instance.environment?.name.toLowerCase() === envName.toLowerCase();
66
- });
67
- if (filtered.length === 0) {
68
- console.warn(`No instances found with environment name "${envName}"`);
69
- }
70
- else {
71
- console.log(`Found ${filtered.length} instance(s) with environment name "${envName}"`);
72
- }
73
- return filtered;
74
- }
75
- function validateInstanceIds(instances, requestedIds) {
76
- const instanceMap = new Map(instances.map((inst) => [inst.id, inst]));
77
- const valid = [];
78
- const invalid = [];
79
- for (const id of requestedIds) {
80
- const instance = instanceMap.get(id);
81
- if (instance) {
82
- valid.push(instance);
83
- }
84
- else {
85
- invalid.push(id);
86
- }
87
- }
88
- return { valid, invalid };
89
- }
90
- async function installAppToInstances(baseUrl, apiKey, appName, instances) {
91
- if (instances.length === 0) {
92
- console.log("No instances to install to.");
93
- return;
94
- }
95
- const instanceIds = instances.map((inst) => inst.id);
96
- console.log(`\nInstalling app "${appName}" to ${instances.length} instance(s):`);
97
- instances.forEach((i) => {
98
- console.log(` - ${i.id}${i.environment?.name ? ` (${i.environment.name})` : ""}${i.name ? ` - ${i.name}` : ""}`);
99
- });
100
- try {
101
- const response = await axios.post(`${baseUrl}/api/v1/apps/${appName}/install/`, { instance_ids: instanceIds }, {
102
- headers: {
103
- accept: "application/json",
104
- "content-type": "application/json",
105
- "x-api-key": apiKey,
106
- },
107
- });
108
- console.log("\nInstallation response:", response.data);
109
- console.log(`✓ Successfully installed app to ${instances.length} instance(s)`);
110
- }
111
- catch (error) {
112
- const axiosError = error;
113
- console.error("\n✗ Error installing app:", axiosError?.response?.data?.detail ?? axiosError.message);
114
- }
115
- }
116
- export function createPublishAppCommand() {
117
- const program = new Command("publish-app");
118
- program
119
- .arguments("[folder]")
120
- .option("--api-key <apiKey>", "API Key for authentication")
121
- .option("--org <organization>", "Organization subdomain", "dev")
122
- .option("--increment-version", "Increment version in app.json")
123
- .option("--dry-run", "Perform a dry run without publishing")
124
- .option("--publish-url <url>", "Explicit publish URL")
125
- .option("--install-to <instanceIds>", "Comma-separated list of instance IDs to install the app to after publishing")
126
- .option("--install-to-env-name <envName>", "Environment name to filter instances and install the app to after publishing")
127
- .description('zip the contents of a folder and publish as an app to a pitcher org URL. for current folder: "p publish-app --api-key myapikey"')
128
- .action(async (folder = ".", options) => {
129
- const apiKey = options.apiKey || process.env.NG_API_KEY;
130
- if (!apiKey) {
131
- console.error("Error: API key is required. Provide it via --api-key or set the NG_API_KEY environment variable.");
132
- process.exit(1);
133
- }
134
- if (!options.publishUrl && !options.org)
135
- options.org = "dev";
136
- options.apiKey = apiKey;
137
- try {
138
- const folderPath = path.resolve(folder);
139
- if (options.incrementVersion) {
140
- const appJsonPath = path.join(folderPath, "app.json");
141
- if (fs.existsSync(appJsonPath)) {
142
- const appJson = JSON.parse(fs.readFileSync(appJsonPath, "utf-8"));
143
- const now = new Date();
144
- const year = now.getFullYear();
145
- const month = String(now.getMonth() + 1).padStart(2, "0");
146
- const day = String(now.getDate()).padStart(2, "0");
147
- const timestamp = now.getTime();
148
- const version = `${year}.${month}.${day}.${timestamp}`;
149
- appJson.version = version;
150
- fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2));
151
- console.log(`Updated app.json version to ${version}`);
152
- }
153
- else {
154
- console.error("app.json not found in the specified folder.");
155
- return;
156
- }
157
- }
158
- const currentDir = path.dirname(fileURLToPath(import.meta.url));
159
- const zipFilePath = path.join(currentDir, "app.zip");
160
- const output = fs.createWriteStream(zipFilePath);
161
- const archive = archiver("zip", {
162
- zlib: { level: 9 },
163
- });
164
- output.on("close", async () => {
165
- console.log(`Zipped ${archive.pointer()} total bytes`);
166
- const formData = new FormData();
167
- formData.append("file", fs.createReadStream(zipFilePath));
168
- const publishUrl = options.publishUrl ||
169
- `https://${options.org}.my.pitcher.com/api/v1/apps/publish/`;
170
- if (options.dryRun) {
171
- console.log("Dry run mode enabled. The following data would be published:");
172
- console.log("Publish URL:", publishUrl);
173
- console.log("Headers:", {
174
- ...formData.getHeaders(),
175
- "x-api-key": options.apiKey,
176
- });
177
- console.log("app.json content:", fs.readFileSync(path.join(folderPath, "app.json"), "utf-8"));
178
- fs.unlinkSync(zipFilePath);
179
- }
180
- else {
181
- try {
182
- const response = await axios.post(publishUrl, formData, {
183
- headers: {
184
- ...formData.getHeaders(),
185
- "x-api-key": options.apiKey,
186
- },
187
- });
188
- console.log("Publish response:", response.data);
189
- const baseUrl = options.publishUrl
190
- ? new URL(options.publishUrl).origin
191
- : `https://${options.org}.my.pitcher.com`;
192
- const appName = response.data?.app?.name;
193
- if (!appName) {
194
- console.warn("Could not determine app name from publish response");
195
- }
196
- else if (options.installTo || options.installToEnvName) {
197
- console.log("\n--- Starting installation process ---");
198
- const allInstances = await fetchAllInstances(baseUrl, options.apiKey);
199
- if (allInstances.length === 0) {
200
- console.warn("Cannot proceed with installation: no instances available");
201
- }
202
- else {
203
- let targetInstances = [];
204
- if (options.installTo) {
205
- const requestedIds = options.installTo
206
- .split(",")
207
- .map((id) => id.trim())
208
- .filter(Boolean);
209
- console.log(`\nValidating ${requestedIds.length} requested instance ID(s)...`);
210
- const { valid, invalid } = validateInstanceIds(allInstances, requestedIds);
211
- if (invalid.length > 0) {
212
- console.warn(`⚠ Warning: ${invalid.length} invalid instance ID(s) will be skipped:`);
213
- invalid.forEach((id) => console.warn(` - ${id}`));
214
- }
215
- if (valid.length > 0) {
216
- console.log(`✓ Found ${valid.length} valid instance(s)`);
217
- targetInstances = [...targetInstances, ...valid];
218
- }
219
- }
220
- if (options.installToEnvName) {
221
- console.log(`\nFiltering instances by environment name: "${options.installToEnvName}"`);
222
- const envInstances = filterInstancesByEnvName(allInstances, options.installToEnvName);
223
- targetInstances = [...targetInstances, ...envInstances];
224
- }
225
- const uniqueInstances = Array.from(new Map(targetInstances.map((inst) => [inst.id, inst])).values());
226
- if (uniqueInstances.length > 0) {
227
- await installAppToInstances(baseUrl, options.apiKey, appName, uniqueInstances);
228
- }
229
- else {
230
- console.log("\nNo valid instances found to install to.");
231
- }
232
- }
233
- }
234
- }
235
- catch (e) {
236
- const error = e;
237
- const errData = error?.response?.data;
238
- console.error("Error publishing:", errData?.detail ?? errData);
239
- }
240
- finally {
241
- fs.unlinkSync(zipFilePath);
242
- }
243
- }
244
- });
245
- archive.on("error", (err) => {
246
- throw err;
247
- });
248
- archive.pipe(output);
249
- archive.directory(folderPath, false);
250
- await archive.finalize();
251
- }
252
- catch (error) {
253
- console.error("Error zipping or publishing:", error);
254
- }
255
- });
256
- return program;
257
- }