nwui-cli 0.3.5

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.
package/build/index.js ADDED
@@ -0,0 +1,93 @@
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
+ try {
13
+ await renderTitle();
14
+ }
15
+ catch (_err) {
16
+ console.log(`\n${color.blue('welcome to the')} ${color.cyan('nativewindui cli')}`);
17
+ }
18
+ try {
19
+ switch (process.argv[2]) {
20
+ case 'add':
21
+ const args = process.argv.slice(3);
22
+ let overwrite = false;
23
+ let directory = undefined;
24
+ while (['--overwrite', '-d'].includes(args[0])) {
25
+ switch (args[0]) {
26
+ case '--overwrite':
27
+ overwrite = true;
28
+ args.shift();
29
+ break;
30
+ case '-d':
31
+ args.shift();
32
+ const exists = await fs.access(path.resolve(args[0]))
33
+ .then(() => true)
34
+ .catch(() => false);
35
+ if (!exists) {
36
+ throw 'provided directory does not exist.';
37
+ }
38
+ directory = args[0];
39
+ args.shift();
40
+ break;
41
+ default:
42
+ break;
43
+ }
44
+ }
45
+ // remaining args are components
46
+ await installComponent(args, overwrite, directory);
47
+ break;
48
+ case 'init':
49
+ const manualInstallationURL = `${env.API_BASE_URL}/installation/manual`;
50
+ console.log(`To setup NativeWind UI, follow the instructions at ${manualInstallationURL}`);
51
+ const goThereNow = await confirm({ message: 'Go there now?' });
52
+ if (goThereNow) {
53
+ open(manualInstallationURL);
54
+ }
55
+ break;
56
+ case 'login':
57
+ if (await isLoggedIn()) {
58
+ const shouldLoginAgain = await confirm({ message: "You are already logged in. Login again?" });
59
+ if (!shouldLoginAgain) {
60
+ return;
61
+ }
62
+ }
63
+ await login();
64
+ break;
65
+ default:
66
+ console.log('Usage:');
67
+ console.log("\tadd [--overwrite] [-d directory] [componentName | 'all' | 'free' | 'paid' | 'screens' [...]]");
68
+ console.log("\tinit");
69
+ console.log("\tlogin");
70
+ console.log("");
71
+ }
72
+ process.exit(0);
73
+ }
74
+ catch (err) {
75
+ if (typeof err === 'string') {
76
+ console.error(err);
77
+ }
78
+ else {
79
+ throw err;
80
+ }
81
+ }
82
+ };
83
+ main().catch((error) => {
84
+ if (error instanceof Error || (typeof error == 'string' && error !== '')) {
85
+ console.error(`${color.red(color.bold('error:'))}`, error);
86
+ }
87
+ else {
88
+ console.error(`${color.red(color.bold('error:'))} an unknown error occurred`);
89
+ }
90
+ console.error(`\nIf you believe this is a bug, please open a ticket at https://github.com/ronintechnologies/nativewindui/issues`);
91
+ console.error(`\nIf you need assistance, join the Ronin discord: https://discord.gg/xeCrcU98\n`);
92
+ process.exit(1);
93
+ });
@@ -0,0 +1,308 @@
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}`) => {
12
+ const cwd = path.resolve(directory);
13
+ let spinner = ora({ text: 'Fetching component metadata...' });
14
+ spinner.start();
15
+ const componentsListing = await fetchComponentsListing();
16
+ const paidComponentSlugs = componentsListing
17
+ .filter(component => !component.free)
18
+ .map(component => component.slug);
19
+ const componentSlugs = new Set((await Promise.all(slugs.map(async (slug) => {
20
+ if (['paid', 'free', 'all'].includes(slug)) {
21
+ let components = componentsListing.slice()
22
+ .filter(component => component.type !== 'screen');
23
+ if (slug !== 'all') {
24
+ components = components.filter(component => (component.free === (slug === 'free')));
25
+ }
26
+ return components.map(component => component.slug);
27
+ }
28
+ if (slug === 'screens') {
29
+ return (componentsListing
30
+ .filter(component => component.type === 'screen')
31
+ .map(component => component.slug));
32
+ }
33
+ return [slug];
34
+ }))).flat());
35
+ if (Array.from(componentSlugs).some(slug => paidComponentSlugs.includes(slug)) && !(await isLoggedIn())) {
36
+ spinner.stop();
37
+ if (!(await askAndLogin())) {
38
+ throw 'unauthenticated';
39
+ }
40
+ }
41
+ spinner.stopAndPersist({ text: 'Received component metadata.' });
42
+ spinner = ora({ text: 'Checking for expo-router...' });
43
+ spinner.start();
44
+ // ensure expo router
45
+ try {
46
+ await execa('npm', ['ls', 'expo-router'], { cwd });
47
+ // in a monorepo, we may have expo-router in scope but no app/ directory.
48
+ await fs.access(path.join(cwd, `app${path.sep}`));
49
+ spinner.stopAndPersist({ text: "Found expo-router." });
50
+ }
51
+ catch (err) {
52
+ spinner.stop();
53
+ console.error('error:', err);
54
+ if (err?.code === 'ENOENT' || err?.exitCode === 1) {
55
+ const confirmation = await confirmAsync({
56
+ message: `The working directory provided does not appear to be an expo-router project. Continue anyway?`,
57
+ });
58
+ if (!confirmation) {
59
+ throw 'aborted';
60
+ }
61
+ spinner.stopAndPersist({ text: "Ignored expo-router." });
62
+ }
63
+ else {
64
+ console.error('error:', err);
65
+ throw err;
66
+ }
67
+ }
68
+ try {
69
+ git.setCwd(cwd);
70
+ if (await git.maybeBailOnGitStatusAsync()) {
71
+ return;
72
+ }
73
+ }
74
+ catch (err) {
75
+ console.error('error checking git:', err);
76
+ return;
77
+ }
78
+ const components = await Promise.all(Array.from(componentSlugs).map(async (slug) => {
79
+ try {
80
+ return await fetchComponent(slug);
81
+ }
82
+ catch (err) {
83
+ console.error('error grabbing component:', err);
84
+ throw err;
85
+ }
86
+ }));
87
+ const resolved = await getRecursiveComponentDependencies(components);
88
+ if (env.NODE_ENV === 'development') {
89
+ console.log('components:', componentSlugs);
90
+ console.log('resolution:', resolved);
91
+ }
92
+ // install primitives && libraries via `npx expo install`
93
+ spinner = ora({ text: 'Installing libraries and primitives...' });
94
+ spinner.start();
95
+ const libs = Array.from(resolved.libraries).concat(Array.from(resolved.primitives));
96
+ if (libs.length > 0) {
97
+ try {
98
+ const install = await execa('npx', ['expo', 'install'].concat(libs), { cwd });
99
+ if (install.exitCode !== 0) {
100
+ console.log(install.all);
101
+ spinner.stop();
102
+ console.error('command:', install.command);
103
+ throw `npx expo install failed with exit code ${install.exitCode}`;
104
+ }
105
+ }
106
+ catch (err) {
107
+ if (err) {
108
+ console.error(err);
109
+ throw 'npx expo install failed';
110
+ }
111
+ }
112
+ }
113
+ spinner.stopAndPersist({ text: 'Libraries and primitives successfully installed.' });
114
+ spinner = ora({ text: 'Installing component files...' });
115
+ spinner.start();
116
+ const additionalFiles = Array.from(resolved.components.entries())
117
+ .flatMap(([_slug, component]) => component.additionalFiles || []);
118
+ const dirs = new Set(
119
+ // remove file name
120
+ additionalFiles.map(additionalFile => additionalFile.path.replace(/[/][^/]*$/, '')));
121
+ const resolveNormalizedPath = (filePath) => {
122
+ return path.join(cwd, ...filePath.replace(/^[~][/]/, '').split('/'));
123
+ };
124
+ // Create necessary directories
125
+ // NOTE: do not Promise.all, so users get a singular error and comprehensible output
126
+ for (const dir of dirs) {
127
+ try {
128
+ await fs.mkdir(resolveNormalizedPath(dir), { recursive: true });
129
+ }
130
+ catch (err) {
131
+ if (typeof err === 'object' && err && 'code' in err && err.code === 'EEXIST') {
132
+ throw `a file exists at the same path where a directory needs to exists: ${dir}`;
133
+ }
134
+ else {
135
+ throw err;
136
+ }
137
+ }
138
+ }
139
+ // Create the additional files
140
+ // NOTE: do not Promise.all (see above)
141
+ for (const additionalFile of additionalFiles) {
142
+ if (additionalFile.path === '~/app/_layout.tsx') {
143
+ continue;
144
+ }
145
+ const normalizedPath = resolveNormalizedPath(additionalFile.path);
146
+ if (!overwrite) {
147
+ try {
148
+ await fs.access(normalizedPath);
149
+ throw 'file exists';
150
+ }
151
+ catch (err) {
152
+ if (err === 'file exists') {
153
+ spinner.stop();
154
+ const confirmation = await confirmAsync({
155
+ message: `File at path ${additionalFile.path} already exists, overwrite it?`
156
+ });
157
+ if (!confirmation) {
158
+ console.log('Skipped file', additionalFile.path);
159
+ spinner.start();
160
+ continue;
161
+ }
162
+ }
163
+ }
164
+ }
165
+ try {
166
+ await fs.writeFile(resolveNormalizedPath(additionalFile.path), additionalFile.code);
167
+ }
168
+ catch (err) {
169
+ throw err;
170
+ }
171
+ }
172
+ spinner.stopAndPersist({ text: 'Component files installed.' });
173
+ spinner = ora({ text: 'Installing example files...' });
174
+ spinner.start();
175
+ // create example usage file
176
+ const examplesDir = '~/components/nativewindui/examples';
177
+ try {
178
+ await fs.mkdir(resolveNormalizedPath(examplesDir), { recursive: true });
179
+ }
180
+ catch (err) {
181
+ if (typeof err === 'object' && err && 'code' in err && err.code === 'EEXIST') {
182
+ throw `a file exists at the same path where a directory needs to exists: ${examplesDir}`;
183
+ }
184
+ else {
185
+ throw err;
186
+ }
187
+ }
188
+ const exampleFiles = Array.from(resolved.components.entries())
189
+ .map(([slug, component]) => ({ slug, code: component.implementationCode }));
190
+ // Create the example usage files
191
+ // NOTE: do not Promise.all (see above)
192
+ for (const exampleFile of exampleFiles) {
193
+ if (!exampleFile.code)
194
+ continue;
195
+ const exampleFilePath = `${examplesDir}/${exampleFile.slug}.tsx`;
196
+ const normalizedPath = resolveNormalizedPath(exampleFilePath);
197
+ if (!overwrite) {
198
+ try {
199
+ await fs.access(normalizedPath);
200
+ throw 'file exists';
201
+ }
202
+ catch (err) {
203
+ if (err === 'file exists') {
204
+ spinner.stop();
205
+ const confirmation = await confirmAsync({
206
+ message: `File at path ${exampleFilePath} already exists, overwrite it?`
207
+ });
208
+ if (!confirmation) {
209
+ console.log('Skipped file', exampleFilePath);
210
+ spinner.start();
211
+ continue;
212
+ }
213
+ }
214
+ }
215
+ }
216
+ try {
217
+ await fs.writeFile(resolveNormalizedPath(exampleFilePath), exampleFile.code);
218
+ }
219
+ catch (err) {
220
+ throw err;
221
+ }
222
+ }
223
+ spinner.stopAndPersist({ text: `Example usage files installed to ${examplesDir}` });
224
+ console.log("");
225
+ };
226
+ async function getRecursiveComponentDependencies(components) {
227
+ const resolved = {
228
+ libraries: new Set(),
229
+ primitives: new Set(),
230
+ components: new Map(),
231
+ };
232
+ for (const component of components) {
233
+ resolved.components.set(component.slug, component);
234
+ }
235
+ // recursively (in case of nwui components, not libraries or primitives) adds deps to resolved
236
+ async function applyDependenciesToResolved(component) {
237
+ await Promise.all((component.dependencies || []).map(async (dependency) => {
238
+ switch (dependency.type) {
239
+ case 'library':
240
+ resolved.libraries.add(dependency.name);
241
+ break;
242
+ case 'primitive':
243
+ resolved.primitives.add(dependency.name);
244
+ break;
245
+ case 'component':
246
+ const slug = dependency.url.replace('/component/', '');
247
+ // do not fetch a component if we already have done so
248
+ // when fetching a component, paid components should never be a dependency of a free component, so pass secondAttempt = true
249
+ // TODO: memoize fetchComponent to remove this logic here; seems necessary for installing multiple components
250
+ const subcomponent = resolved.components.get(slug) || await fetchComponent(slug, true);
251
+ resolved.components.set(slug, subcomponent);
252
+ await applyDependenciesToResolved(subcomponent);
253
+ break;
254
+ }
255
+ }));
256
+ }
257
+ await Promise.all(components.map(async (component) => {
258
+ await applyDependenciesToResolved(component);
259
+ }));
260
+ return resolved;
261
+ }
262
+ var fetchComponent = memoizee(async (slug, secondAttempt = false) => {
263
+ const { data: { session }, error: _error } = await supabase.auth.getSession();
264
+ const { access_token, refresh_token } = session || {};
265
+ try {
266
+ const response = await fetch(`/api/components/${slug}`, {
267
+ headers: !(access_token && refresh_token) ? {} : {
268
+ access_token,
269
+ refresh_token,
270
+ },
271
+ });
272
+ if (response.status === 401)
273
+ throw 'unauthorized';
274
+ return await response.json();
275
+ }
276
+ catch (err) {
277
+ if (err === 'unauthorized' && !secondAttempt) {
278
+ throw 'unauthorized';
279
+ }
280
+ console.error('error fetching component:', slug);
281
+ console.error(err);
282
+ throw err;
283
+ }
284
+ }, { promise: true });
285
+ var fetchComponentsListing = memoizee(async () => {
286
+ const response = await fetch('/api/components');
287
+ const metadata = await response.json();
288
+ return metadata;
289
+ });
290
+ /**
291
+ * Ask the user if they want to login, and proceeds to login if so. Returns whether the user logged in.
292
+ */
293
+ async function askAndLogin() {
294
+ const shouldSignIn = await confirmAsync({
295
+ message: 'To download paid components, you need to sign in to a paid account. Sign in now?',
296
+ });
297
+ if (shouldSignIn) {
298
+ try {
299
+ const success = await login();
300
+ if (success)
301
+ return true;
302
+ }
303
+ catch (err) {
304
+ console.error('error logging in:');
305
+ }
306
+ }
307
+ return false;
308
+ }
@@ -0,0 +1,81 @@
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/log.js ADDED
@@ -0,0 +1,81 @@
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 ADDED
@@ -0,0 +1,92 @@
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 () => {
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
+ console.error('error:', error);
49
+ throw error;
50
+ }
51
+ user = data.user;
52
+ session = data.session;
53
+ }
54
+ const { access_token, refresh_token } = session;
55
+ await open(`/cli?access_token=${access_token}&refresh_token=${refresh_token}`);
56
+ const spinner = ora({ text: "Waiting for you to authenticate in the browser..." });
57
+ spinner.start();
58
+ supabase.realtime.setAuth(access_token);
59
+ const channel = supabase.channel(user.id);
60
+ const failed = !(await new Promise((resolve, reject) => {
61
+ if (process.env.NODE_ENV === 'development')
62
+ console.log('user id:', user.id);
63
+ const subscription = channel
64
+ .on('broadcast', { event: 'session-created' }, (_payload) => {
65
+ if (process.env.NODE_ENV === 'development')
66
+ console.log('payload:', _payload);
67
+ subscription.unsubscribe();
68
+ resolve(true);
69
+ })
70
+ .subscribe((_status, err) => {
71
+ if (process.env.NODE_ENV === 'development') {
72
+ console.log('status:', _status);
73
+ console.error('err:', err);
74
+ }
75
+ if (err) {
76
+ try {
77
+ subscription.unsubscribe();
78
+ }
79
+ catch (_err) { }
80
+ reject(err);
81
+ }
82
+ });
83
+ }));
84
+ channel.unsubscribe();
85
+ if (failed) {
86
+ spinner.stop();
87
+ }
88
+ else {
89
+ spinner.stopAndPersist({ text: "Successfully logged in." });
90
+ }
91
+ return !failed;
92
+ };
package/build/net.js ADDED
@@ -0,0 +1,17 @@
1
+ import openOpen from 'open';
2
+ import { createClient } from '@supabase/supabase-js';
3
+ import { localStorage } from './utils/local-storage.js';
4
+ import { env } from './utils/env.js';
5
+ export const fetch = (urlSuffix, init) => {
6
+ return global.fetch(`${env.API_BASE_URL}${urlSuffix}`, init);
7
+ };
8
+ export const open = (urlSuffix) => {
9
+ return openOpen(`${env.API_BASE_URL}${urlSuffix}`);
10
+ };
11
+ export const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_ANON_KEY, {
12
+ 'auth': {
13
+ 'autoRefreshToken': true,
14
+ 'persistSession': true,
15
+ 'storage': localStorage('anon-user'),
16
+ },
17
+ });
@@ -0,0 +1 @@
1
+ export {};