nwui-cli 0.4.13-staging.1 → 0.4.13

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.
@@ -0,0 +1,5 @@
1
+
2
+ 
3
+ > nwui-cli@0.4.9 build /Users/dan/Developer/NativeWindUI/nativewindui/apps/cli
4
+ > tsc && chmod +x ./build/index.js
5
+
package/build/index.js ADDED
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import open from 'open';
5
+ import color from 'picocolors';
6
+ import { env } from './utils/env.js';
7
+ import { confirm } from './utils/prompts.js';
8
+ import { isLoggedIn, login } from './login.js';
9
+ import { installComponent } from './install-component.js';
10
+ import { renderTitle } from './utils/opening.js';
11
+ const main = async () => {
12
+ let quiet = false;
13
+ try {
14
+ if (!process.argv.includes('--quiet') && !process.argv.includes('-q')) {
15
+ await renderTitle();
16
+ }
17
+ }
18
+ catch (_err) {
19
+ if (!quiet) {
20
+ console.log(`\n${color.blue('welcome to the')} ${color.cyan('nativewindui cli')}`);
21
+ }
22
+ }
23
+ try {
24
+ switch (process.argv[2]) {
25
+ case 'add':
26
+ const args = process.argv.slice(3);
27
+ let noInstall = false;
28
+ let bigExamplesWithDependencies = false;
29
+ let overwrite = false;
30
+ let ignoreExpoRouterMissing = false;
31
+ let directory = undefined;
32
+ while (['--big-examples-with-deps', '--overwrite', '--yes', '-d', '--no-install', '--quiet', '-q'].includes(args[0])) {
33
+ switch (args[0]) {
34
+ case '--quiet':
35
+ case '-q':
36
+ quiet = true;
37
+ env.EXPO_QUIET = true;
38
+ args.shift();
39
+ break;
40
+ case '--big-examples-with-deps':
41
+ bigExamplesWithDependencies = true;
42
+ args.shift();
43
+ break;
44
+ case '--no-install':
45
+ noInstall = true;
46
+ args.shift();
47
+ break;
48
+ case '--overwrite':
49
+ overwrite = true;
50
+ args.shift();
51
+ break;
52
+ case '--yes':
53
+ overwrite = true;
54
+ ignoreExpoRouterMissing = true;
55
+ env.EXPO_NO_GIT_STATUS = true;
56
+ args.shift();
57
+ break;
58
+ case '--directory':
59
+ case '-d':
60
+ args.shift();
61
+ const exists = await fs.access(path.resolve(args[0]))
62
+ .then(() => true)
63
+ .catch(() => false);
64
+ if (!exists) {
65
+ throw 'provided directory does not exist.';
66
+ }
67
+ directory = args[0];
68
+ args.shift();
69
+ break;
70
+ default:
71
+ break;
72
+ }
73
+ }
74
+ // remaining args are components
75
+ await installComponent(args, overwrite, directory, bigExamplesWithDependencies, ignoreExpoRouterMissing, noInstall, quiet);
76
+ break;
77
+ case 'init':
78
+ const manualInstallationURL = `${env.API_BASE_URL}/installation/manual`;
79
+ if (!quiet) {
80
+ console.log(`To setup NativeWind UI, follow the instructions at ${manualInstallationURL}`);
81
+ const goThereNow = await confirm({ message: 'Go there now?' });
82
+ if (goThereNow) {
83
+ open(manualInstallationURL);
84
+ }
85
+ }
86
+ break;
87
+ case 'login':
88
+ if (!quiet) {
89
+ if (await isLoggedIn()) {
90
+ const shouldLoginAgain = await confirm({ message: "You are already logged in. Login again?" });
91
+ if (!shouldLoginAgain) {
92
+ return;
93
+ }
94
+ }
95
+ }
96
+ await login(quiet);
97
+ break;
98
+ default:
99
+ if (!quiet) {
100
+ console.log('Usage:');
101
+ console.log("\tadd [--overwrite] [-d directory] [--yes] [--no-install] [--quiet | -q] [componentName | 'all' | 'free' | 'paid' | 'screens' [...]]");
102
+ console.log("\tinit [--quiet | -q]");
103
+ console.log("\tlogin [--quiet | -q]");
104
+ console.log("");
105
+ }
106
+ break;
107
+ }
108
+ process.exit(0);
109
+ }
110
+ catch (err) {
111
+ if (typeof err === 'string') {
112
+ if (!quiet) {
113
+ console.error(err);
114
+ }
115
+ }
116
+ else {
117
+ throw err;
118
+ }
119
+ }
120
+ };
121
+ main().catch((error) => {
122
+ if (error instanceof Error || (typeof error == 'string' && error !== '')) {
123
+ console.error(`${color.red(color.bold('error:'))}`, error);
124
+ }
125
+ else {
126
+ console.error(`${color.red(color.bold('error:'))} an unknown error occurred`);
127
+ }
128
+ console.error(`\nIf you believe this is a bug, please open a ticket at https://github.com/ronintechnologies/nativewindui/issues`);
129
+ console.error(`\nIf you need assistance, join the Ronin discord: https://discord.gg/xeCrcU98\n`);
130
+ process.exit(1);
131
+ });
@@ -0,0 +1,513 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { execa } from 'execa';
4
+ import ora from 'ora';
5
+ import memoizee from 'memoizee';
6
+ import { fetch, supabase } from './net.js';
7
+ import { env } from './utils/env.js';
8
+ import * as git from './utils/git.js';
9
+ import { isLoggedIn, login } from './login.js';
10
+ import { confirmAsync } from './utils/prompts.js';
11
+ export const installComponent = async (slugs, overwrite = false, directory = `.${path.sep}`, bigExamplesWithDependencies = false, ignoreExpoRouterMissing = false, noInstall = false, quiet = false) => {
12
+ const cwd = path.resolve(directory);
13
+ let spinner = ora({ text: 'Fetching component metadata...', isSilent: quiet });
14
+ if (!quiet)
15
+ spinner.start();
16
+ const componentsListing = await fetchComponentsListing();
17
+ const paidComponentSlugs = componentsListing
18
+ .filter((component) => !component.free)
19
+ .map((component) => component.slug);
20
+ const componentSlugs = new Set((await Promise.all(slugs.map(async (slug) => {
21
+ if (['paid', 'free', 'all'].includes(slug)) {
22
+ let components = componentsListing
23
+ .slice()
24
+ .filter((component) => component.type !== 'screen');
25
+ if (slug !== 'all') {
26
+ components = components.filter((component) => component.free === (slug === 'free'));
27
+ }
28
+ return components.map((component) => component.slug);
29
+ }
30
+ if (slug === 'screens') {
31
+ return componentsListing
32
+ .filter((component) => component.type === 'screen')
33
+ .map((component) => component.slug);
34
+ }
35
+ return [slug];
36
+ }))).flat());
37
+ if (Array.from(componentSlugs).some((slug) => paidComponentSlugs.includes(slug)) &&
38
+ !(await isLoggedIn())) {
39
+ if (!quiet)
40
+ spinner.stop();
41
+ if (!(await askAndLogin(quiet))) {
42
+ throw 'unauthenticated';
43
+ }
44
+ }
45
+ if (!quiet)
46
+ spinner.stopAndPersist({ text: 'Received component metadata.' });
47
+ spinner = ora({ text: 'Checking for expo-router...', isSilent: quiet });
48
+ if (!quiet)
49
+ spinner.start();
50
+ // ensure expo router
51
+ try {
52
+ await execa('npm', ['ls', 'expo-router'], { cwd });
53
+ // in a monorepo, we may have expo-router in scope but no app/ directory.
54
+ await fs.access(path.join(cwd, `app${path.sep}`));
55
+ if (!quiet)
56
+ spinner.stopAndPersist({ text: 'Found expo-router.' });
57
+ }
58
+ catch (err) {
59
+ if (!quiet)
60
+ spinner.stop();
61
+ if (err?.code === 'ENOENT' || err?.exitCode === 1) {
62
+ if (!ignoreExpoRouterMissing) {
63
+ const confirmation = await confirmAsync({
64
+ message: `The working directory provided does not appear to be an expo-router project. Continue anyway?`,
65
+ });
66
+ if (!confirmation) {
67
+ throw 'aborted';
68
+ }
69
+ }
70
+ if (!quiet)
71
+ spinner.stopAndPersist({ text: 'Ignored expo-router.' });
72
+ }
73
+ else {
74
+ if (!quiet)
75
+ console.error('error:', err);
76
+ throw err;
77
+ }
78
+ }
79
+ try {
80
+ git.setCwd(cwd);
81
+ if (await git.maybeBailOnGitStatusAsync()) {
82
+ return;
83
+ }
84
+ }
85
+ catch (err) {
86
+ if (!quiet)
87
+ console.error('error checking git:', err);
88
+ return;
89
+ }
90
+ const resolved = await getRecursiveComponentDependencies(componentSlugs, bigExamplesWithDependencies);
91
+ if (env.NODE_ENV === 'development') {
92
+ console.log('components:', componentSlugs);
93
+ console.log('resolution:', resolved);
94
+ }
95
+ // install primitives && libraries via `npx expo install`
96
+ spinner = ora({ text: 'Installing libraries and primitives...', isSilent: quiet });
97
+ if (!quiet)
98
+ spinner.start();
99
+ const libs = Array.from(resolved.libraries).concat(Array.from(resolved.primitives));
100
+ if (libs.length > 0) {
101
+ try {
102
+ const npxArgs = ['expo', 'install'];
103
+ // speed up invocation
104
+ const fastNpmInstallArgs = [
105
+ '--silent',
106
+ '--no-audit',
107
+ '--progress=false',
108
+ '--legacy-peer-deps',
109
+ ];
110
+ // conditionally for --no-install (see below)
111
+ let removePackageLock = false;
112
+ let removeNodeModules = false;
113
+ if (noInstall) {
114
+ npxArgs.push('--npm', ...libs, ...[
115
+ '--',
116
+ // prevent downloading & writing node_modules
117
+ '--package-lock-only',
118
+ '--no-package-lock',
119
+ ...fastNpmInstallArgs,
120
+ ]);
121
+ if (env.NODE_ENV === 'development') {
122
+ console.log('lockfile:', resolveNormalizedPath(cwd, 'package-lock.json'));
123
+ }
124
+ // some versions of npm will create/modify the lockfile with these args, others won't.
125
+ const packageLockExists = await fs
126
+ .access(resolveNormalizedPath(cwd, 'package-lock.json'))
127
+ .then(() => true)
128
+ .catch(() => false);
129
+ // if a lockfile doesn't exist before we get started, delete it afterward.
130
+ // we do this because we don't know the user's preferred package manager.
131
+ if (!packageLockExists) {
132
+ removePackageLock = true;
133
+ }
134
+ // `expo install` will complain that `expo` isn't installed, so we need to install it first.
135
+ // Note: this seems to not happen always in testing because we generate projects in
136
+ // subdirectories of other projects (like CES and NWUI) that have Expo installed.
137
+ const nodeModulesExists = await fs
138
+ .access(resolveNormalizedPath(cwd, 'node_modules'))
139
+ .then(() => true)
140
+ .catch(() => false);
141
+ // assume if `node_modules` exists and we've already verified this is an Expo Router project
142
+ // that we don't need to install Expo; otherwise, we will install it and remove when done.
143
+ if (!nodeModulesExists) {
144
+ removeNodeModules = true;
145
+ const install = await execa('npm', ['install', ...fastNpmInstallArgs], { cwd });
146
+ if (install.exitCode !== 0) {
147
+ if (!quiet)
148
+ spinner.stop();
149
+ if (!quiet)
150
+ console.log(install.all);
151
+ if (!quiet)
152
+ console.error('command:', install.command);
153
+ throw `npx expo install failed with exit code ${install.exitCode}`;
154
+ }
155
+ }
156
+ }
157
+ else {
158
+ // detect if package manager is npm -- this assumes that the user has not deleted it before adding components
159
+ // TODO: consider using a package manager detector like https://github.com/antfu-collective/package-manager-detector and using the initial install arg as fallback (ex: `bunx nwui-cli add button` would use bun)
160
+ const packageLockExists = await fs
161
+ .access(resolveNormalizedPath(cwd, 'package-lock.json'))
162
+ .then(() => true)
163
+ .catch(() => false);
164
+ if (packageLockExists) {
165
+ npxArgs.push('--npm', ...libs, ...['--', '--legacy-peer-deps']);
166
+ }
167
+ else {
168
+ npxArgs.push(...libs);
169
+ }
170
+ }
171
+ if (env.NODE_ENV === 'development')
172
+ console.log('> npx', npxArgs);
173
+ const install = await execa('npx', npxArgs, { cwd });
174
+ if (install.exitCode !== 0) {
175
+ if (!quiet)
176
+ spinner.stop();
177
+ if (!quiet)
178
+ console.log(install.all);
179
+ if (!quiet)
180
+ console.error('command:', install.command);
181
+ throw `npx expo install failed with exit code ${install.exitCode}`;
182
+ }
183
+ if (removePackageLock) {
184
+ // older versions of `npm` will not create a package-lock.json with the args provided,
185
+ // so we use `force: true` which does not throw if the deletion fails (and nothing else).
186
+ await fs.rm(resolveNormalizedPath(cwd, 'package-lock.json'), { force: true });
187
+ if (env.NODE_ENV === 'development')
188
+ console.log('deleted package-lock.json');
189
+ }
190
+ if (removeNodeModules) {
191
+ // we installed Expo earlier when `node_modules` didn't exist, and `--no-install` was used.
192
+ await fs.rm(resolveNormalizedPath(cwd, 'node_modules'), { recursive: true, force: true });
193
+ if (env.NODE_ENV === 'development')
194
+ console.log('deleted node_modules');
195
+ }
196
+ }
197
+ catch (err) {
198
+ if (err) {
199
+ if (!quiet)
200
+ console.error(err);
201
+ throw 'npx expo install failed';
202
+ }
203
+ }
204
+ }
205
+ if (!quiet)
206
+ spinner.stopAndPersist({ text: 'Libraries and primitives successfully installed.' });
207
+ spinner = ora({ text: 'Installing component files...', isSilent: quiet });
208
+ if (!quiet)
209
+ spinner.start();
210
+ const additionalFiles = Array.from(resolved.components.entries()).flatMap(([_slug, component]) => component.additionalFiles || []);
211
+ const dirs = new Set(
212
+ // remove file name
213
+ additionalFiles.map((additionalFile) => additionalFile.path.replace(/[/][^/]*$/, '')));
214
+ // Create necessary directories
215
+ // NOTE: do not Promise.all, so users get a singular error and comprehensible output
216
+ for (const dir of dirs) {
217
+ try {
218
+ await fs.mkdir(resolveNormalizedPath(cwd, dir), { recursive: true });
219
+ }
220
+ catch (err) {
221
+ if (typeof err === 'object' && err && 'code' in err && err.code === 'EEXIST') {
222
+ throw `a file exists at the same path where a directory needs to exists: ${dir}`;
223
+ }
224
+ else {
225
+ throw err;
226
+ }
227
+ }
228
+ }
229
+ // Create the additional files
230
+ // NOTE: do not Promise.all (see above)
231
+ for (const additionalFile of additionalFiles) {
232
+ if (additionalFile.path === '~/app/_layout.tsx') {
233
+ continue;
234
+ }
235
+ const normalizedPath = resolveNormalizedPath(cwd, additionalFile.path);
236
+ if (!overwrite) {
237
+ try {
238
+ await fs.access(normalizedPath);
239
+ throw 'file exists';
240
+ }
241
+ catch (err) {
242
+ if (err === 'file exists') {
243
+ if (!quiet)
244
+ spinner.stop();
245
+ const confirmation = await confirmAsync({
246
+ message: `File at path ${additionalFile.path} already exists, overwrite it?`,
247
+ });
248
+ if (!confirmation) {
249
+ if (!quiet)
250
+ console.log('Skipped file', additionalFile.path);
251
+ if (!quiet)
252
+ spinner.start();
253
+ continue;
254
+ }
255
+ }
256
+ }
257
+ }
258
+ try {
259
+ await fs.writeFile(resolveNormalizedPath(cwd, additionalFile.path), additionalFile.code);
260
+ }
261
+ catch (err) {
262
+ throw err;
263
+ }
264
+ }
265
+ if (!quiet)
266
+ spinner.stopAndPersist({ text: 'Component files installed.' });
267
+ await deleteDeprecatedFiles(resolved, cwd, quiet);
268
+ if (bigExamplesWithDependencies) {
269
+ await installExamples(resolved, cwd, overwrite, quiet);
270
+ }
271
+ if (!quiet)
272
+ console.log('');
273
+ if (!quiet)
274
+ console.log("If you're looking to move even faster, I may be able to help!");
275
+ if (!quiet)
276
+ console.log('- dan@nativewindui.com');
277
+ };
278
+ const resolveNormalizedPath = (cwd, filePath) => {
279
+ return path.join(cwd, ...filePath.replace(/^[~][/]/, '').split('/'));
280
+ };
281
+ const deletedComponentSlugsWithReplacements = [['selectable-text', 'text']];
282
+ async function deleteDeprecatedFiles(resolved, cwd, quiet = false) {
283
+ let spinner = ora({ text: 'Cleaning up old files...', isSilent: quiet });
284
+ if (!quiet)
285
+ spinner.start();
286
+ // old examples directory
287
+ // to be as unintrusive as possible, we:
288
+ // - only delete example files associated with components requested for installation
289
+ // - delete example files associatd with components that no longer exists
290
+ // - do not assume & delete the entire `~/components/nativewindui/examples` folder
291
+ const oldExamplesDir = `~/components/nativewindui/examples`;
292
+ try {
293
+ await fs.access(resolveNormalizedPath(cwd, oldExamplesDir)).catch(() => {
294
+ if (env.NODE_ENV === 'development')
295
+ console.log('no examples folder found');
296
+ throw 'examples not found';
297
+ });
298
+ // old examples dir found, try to delete relevant example files
299
+ const exampleFileSlugs = Array.from(resolved.components.entries()).map(([slug, _component]) => slug);
300
+ // only remove deprecated components' examples if their replacement was requested for install
301
+ deletedComponentSlugsWithReplacements.forEach(([deletedSlug, replacementSlug]) => {
302
+ if (exampleFileSlugs.includes(replacementSlug)) {
303
+ exampleFileSlugs.push(deletedSlug);
304
+ }
305
+ });
306
+ // remove each relevant old example file if it exists
307
+ for (const slug of exampleFileSlugs) {
308
+ const exampleFilePath = `${oldExamplesDir}/${slug}.tsx`;
309
+ const normalizedPath = resolveNormalizedPath(cwd, exampleFilePath);
310
+ try {
311
+ // force will simply not throw errors/exceptions if the file does not exist
312
+ await fs.rm(normalizedPath, { force: true });
313
+ }
314
+ catch (err) {
315
+ // do nothing on failure
316
+ if (env.NODE_ENV === 'development') {
317
+ console.error(`error cleaning up old example file ${slug}:`, err);
318
+ }
319
+ }
320
+ }
321
+ }
322
+ catch (err) {
323
+ if (err !== 'examples not found') {
324
+ if (!quiet)
325
+ console.error('error cleaning up depreated files:', err ? err.message || err : 'unknown');
326
+ // do not re-throw, clean up is not required
327
+ }
328
+ }
329
+ if (!quiet)
330
+ spinner.stopAndPersist({ text: 'Cleaned up old files.' });
331
+ }
332
+ async function installExamples(resolved, cwd, overwrite, quiet = false) {
333
+ let spinner = ora({ text: 'Installing example files...', isSilent: quiet });
334
+ if (!quiet)
335
+ spinner.start();
336
+ // create example usage file
337
+ const examplesDir = '~/components/nativewindui-examples';
338
+ try {
339
+ await fs.mkdir(resolveNormalizedPath(cwd, examplesDir), { recursive: true });
340
+ }
341
+ catch (err) {
342
+ if (typeof err === 'object' && err && 'code' in err && err.code === 'EEXIST') {
343
+ throw `a file exists at the same path where a directory needs to exists: ${examplesDir}`;
344
+ }
345
+ else {
346
+ throw err;
347
+ }
348
+ }
349
+ const exampleFiles = Array.from(resolved.components.entries()).map(([slug, component]) => ({
350
+ slug,
351
+ code: component.type === 'component' ? component.implementationCode : null,
352
+ }));
353
+ // Create the example usage files
354
+ // NOTE: do not Promise.all (see above)
355
+ for (const exampleFile of exampleFiles) {
356
+ if (!exampleFile.code)
357
+ continue;
358
+ const exampleFilePath = `${examplesDir}/${exampleFile.slug}.tsx`;
359
+ const normalizedPath = resolveNormalizedPath(cwd, exampleFilePath);
360
+ if (!overwrite) {
361
+ try {
362
+ await fs.access(normalizedPath);
363
+ throw 'file exists';
364
+ }
365
+ catch (err) {
366
+ if (err === 'file exists') {
367
+ if (!quiet)
368
+ spinner.stop();
369
+ const confirmation = await confirmAsync({
370
+ message: `File at path ${exampleFilePath} already exists, overwrite it?`,
371
+ });
372
+ if (!confirmation) {
373
+ if (!quiet)
374
+ console.log('Skipped file', exampleFilePath);
375
+ if (!quiet)
376
+ spinner.start();
377
+ continue;
378
+ }
379
+ }
380
+ }
381
+ }
382
+ try {
383
+ await fs.writeFile(resolveNormalizedPath(cwd, exampleFilePath), exampleFile.code);
384
+ }
385
+ catch (err) {
386
+ throw err;
387
+ }
388
+ }
389
+ if (!quiet)
390
+ spinner.stopAndPersist({ text: `Example usage files installed to ${examplesDir}` });
391
+ }
392
+ async function getRecursiveComponentDependencies(componentSlugs,
393
+ // install components, primitives and libraries for the example usages if true.
394
+ bigExamplesWithDependencies) {
395
+ const components = await Promise.all(Array.from(componentSlugs).map(async (slug) => {
396
+ try {
397
+ return await fetchComponent(slug);
398
+ }
399
+ catch (err) {
400
+ console.error('error grabbing component:', err);
401
+ throw err;
402
+ }
403
+ }));
404
+ if (bigExamplesWithDependencies) {
405
+ const exampleComponentDependencies = new Set(components.flatMap((c) => {
406
+ if (c.type !== 'component')
407
+ return [];
408
+ return (c.exampleDependencies || [])
409
+ .filter((dep) => dep.type === 'component')
410
+ .filter((dep) => !componentSlugs.has(dep.name))
411
+ .map((dep) => dep.url.replace('/component/', ''));
412
+ }));
413
+ components.push(...(await Promise.all(Array.from(exampleComponentDependencies).map(async (slug) => {
414
+ try {
415
+ return await fetchComponent(slug);
416
+ }
417
+ catch (err) {
418
+ console.error('error grabbing component:', err);
419
+ throw err;
420
+ }
421
+ }))));
422
+ }
423
+ const resolved = {
424
+ libraries: new Set(),
425
+ primitives: new Set(),
426
+ components: new Map(),
427
+ };
428
+ for (const component of components) {
429
+ resolved.components.set(component.slug, component);
430
+ }
431
+ // recursively (in case of nwui components, not libraries or primitives) adds deps to resolved
432
+ async function applyDependenciesToResolved(component) {
433
+ const dependencies = component.dependencies || [];
434
+ if (bigExamplesWithDependencies && component.type === 'component') {
435
+ // do not recursively install components to prevent infinite loop
436
+ // callers of this function should add components into the components argument
437
+ dependencies.push(...(component.exampleDependencies || []).filter((dep) => dep.type != 'component'));
438
+ }
439
+ await Promise.all(dependencies.map(async (dependency) => {
440
+ switch (dependency.type) {
441
+ case 'library':
442
+ resolved.libraries.add(dependency.name);
443
+ break;
444
+ case 'primitive':
445
+ resolved.primitives.add(dependency.name);
446
+ break;
447
+ case 'component':
448
+ const slug = dependency.url.replace('/component/', '');
449
+ // do not fetch a component if we already have done so
450
+ // when fetching a component, paid components should never be a dependency of a free component, so pass secondAttempt = true
451
+ // TODO: memoize fetchComponent to remove this logic here; seems necessary for installing multiple components
452
+ const subcomponent = resolved.components.get(slug) || (await fetchComponent(slug, true));
453
+ resolved.components.set(slug, subcomponent);
454
+ await applyDependenciesToResolved(subcomponent);
455
+ break;
456
+ }
457
+ }));
458
+ }
459
+ await Promise.all(components.map(async (component) => {
460
+ await applyDependenciesToResolved(component);
461
+ }));
462
+ return resolved;
463
+ }
464
+ var fetchComponent = memoizee(async (slug, secondAttempt = false) => {
465
+ const { data: { session }, error: _error, } = await supabase.auth.getSession();
466
+ const { access_token, refresh_token } = session || {};
467
+ try {
468
+ const response = await fetch(`/api/components/${slug}`, {
469
+ headers: !(access_token && refresh_token)
470
+ ? {}
471
+ : {
472
+ access_token,
473
+ refresh_token,
474
+ },
475
+ });
476
+ if (response.status === 401)
477
+ throw 'unauthorized';
478
+ return (await response.json());
479
+ }
480
+ catch (err) {
481
+ if (err === 'unauthorized' && !secondAttempt) {
482
+ throw 'unauthorized';
483
+ }
484
+ console.error('error fetching component:', slug);
485
+ console.error(err);
486
+ throw err;
487
+ }
488
+ }, { promise: true });
489
+ var fetchComponentsListing = memoizee(async () => {
490
+ const response = await fetch('/api/components');
491
+ const metadata = await response.json();
492
+ return metadata;
493
+ });
494
+ /**
495
+ * Ask the user if they want to login, and proceeds to login if so. Returns whether the user logged in.
496
+ */
497
+ async function askAndLogin(quiet = false) {
498
+ const shouldSignIn = await confirmAsync({
499
+ message: 'To download paid components, you need to sign in to a paid account. Sign in now?',
500
+ });
501
+ if (shouldSignIn) {
502
+ try {
503
+ const success = await login(quiet);
504
+ if (success)
505
+ return true;
506
+ }
507
+ catch (err) {
508
+ if (!quiet)
509
+ console.error('error logging in:');
510
+ }
511
+ }
512
+ return false;
513
+ }