Skip to content

Commit 8d02dcb

Browse files
authored
Merge pull request #33 from reynaldichernando/puter-js
Migrate drivers call to Puter.js NPM
2 parents 0280b5a + 462e720 commit 8d02dcb

File tree

7 files changed

+149
-302
lines changed

7 files changed

+149
-302
lines changed

src/commands/apps.js

Lines changed: 37 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { deleteSite } from './sites.js';
99
import { copyFile, createFile, listRemoteFiles, pathExists, removeFileOrDirectory } from './files.js';
1010
import { getCurrentDirectory } from './auth.js';
1111
import crypto from '../crypto.js';
12+
import { getPuter } from '../modules/PuterModule.js';
1213

1314
/**
1415
* List all apps
@@ -23,22 +24,13 @@ import crypto from '../crypto.js';
2324
*/
2425
export async function listApps({ statsPeriod = 'all', iconSize = 64 } = {}) {
2526
console.log(chalk.green(`Listing of apps during period "${chalk.cyan(statsPeriod)}" (try also: today, yesterday, 7d, 30d, this_month, last_month):\n`));
27+
const puter = getPuter();
2628
try {
27-
const response = await fetch(`${API_BASE}/drivers/call`, {
28-
method: 'POST',
29-
headers: getHeaders(),
30-
body: JSON.stringify({
31-
interface: "puter-apps",
32-
method: "select",
33-
args: {
34-
params: { icon_size: iconSize },
35-
predicate: ["user-can-edit"],
36-
stats_period: statsPeriod,
37-
}
38-
})
29+
const result = await puter.apps.list({
30+
icon_size: iconSize,
31+
stats_period: statsPeriod
3932
});
40-
const data = await response.json();
41-
if (data && data['result']) {
33+
if (result) {
4234
// Create a new table instance
4335
const table = new Table({
4436
head: [
@@ -57,7 +49,7 @@ export async function listApps({ statsPeriod = 'all', iconSize = 64 } = {}) {
5749

5850
// Populate the table with app data
5951
let i = 0;
60-
for (const app of data['result']) {
52+
for (const app of result) {
6153
table.push([
6254
i++,
6355
app['title'],
@@ -72,7 +64,7 @@ export async function listApps({ statsPeriod = 'all', iconSize = 64 } = {}) {
7264

7365
// Display the table
7466
console.log(table.toString());
75-
console.log(chalk.green(`You have in total: ${chalk.cyan(data['result'].length)} application(s).`));
67+
console.log(chalk.green(`You have in total: ${chalk.cyan(result.length)} application(s).`));
7668
} else {
7769
console.error(chalk.red('Unable to list your apps. Please check your credentials.'));
7870
}
@@ -97,24 +89,12 @@ export async function appInfo(args = []) {
9789
}
9890
const appName = args[0].trim()
9991
console.log(chalk.green(`Looking for "${chalk.dim(appName)}" app informations:\n`));
92+
const puter = getPuter();
10093
try {
101-
const response = await fetch(`${API_BASE}/drivers/call`, {
102-
method: 'POST',
103-
headers: getHeaders(),
104-
body: JSON.stringify({
105-
interface: "puter-apps",
106-
method: "read",
107-
args: {
108-
id: {
109-
name: appName
110-
}
111-
}
112-
})
113-
});
114-
const data = await response.json();
115-
if (data && data['result']) {
94+
const result = await puter.apps.get(appName);
95+
if (result) {
11696
// Display the informations
117-
displayNonNullValues(data['result']);
97+
displayNonNullValues(result);
11898
} else {
11999
console.error(chalk.red('Could not find this app.'));
120100
}
@@ -150,6 +130,7 @@ export async function createApp(args) {
150130
console.log(chalk.dim(`Description: ${description}`));
151131
console.log(chalk.dim(`URL: ${url}`));
152132

133+
const puter = getPuter();
153134
try {
154135
// Step 1: Create the app
155136
const createAppResponse = await fetch(`${API_BASE}/drivers/call`, {
@@ -246,23 +227,11 @@ export async function createApp(args) {
246227

247228
// Step 5: Update the app's index_url to point to the subdomain
248229
console.log(chalk.green(`Set "${chalk.dim(subdomainName)}" as a subdomain for app: "${chalk.dim(appName)}"...\n`));
249-
const updateAppResponse = await fetch(`${API_BASE}/drivers/call`, {
250-
method: 'POST',
251-
headers: getHeaders(),
252-
body: JSON.stringify({
253-
interface: "puter-apps",
254-
method: "update",
255-
args: {
256-
id: { name: appName },
257-
object: {
258-
index_url: `https://${subdomainName}.puter.site`,
259-
title: name
260-
}
261-
}
262-
})
263-
});
264-
const updateAppData = await updateAppResponse.json();
265-
if (!updateAppData || !updateAppData.success) {
230+
const updateAppData = await puter.apps.update(appName, {
231+
indexURL: `https://${subdomainName}.puter.site`,
232+
title: name
233+
})
234+
if (!updateAppData) {
266235
console.error(chalk.red(`Failed to update app "${name}" with new subdomain`));
267236
return;
268237
}
@@ -301,35 +270,25 @@ export async function updateApp(args = []) {
301270
return;
302271
}
303272

273+
const puter = getPuter();
304274
console.log(chalk.green(`Updating app: "${chalk.dim(name)}" from directory: ${chalk.dim(remoteDir)}\n`));
305275
try {
306276
// Step 1: Get the app info
307-
const appResponse = await fetch(`${API_BASE}/drivers/call`, {
308-
method: 'POST',
309-
headers: getHeaders(),
310-
body: JSON.stringify({
311-
interface: "puter-apps",
312-
method: "read",
313-
args: {
314-
id: { name }
315-
}
316-
})
317-
});
318-
const data = await appResponse.json();
319-
if (!data || !data.success) {
277+
const data = await puter.apps.get(name);
278+
if (!data) {
320279
console.error(chalk.red(`Failed to find app: "${name}"`));
321280
return;
322281
}
323-
const appUid = data.result.uid;
324-
const appName = data.result.name;
325-
const username = data.result.owner.username;
326-
const indexUrl = data.result.index_url;
282+
const appUid = data.uid;
283+
const appName = data.name;
284+
const username = data.owner.username;
285+
const indexUrl = data.index_url;
327286
const appDir = `/${username}/AppData/${appUid}`;
328287
console.log(chalk.cyan(`AppName: ${chalk.dim(appName)}\nUID: ${chalk.dim(appUid)}\nUsername: ${chalk.dim(username)}`));
329288

330289
// Step 2: Find the path from subdomain
331290
const subdomains = await getSubdomains();
332-
const appSubdomain = subdomains.result.find(sd => sd.root_dir?.dirname?.endsWith(appUid));
291+
const appSubdomain = subdomains.find(sd => sd.root_dir?.dirname?.endsWith(appUid));
333292
if (!appSubdomain){
334293
console.error(chalk.red(`Sorry! We could not find the subdomain for ${chalk.cyan(name)} application.`));
335294
return;
@@ -361,6 +320,7 @@ export async function updateApp(args = []) {
361320
console.log(chalk.dim(indexUrl));
362321
} catch (error) {
363322
console.error(chalk.red(`Failed to update app "${name}".\nError: ${error.message}`));
323+
console.error(error);
364324
}
365325
}
366326

@@ -374,60 +334,38 @@ export async function deleteApp(name) {
374334
console.log(chalk.red('Usage: app:delete <name>'));
375335
return false;
376336
}
337+
const puter = getPuter();
377338
console.log(chalk.green(`Checking app "${name}"...\n`));
378339
try {
379340
// Step 1: Read app details
380-
const readResponse = await fetch(`${API_BASE}/drivers/call`, {
381-
method: 'POST',
382-
headers: getHeaders(),
383-
body: JSON.stringify({
384-
interface: "puter-apps",
385-
method: "read",
386-
args: {
387-
id: { name }
388-
}
389-
})
390-
});
391-
392-
const readData = await readResponse.json();
341+
const readData = await puter.apps.get(name);
393342

394-
if (!readData.success || !readData.result) {
343+
if (!readData) {
395344
console.log(chalk.red(`App "${chalk.bold(name)}" not found.`));
396345
return false;
397346
}
398347

399348
// Show app details and confirm deletion
400349
console.log(chalk.cyan('\nApp Details:'));
401350
console.log(chalk.dim('----------------------------------------'));
402-
console.log(chalk.dim(`Name: ${chalk.cyan(readData.result.name)}`));
403-
console.log(chalk.dim(`Title: ${chalk.cyan(readData.result.title)}`));
404-
console.log(chalk.dim(`Created: ${chalk.cyan(formatDate(readData.result.created_at))}`));
405-
console.log(chalk.dim(`URL: ${readData.result.index_url}`));
351+
console.log(chalk.dim(`Name: ${chalk.cyan(readData.name)}`));
352+
console.log(chalk.dim(`Title: ${chalk.cyan(readData.title)}`));
353+
console.log(chalk.dim(`Created: ${chalk.cyan(formatDate(readData.created_at))}`));
354+
console.log(chalk.dim(`URL: ${readData.index_url}`));
406355
console.log(chalk.dim('----------------------------------------'));
407356

408357
// Step 2: Delete the app
409358
console.log(chalk.green(`Deleting app "${chalk.red(name)}"...`));
410-
const deleteResponse = await fetch(`${API_BASE}/drivers/call`, {
411-
method: 'POST',
412-
headers: getHeaders(),
413-
body: JSON.stringify({
414-
interface: "puter-apps",
415-
method: "delete",
416-
args: {
417-
id: { name }
418-
}
419-
})
420-
});path
421359

422-
const deleteData = await deleteResponse.json();
423-
if (!deleteData.success) {
360+
const deleteData = await puter.apps.delete(name);
361+
if (!deleteData) {
424362
console.error(chalk.red(`Failed to delete app "${name}".\nP.S. Make sure to provide the 'name' attribute not the 'title'.`));
425363
return false;
426364
}
427365

428366
// Lookup subdomainUID then delete it
429367
const subdomains = await getSubdomains();
430-
const appSubdomain = subdomains.result.find(sd => sd.root_dir?.dirname?.endsWith(readData.result.uid));
368+
const appSubdomain = subdomains.find(sd => sd.root_dir?.dirname?.endsWith(readData.uid));
431369
const subdomainDeleted = await deleteSite([appSubdomain.uid]);
432370
if (subdomainDeleted){
433371
console.log(chalk.green(`Subdomain: ${chalk.dim(appSubdomain.uid)} deleted.`));

src/commands/auth.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import fetch from 'node-fetch';
77
import { PROJECT_NAME, API_BASE, getHeaders, BASE_URL } from '../commons.js'
88
import { ProfileAPI } from '../modules/ProfileModule.js';
99
import { get_context } from '../temporary/context_helpers.js';
10+
import { getPuter } from '../modules/PuterModule.js';
1011
const config = new Conf({ projectName: PROJECT_NAME });
1112

1213
/**
@@ -56,12 +57,9 @@ export async function logout() {
5657

5758
export async function getUserInfo() {
5859
console.log(chalk.green('Getting user info...\n'));
60+
const puter = getPuter();
5961
try {
60-
const response = await fetch(`${API_BASE}/whoami`, {
61-
method: 'GET',
62-
headers: getHeaders()
63-
});
64-
const data = await response.json();
62+
const data = await puter.auth.getUser();
6563
if (data) {
6664
console.log(chalk.cyan('User Information:'));
6765
console.log(chalk.dim('----------------------------------------'));

0 commit comments

Comments
 (0)