nwui-cli 0.4.10 → 0.4.11

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,498 +0,0 @@
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.slice()
23
- .filter(component => component.type !== 'screen');
24
- if (slug !== 'all') {
25
- components = components.filter(component => (component.free === (slug === 'free')));
26
- }
27
- return components.map(component => component.slug);
28
- }
29
- if (slug === 'screens') {
30
- return (componentsListing
31
- .filter(component => component.type === 'screen')
32
- .map(component => component.slug));
33
- }
34
- return [slug];
35
- }))).flat());
36
- if (Array.from(componentSlugs).some(slug => paidComponentSlugs.includes(slug)) && !(await isLoggedIn())) {
37
- if (!quiet)
38
- spinner.stop();
39
- if (!(await askAndLogin(quiet))) {
40
- throw 'unauthenticated';
41
- }
42
- }
43
- if (!quiet)
44
- spinner.stopAndPersist({ text: 'Received component metadata.' });
45
- spinner = ora({ text: 'Checking for expo-router...', isSilent: quiet });
46
- if (!quiet)
47
- spinner.start();
48
- // ensure expo router
49
- try {
50
- await execa('npm', ['ls', 'expo-router'], { cwd });
51
- // in a monorepo, we may have expo-router in scope but no app/ directory.
52
- await fs.access(path.join(cwd, `app${path.sep}`));
53
- if (!quiet)
54
- spinner.stopAndPersist({ text: "Found expo-router." });
55
- }
56
- catch (err) {
57
- if (!quiet)
58
- spinner.stop();
59
- if (err?.code === 'ENOENT' || err?.exitCode === 1) {
60
- if (!ignoreExpoRouterMissing) {
61
- const confirmation = await confirmAsync({
62
- message: `The working directory provided does not appear to be an expo-router project. Continue anyway?`,
63
- });
64
- if (!confirmation) {
65
- throw 'aborted';
66
- }
67
- }
68
- if (!quiet)
69
- spinner.stopAndPersist({ text: "Ignored expo-router." });
70
- }
71
- else {
72
- if (!quiet)
73
- console.error('error:', err);
74
- throw err;
75
- }
76
- }
77
- try {
78
- git.setCwd(cwd);
79
- if (await git.maybeBailOnGitStatusAsync()) {
80
- return;
81
- }
82
- }
83
- catch (err) {
84
- if (!quiet)
85
- console.error('error checking git:', err);
86
- return;
87
- }
88
- const resolved = await getRecursiveComponentDependencies(componentSlugs, bigExamplesWithDependencies);
89
- if (env.NODE_ENV === 'development') {
90
- console.log('components:', componentSlugs);
91
- console.log('resolution:', resolved);
92
- }
93
- // install primitives && libraries via `npx expo install`
94
- spinner = ora({ text: 'Installing libraries and primitives...', isSilent: quiet });
95
- if (!quiet)
96
- spinner.start();
97
- const libs = Array.from(resolved.libraries).concat(Array.from(resolved.primitives));
98
- if (libs.length > 0) {
99
- try {
100
- const npxArgs = ['expo', 'install'];
101
- // speed up invocation
102
- const fastNpmInstallArgs = ['--silent', '--no-audit', '--progress=false', '--legacy-peer-deps'];
103
- // conditionally for --no-install (see below)
104
- let removePackageLock = false;
105
- let removeNodeModules = false;
106
- if (noInstall) {
107
- npxArgs.push('--npm', ...libs, ...[
108
- '--',
109
- // prevent downloading & writing node_modules
110
- '--package-lock-only',
111
- '--no-package-lock',
112
- ...fastNpmInstallArgs
113
- ]);
114
- if (env.NODE_ENV === 'development') {
115
- console.log('lockfile:', resolveNormalizedPath(cwd, 'package-lock.json'));
116
- }
117
- // some versions of npm will create/modify the lockfile with these args, others won't.
118
- const packageLockExists = await fs.access(resolveNormalizedPath(cwd, 'package-lock.json'))
119
- .then(() => true)
120
- .catch(() => false);
121
- // if a lockfile doesn't exist before we get started, delete it afterward.
122
- // we do this because we don't know the user's preferred package manager.
123
- if (!packageLockExists) {
124
- removePackageLock = true;
125
- }
126
- // `expo install` will complain that `expo` isn't installed, so we need to install it first.
127
- // Note: this seems to not happen always in testing because we generate projects in
128
- // subdirectories of other projects (like CES and NWUI) that have Expo installed.
129
- const nodeModulesExists = await fs.access(resolveNormalizedPath(cwd, 'node_modules'))
130
- .then(() => true)
131
- .catch(() => false);
132
- // assume if `node_modules` exists and we've already verified this is an Expo Router project
133
- // that we don't need to install Expo; otherwise, we will install it and remove when done.
134
- if (!nodeModulesExists) {
135
- removeNodeModules = true;
136
- const install = await execa('npm', ['install', ...fastNpmInstallArgs], { cwd });
137
- if (install.exitCode !== 0) {
138
- if (!quiet)
139
- spinner.stop();
140
- if (!quiet)
141
- console.log(install.all);
142
- if (!quiet)
143
- console.error('command:', install.command);
144
- throw `npx expo install failed with exit code ${install.exitCode}`;
145
- }
146
- }
147
- }
148
- else {
149
- npxArgs.push('--npm', ...libs, ...[
150
- '--',
151
- '--legacy-peer-deps'
152
- ]);
153
- }
154
- if (env.NODE_ENV === 'development')
155
- console.log('> npx', npxArgs);
156
- const install = await execa('npx', npxArgs, { cwd });
157
- if (install.exitCode !== 0) {
158
- if (!quiet)
159
- spinner.stop();
160
- if (!quiet)
161
- console.log(install.all);
162
- if (!quiet)
163
- console.error('command:', install.command);
164
- throw `npx expo install failed with exit code ${install.exitCode}`;
165
- }
166
- if (removePackageLock) {
167
- // older versions of `npm` will not create a package-lock.json with the args provided,
168
- // so we use `force: true` which does not throw if the deletion fails (and nothing else).
169
- await fs.rm(resolveNormalizedPath(cwd, 'package-lock.json'), { force: true });
170
- if (env.NODE_ENV === 'development')
171
- console.log('deleted package-lock.json');
172
- }
173
- if (removeNodeModules) {
174
- // we installed Expo earlier when `node_modules` didn't exist, and `--no-install` was used.
175
- await fs.rm(resolveNormalizedPath(cwd, 'node_modules'), { recursive: true, force: true });
176
- if (env.NODE_ENV === 'development')
177
- console.log('deleted node_modules');
178
- }
179
- }
180
- catch (err) {
181
- if (err) {
182
- if (!quiet)
183
- console.error(err);
184
- throw 'npx expo install failed';
185
- }
186
- }
187
- }
188
- if (!quiet)
189
- spinner.stopAndPersist({ text: 'Libraries and primitives successfully installed.' });
190
- spinner = ora({ text: 'Installing component files...', isSilent: quiet });
191
- if (!quiet)
192
- spinner.start();
193
- const additionalFiles = Array.from(resolved.components.entries())
194
- .flatMap(([_slug, component]) => component.additionalFiles || []);
195
- const dirs = new Set(
196
- // remove file name
197
- additionalFiles.map(additionalFile => additionalFile.path.replace(/[/][^/]*$/, '')));
198
- // Create necessary directories
199
- // NOTE: do not Promise.all, so users get a singular error and comprehensible output
200
- for (const dir of dirs) {
201
- try {
202
- await fs.mkdir(resolveNormalizedPath(cwd, dir), { recursive: true });
203
- }
204
- catch (err) {
205
- if (typeof err === 'object' && err && 'code' in err && err.code === 'EEXIST') {
206
- throw `a file exists at the same path where a directory needs to exists: ${dir}`;
207
- }
208
- else {
209
- throw err;
210
- }
211
- }
212
- }
213
- // Create the additional files
214
- // NOTE: do not Promise.all (see above)
215
- for (const additionalFile of additionalFiles) {
216
- if (additionalFile.path === '~/app/_layout.tsx') {
217
- continue;
218
- }
219
- const normalizedPath = resolveNormalizedPath(cwd, additionalFile.path);
220
- if (!overwrite) {
221
- try {
222
- await fs.access(normalizedPath);
223
- throw 'file exists';
224
- }
225
- catch (err) {
226
- if (err === 'file exists') {
227
- if (!quiet)
228
- spinner.stop();
229
- const confirmation = await confirmAsync({
230
- message: `File at path ${additionalFile.path} already exists, overwrite it?`
231
- });
232
- if (!confirmation) {
233
- if (!quiet)
234
- console.log('Skipped file', additionalFile.path);
235
- if (!quiet)
236
- spinner.start();
237
- continue;
238
- }
239
- }
240
- }
241
- }
242
- try {
243
- await fs.writeFile(resolveNormalizedPath(cwd, additionalFile.path), additionalFile.code);
244
- }
245
- catch (err) {
246
- throw err;
247
- }
248
- }
249
- if (!quiet)
250
- spinner.stopAndPersist({ text: 'Component files installed.' });
251
- await deleteDeprecatedFiles(resolved, cwd, quiet);
252
- if (bigExamplesWithDependencies) {
253
- await installExamples(resolved, cwd, overwrite, quiet);
254
- }
255
- if (!quiet)
256
- console.log("");
257
- if (!quiet)
258
- console.log("If you're looking to move even faster, I may be able to help!");
259
- if (!quiet)
260
- console.log("- dan@nativewindui.com");
261
- };
262
- const resolveNormalizedPath = (cwd, filePath) => {
263
- return path.join(cwd, ...filePath.replace(/^[~][/]/, '').split('/'));
264
- };
265
- const deletedComponentSlugsWithReplacements = [
266
- ['selectable-text', 'text']
267
- ];
268
- async function deleteDeprecatedFiles(resolved, cwd, quiet = false) {
269
- let spinner = ora({ text: 'Cleaning up old files...', isSilent: quiet });
270
- if (!quiet)
271
- spinner.start();
272
- // old examples directory
273
- // to be as unintrusive as possible, we:
274
- // - only delete example files associated with components requested for installation
275
- // - delete example files associatd with components that no longer exists
276
- // - do not assume & delete the entire `~/components/nativewindui/examples` folder
277
- const oldExamplesDir = `~/components/nativewindui/examples`;
278
- try {
279
- await fs.access(resolveNormalizedPath(cwd, oldExamplesDir)).catch(() => {
280
- if (env.NODE_ENV === 'development')
281
- console.log('no examples folder found');
282
- throw 'examples not found';
283
- });
284
- // old examples dir found, try to delete relevant example files
285
- const exampleFileSlugs = Array.from(resolved.components.entries())
286
- .map(([slug, _component]) => slug);
287
- // only remove deprecated components' examples if their replacement was requested for install
288
- deletedComponentSlugsWithReplacements.forEach(([deletedSlug, replacementSlug]) => {
289
- if (exampleFileSlugs.includes(replacementSlug)) {
290
- exampleFileSlugs.push(deletedSlug);
291
- }
292
- });
293
- // remove each relevant old example file if it exists
294
- for (const slug of exampleFileSlugs) {
295
- const exampleFilePath = `${oldExamplesDir}/${slug}.tsx`;
296
- const normalizedPath = resolveNormalizedPath(cwd, exampleFilePath);
297
- try {
298
- // force will simply not throw errors/exceptions if the file does not exist
299
- await fs.rm(normalizedPath, { force: true });
300
- }
301
- catch (err) {
302
- // do nothing on failure
303
- if (env.NODE_ENV === 'development') {
304
- console.error(`error cleaning up old example file ${slug}:`, err);
305
- }
306
- }
307
- }
308
- }
309
- catch (err) {
310
- if (err !== 'examples not found') {
311
- if (!quiet)
312
- console.error('error cleaning up depreated files:', err ? (err.message || err) : 'unknown');
313
- // do not re-throw, clean up is not required
314
- }
315
- }
316
- if (!quiet)
317
- spinner.stopAndPersist({ text: 'Cleaned up old files.' });
318
- }
319
- async function installExamples(resolved, cwd, overwrite, quiet = false) {
320
- let spinner = ora({ text: 'Installing example files...', isSilent: quiet });
321
- if (!quiet)
322
- spinner.start();
323
- // create example usage file
324
- const examplesDir = '~/components/nativewindui-examples';
325
- try {
326
- await fs.mkdir(resolveNormalizedPath(cwd, examplesDir), { recursive: true });
327
- }
328
- catch (err) {
329
- if (typeof err === 'object' && err && 'code' in err && err.code === 'EEXIST') {
330
- throw `a file exists at the same path where a directory needs to exists: ${examplesDir}`;
331
- }
332
- else {
333
- throw err;
334
- }
335
- }
336
- const exampleFiles = Array.from(resolved.components.entries()).map(([slug, component]) => ({
337
- slug,
338
- code: component.type === "component" ? component.implementationCode : null,
339
- }));
340
- // Create the example usage files
341
- // NOTE: do not Promise.all (see above)
342
- for (const exampleFile of exampleFiles) {
343
- if (!exampleFile.code)
344
- continue;
345
- const exampleFilePath = `${examplesDir}/${exampleFile.slug}.tsx`;
346
- const normalizedPath = resolveNormalizedPath(cwd, exampleFilePath);
347
- if (!overwrite) {
348
- try {
349
- await fs.access(normalizedPath);
350
- throw 'file exists';
351
- }
352
- catch (err) {
353
- if (err === 'file exists') {
354
- if (!quiet)
355
- spinner.stop();
356
- const confirmation = await confirmAsync({
357
- message: `File at path ${exampleFilePath} already exists, overwrite it?`
358
- });
359
- if (!confirmation) {
360
- if (!quiet)
361
- console.log('Skipped file', exampleFilePath);
362
- if (!quiet)
363
- spinner.start();
364
- continue;
365
- }
366
- }
367
- }
368
- }
369
- try {
370
- await fs.writeFile(resolveNormalizedPath(cwd, exampleFilePath), exampleFile.code);
371
- }
372
- catch (err) {
373
- throw err;
374
- }
375
- }
376
- if (!quiet)
377
- spinner.stopAndPersist({ text: `Example usage files installed to ${examplesDir}` });
378
- }
379
- async function getRecursiveComponentDependencies(componentSlugs,
380
- // install components, primitives and libraries for the example usages if true.
381
- bigExamplesWithDependencies) {
382
- const components = await Promise.all(Array.from(componentSlugs).map(async (slug) => {
383
- try {
384
- return await fetchComponent(slug);
385
- }
386
- catch (err) {
387
- console.error('error grabbing component:', err);
388
- throw err;
389
- }
390
- }));
391
- if (bigExamplesWithDependencies) {
392
- const exampleComponentDependencies = new Set(components.flatMap((c) => {
393
- if (c.type !== 'component')
394
- return [];
395
- return (c.exampleDependencies || [])
396
- .filter(dep => dep.type === 'component')
397
- .filter(dep => !componentSlugs.has(dep.name))
398
- .map(dep => dep.url.replace('/component/', ''));
399
- }));
400
- components.push(...(await Promise.all(Array.from(exampleComponentDependencies).map(async (slug) => {
401
- try {
402
- return await fetchComponent(slug);
403
- }
404
- catch (err) {
405
- console.error('error grabbing component:', err);
406
- throw err;
407
- }
408
- }))));
409
- }
410
- const resolved = {
411
- libraries: new Set(),
412
- primitives: new Set(),
413
- components: new Map(),
414
- };
415
- for (const component of components) {
416
- resolved.components.set(component.slug, component);
417
- }
418
- // recursively (in case of nwui components, not libraries or primitives) adds deps to resolved
419
- async function applyDependenciesToResolved(component) {
420
- const dependencies = component.dependencies || [];
421
- if (bigExamplesWithDependencies && component.type === 'component') {
422
- // do not recursively install components to prevent infinite loop
423
- // callers of this function should add components into the components argument
424
- dependencies.push(...((component.exampleDependencies || []).filter(dep => dep.type != 'component')));
425
- }
426
- await Promise.all((dependencies).map(async (dependency) => {
427
- switch (dependency.type) {
428
- case 'library':
429
- resolved.libraries.add(dependency.name);
430
- break;
431
- case 'primitive':
432
- resolved.primitives.add(dependency.name);
433
- break;
434
- case 'component':
435
- const slug = dependency.url.replace('/component/', '');
436
- // do not fetch a component if we already have done so
437
- // when fetching a component, paid components should never be a dependency of a free component, so pass secondAttempt = true
438
- // TODO: memoize fetchComponent to remove this logic here; seems necessary for installing multiple components
439
- const subcomponent = resolved.components.get(slug) || await fetchComponent(slug, true);
440
- resolved.components.set(slug, subcomponent);
441
- await applyDependenciesToResolved(subcomponent);
442
- break;
443
- }
444
- }));
445
- }
446
- await Promise.all(components.map(async (component) => {
447
- await applyDependenciesToResolved(component);
448
- }));
449
- return resolved;
450
- }
451
- var fetchComponent = memoizee(async (slug, secondAttempt = false) => {
452
- const { data: { session }, error: _error } = await supabase.auth.getSession();
453
- const { access_token, refresh_token } = session || {};
454
- try {
455
- const response = await fetch(`/api/components/${slug}`, {
456
- headers: !(access_token && refresh_token) ? {} : {
457
- access_token,
458
- refresh_token,
459
- },
460
- });
461
- if (response.status === 401)
462
- throw 'unauthorized';
463
- return await response.json();
464
- }
465
- catch (err) {
466
- if (err === 'unauthorized' && !secondAttempt) {
467
- throw 'unauthorized';
468
- }
469
- console.error('error fetching component:', slug);
470
- console.error(err);
471
- throw err;
472
- }
473
- }, { promise: true });
474
- var fetchComponentsListing = memoizee(async () => {
475
- const response = await fetch('/api/components');
476
- const metadata = await response.json();
477
- return metadata;
478
- });
479
- /**
480
- * Ask the user if they want to login, and proceeds to login if so. Returns whether the user logged in.
481
- */
482
- async function askAndLogin(quiet = false) {
483
- const shouldSignIn = await confirmAsync({
484
- message: 'To download paid components, you need to sign in to a paid account. Sign in now?',
485
- });
486
- if (shouldSignIn) {
487
- try {
488
- const success = await login(quiet);
489
- if (success)
490
- return true;
491
- }
492
- catch (err) {
493
- if (!quiet)
494
- console.error('error logging in:');
495
- }
496
- }
497
- return false;
498
- }
package/build/log.js DELETED
@@ -1,81 +0,0 @@
1
- // Source: https://github.com/expo/expo/blob/474a7a4/packages/%40expo/cli/src/log.ts
2
- //
3
- // The MIT License (MIT)
4
- //
5
- // Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
6
- //
7
- // Permission is hereby granted, free of charge, to any person obtaining a copy
8
- // of this software and associated documentation files (the "Software"), to deal
9
- // in the Software without restriction, including without limitation the rights
10
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- // copies of the Software, and to permit persons to whom the Software is
12
- // furnished to do so, subject to the following conditions:
13
- //
14
- // The above copyright notice and this permission notice shall be included in all
15
- // copies or substantial portions of the Software.
16
- //
17
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- // SOFTWARE.
24
- import chalk from 'chalk';
25
- export function time(label) {
26
- console.time(label);
27
- }
28
- export function timeEnd(label) {
29
- console.timeEnd(label);
30
- }
31
- export function error(...message) {
32
- console.error(...message);
33
- }
34
- /** Print an error and provide additional info (the stack trace) in debug mode. */
35
- export function exception(e) {
36
- const { env } = require('./utils/env');
37
- error(chalk.red(e.toString()) + (env.EXPO_DEBUG ? '\n' + chalk.gray(e.stack) : ''));
38
- }
39
- export function warn(...message) {
40
- console.warn(...message.map((value) => chalk.yellow(value)));
41
- }
42
- export function log(...message) {
43
- console.log(...message);
44
- }
45
- /** @deprecated use `debug` package with the `expo:` prefix instead. */
46
- export function debug(...message) {
47
- if (require('./utils/env').env.EXPO_DEBUG)
48
- console.log(...message);
49
- }
50
- /** Clear the terminal of all text. */
51
- export function clear() {
52
- process.stdout.write(process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H');
53
- }
54
- /** Log a message and exit the current process. If the `code` is non-zero then `console.error` will be used instead of `console.log`. */
55
- export function exit(message, code = 1) {
56
- if (message instanceof Error) {
57
- exception(message);
58
- process.exit(code);
59
- }
60
- if (message) {
61
- if (code === 0) {
62
- log(message);
63
- }
64
- else {
65
- error(message);
66
- }
67
- }
68
- process.exit(code);
69
- }
70
- // The re-export makes auto importing easier.
71
- export const Log = {
72
- time,
73
- timeEnd,
74
- error,
75
- exception,
76
- warn,
77
- log,
78
- debug,
79
- clear,
80
- exit,
81
- };
package/build/login.js DELETED
@@ -1,103 +0,0 @@
1
- import ora from 'ora';
2
- import { open, supabase } from './net.js';
3
- /**
4
- * Checks if this device has a session, i.e. for an anonymous Supabase user, and refreshes tokens to ensure the (anonymous) account still exists.
5
- */
6
- export const checkAndRefreshSession = async () => {
7
- const { data: { user }, error: getUserError } = await supabase.auth.getUser();
8
- if (getUserError || !user) {
9
- return false;
10
- }
11
- const { data: { session }, error: getSessionError } = await supabase.auth.getSession();
12
- if (getSessionError || !session) {
13
- return false;
14
- }
15
- return { user, session };
16
- };
17
- /**
18
- * Whether this device has an anonymous Supabase user that's also linked to a real Supabase user.
19
- * Also has the side-effect of refreshing the access token via checkAndRefreshSession.
20
- *
21
- * TODO: should this ensure the user_id is valid?
22
- * although RLS ensures this at creation, it doesn't prevent deleted REAL user accounts (a small edge-case).
23
- */
24
- export const isLoggedIn = async () => {
25
- const { user } = (await checkAndRefreshSession()) || {};
26
- if (!user) {
27
- return false;
28
- }
29
- const { data, error } = await supabase.from('session')
30
- .select('*')
31
- .eq('anon_id', user.id)
32
- .limit(1)
33
- .maybeSingle();
34
- if (!error && data && data.user_id && data.user_id.length > 0) {
35
- return true;
36
- }
37
- };
38
- /**
39
- * Creates a new anonymous user and opens the web browser for the user to link their real account.
40
- *
41
- * Returns whether login was successful/completed, but also may throw for some login failures.
42
- */
43
- export const login = async (quiet = false, secondAttempt = false) => {
44
- let { user, session } = await checkAndRefreshSession() || { user: null, session: null };
45
- if (!user || !session) {
46
- const { data, error } = await supabase.auth.signInAnonymously();
47
- if (error || user === null || session === null) {
48
- if (!secondAttempt && error === null && user === null && session === null) {
49
- // likely supabase/localStorage emulation layer having a weird incompatibility
50
- // occurs when the localStorage has not yet been persisted to disk
51
- if (process.env['NODE_ENV'] === 'development') {
52
- console.error('failure to do signInAnonymously (maybe storage issue?), retrying...');
53
- }
54
- // after the error occurs, an empty localStorage has been persisted on disk, so retry once
55
- return login(quiet, true);
56
- }
57
- throw error;
58
- }
59
- user = data.user;
60
- session = data.session;
61
- }
62
- const { access_token, refresh_token } = session;
63
- await open(`/cli?access_token=${access_token}&refresh_token=${refresh_token}`);
64
- const spinner = ora({ text: "Waiting for you to authenticate in the browser...", isSilent: quiet });
65
- if (!quiet)
66
- spinner.start();
67
- supabase.realtime.setAuth(access_token);
68
- const channel = supabase.channel(user.id, { config: { broadcast: { self: true }, private: true } });
69
- const failed = !(await new Promise((resolve, reject) => {
70
- if (process.env['NODE_ENV'] === 'development')
71
- console.log('user id:', user.id);
72
- const subscription = channel
73
- .on('broadcast', { event: 'session-created' }, (_payload) => {
74
- if (process.env['NODE_ENV'] === 'development')
75
- console.log('payload:', _payload);
76
- subscription.unsubscribe();
77
- resolve(true);
78
- })
79
- .subscribe((_status, err) => {
80
- if (process.env['NODE_ENV'] === 'development') {
81
- console.log('status:', _status);
82
- console.error('err:', err);
83
- }
84
- if (err) {
85
- try {
86
- subscription.unsubscribe();
87
- }
88
- catch (_err) { }
89
- reject(err);
90
- }
91
- });
92
- }));
93
- channel.unsubscribe();
94
- if (failed) {
95
- if (!quiet)
96
- spinner.stop();
97
- }
98
- else {
99
- if (!quiet)
100
- spinner.stopAndPersist({ text: "Successfully logged in." });
101
- }
102
- return !failed;
103
- };