nwui-cli 0.4.13 → 0.4.14

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/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
- };
package/build/net.js DELETED
@@ -1,17 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,38 +0,0 @@
1
- const trueish = (value) => value == 'true' || value == '1';
2
- // polyfill for Expo's `@expo/cli/src/utils/env.ts`, used by other files included in this project.
3
- class ExpoEnv {
4
- get EXPO_DEBUG() {
5
- return trueish(process.env["NWUI_DEBUG"] || "");
6
- }
7
- get EXPO_NO_GIT_STATUS() {
8
- return trueish(process.env["EXPO_NO_GIT_STATUS"] || "");
9
- }
10
- set EXPO_NO_GIT_STATUS(value) {
11
- process.env["EXPO_NO_GIT_STATUS"] = value ? "1" : "0";
12
- }
13
- get EXPO_QUIET() {
14
- return trueish(process.env["EXPO_QUIET"] || "");
15
- }
16
- set EXPO_QUIET(value) {
17
- process.env["EXPO_QUIET"] = value ? "1" : "0";
18
- }
19
- }
20
- ;
21
- class Env extends ExpoEnv {
22
- get API_BASE_URL() {
23
- return process.env["API_BASE_URL"] || (this.NODE_ENV === "development"
24
- ? 'http://localhost:3000'
25
- : 'https://nativewindui.com');
26
- }
27
- get NODE_ENV() {
28
- return process.env["NODE_ENV"] || "production";
29
- }
30
- get SUPABASE_ANON_KEY() {
31
- return process.env["SUPABASE_ANON_KEY"] || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5xdHlobWlvanZ0bGV1cGtkZWxnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTU5MDc2MDIsImV4cCI6MjAzMTQ4MzYwMn0.7tRFhmjngUKXQxiNKPPWfsjWrUB515PHtQzBSM-vN88';
32
- }
33
- get SUPABASE_URL() {
34
- return process.env["SUPABASE_URL"] || 'https://nqtyhmiojvtleupkdelg.supabase.co';
35
- }
36
- }
37
- ;
38
- export const env = new Env();
@@ -1,84 +0,0 @@
1
- import { execa } from 'execa';
2
- let cwd = undefined;
3
- export const setCwd = (dir) => { cwd = dir; };
4
- // polyfill @expo/spawn-async, overriding cwd based on above setting/setter
5
- const spawnAsync = (cmd, args) => execa(cmd, args, cwd ? { cwd } : undefined);
6
- // Source: https://github.com/expo/expo/blob/474a7a4/packages/%40expo/cli/src/utils/git.ts
7
- // Modified to avoid bundler-dependent import statements
8
- //
9
- // The MIT License (MIT)
10
- //
11
- // Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
12
- //
13
- // Permission is hereby granted, free of charge, to any person obtaining a copy
14
- // of this software and associated documentation files (the "Software"), to deal
15
- // in the Software without restriction, including without limitation the rights
16
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
- // copies of the Software, and to permit persons to whom the Software is
18
- // furnished to do so, subject to the following conditions:
19
- //
20
- // The above copyright notice and this permission notice shall be included in all
21
- // copies or substantial portions of the Software.
22
- //
23
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
- // SOFTWARE.
30
- import chalk from 'chalk';
31
- import { env } from './env.js';
32
- import { confirmAsync } from './prompts.js';
33
- import * as Log from '../log.js';
34
- export async function maybeBailOnGitStatusAsync() {
35
- const isGitStatusClean = await validateGitStatusAsync();
36
- // If status is clean, no need to check anything else
37
- if (isGitStatusClean) {
38
- return false;
39
- }
40
- // If EXPO_NO_GIT_STATUS is enabled, skip the warning and continue
41
- if (env.EXPO_NO_GIT_STATUS) {
42
- return false;
43
- }
44
- Log.log();
45
- const answer = await confirmAsync({
46
- message: `Continue with uncommited changes?`,
47
- });
48
- if (!answer) {
49
- return true;
50
- }
51
- Log.log();
52
- return false;
53
- }
54
- export async function validateGitStatusAsync() {
55
- let workingTreeStatus = 'unknown';
56
- try {
57
- const result = await spawnAsync('git', ['status', '--porcelain']);
58
- workingTreeStatus = result.stdout === '' ? 'clean' : 'dirty';
59
- }
60
- catch {
61
- // Maybe git is not installed?
62
- // Maybe this project is not using git?
63
- }
64
- if (workingTreeStatus === 'clean') {
65
- return true;
66
- }
67
- else if (workingTreeStatus === 'dirty') {
68
- if (!env.EXPO_QUIET) {
69
- logWarning('Git branch has uncommited file changes', `It's recommended to commit all changes before proceeding in case you want to revert generated changes.`);
70
- }
71
- }
72
- else {
73
- if (!env.EXPO_QUIET) {
74
- logWarning('No git repo found in current directory', `Use git to track file changes before running commands that modify project files.`);
75
- }
76
- }
77
- return false;
78
- }
79
- function logWarning(warning, hint) {
80
- if (!env.EXPO_QUIET) {
81
- Log.warn(chalk.bold `! ` + warning);
82
- Log.log(chalk.gray `\u203A ` + chalk.gray(hint));
83
- }
84
- }
@@ -1,2 +0,0 @@
1
- // polyfill for included Expo git utility, see ./git.ts
2
- export const isInteractive = () => process.stdout.isTTY;
@@ -1,19 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { LocalStorage } from 'node-localstorage';
5
- const STORAGE_DIR = path.join(os.homedir(), '.nwui/');
6
- try {
7
- fs.readdirSync(STORAGE_DIR);
8
- }
9
- catch (err) {
10
- if (typeof err == 'object' && err && 'code' in err && err.code === 'ENOENT') {
11
- fs.mkdirSync(STORAGE_DIR);
12
- }
13
- else {
14
- throw err;
15
- }
16
- }
17
- export const localStorage = (storageName) => {
18
- return new LocalStorage(path.join(STORAGE_DIR, storageName));
19
- };
@@ -1,28 +0,0 @@
1
- import figlet from 'figlet';
2
- import gradient from 'gradient-string';
3
- const TITLE_TEXT = 'NativeWindUI';
4
- // expo stack orange gradient
5
- const expoStackTheme = {
6
- orange: '#f97316',
7
- between: 'f2940f',
8
- yellow: '#eab308'
9
- };
10
- export async function renderTitle() {
11
- const cesGradient = gradient(Object.values(expoStackTheme));
12
- const data = await new Promise((resolve, reject) => {
13
- figlet.text(TITLE_TEXT, {
14
- font: 'Standard',
15
- horizontalLayout: 'fitted',
16
- verticalLayout: 'fitted',
17
- width: 80,
18
- whitespaceBreak: true
19
- }, (err, data) => {
20
- if (err) {
21
- reject('could not render');
22
- return;
23
- }
24
- resolve(cesGradient.multiline(data));
25
- });
26
- });
27
- console.log(data);
28
- }
@@ -1,138 +0,0 @@
1
- // Modified from: https://github.com/bombshell-dev/clack/blob/e8c4a3e/packages/prompts/src/index.ts
2
- //
3
- // MIT License
4
- //
5
- // Copyright (c) Nate Moore
6
- //
7
- // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
- //
9
- // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
- //
11
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12
- import { ConfirmPrompt, isCancel, SelectPrompt, TextPrompt } from "@clack/core";
13
- import isUnicodeSupported from "is-unicode-supported";
14
- import color from "picocolors";
15
- export { isCancel } from "@clack/core";
16
- const unicode = isUnicodeSupported();
17
- const s = (c, fallback) => (unicode ? c : fallback);
18
- const S_RADIO_ACTIVE = s("●", ">");
19
- const S_RADIO_INACTIVE = s("○", " ");
20
- export const text = (opts) => {
21
- return new TextPrompt({
22
- validate: opts.validate,
23
- placeholder: opts.placeholder,
24
- defaultValue: opts.defaultValue,
25
- initialValue: opts.initialValue,
26
- render() {
27
- const title = `${opts.message} \n ${"\u279C"}`;
28
- const placeholder = opts.placeholder
29
- ? color.inverse(opts.placeholder[0]) +
30
- color.dim(opts.placeholder.slice(1))
31
- : color.inverse(color.hidden("_"));
32
- const value = !this.value ? placeholder : this.valueWithCursor;
33
- switch (this.state) {
34
- case "error":
35
- return `${title.trim()} ${value}\n ${color.yellow(this.error)}\n`;
36
- case "submit":
37
- return `${title} ${color.dim(value || opts.placeholder)}`;
38
- case "cancel":
39
- return `${title} ${color.strikethrough(color.dim(value ?? ""))}${value?.trim() ? "\n" : ""}`;
40
- default:
41
- return `${title} ${value}`;
42
- }
43
- },
44
- }).prompt();
45
- };
46
- export const confirm = async (opts) => {
47
- const active = opts.active ?? "Yes";
48
- const inactive = opts.inactive ?? "No";
49
- let cancelled = false;
50
- const prompt = new ConfirmPrompt({
51
- active,
52
- inactive,
53
- initialValue: opts.initialValue ?? true,
54
- render() {
55
- const title = `${opts.message}\n`;
56
- const value = this.value ? active : inactive;
57
- switch (this.state) {
58
- case "submit":
59
- return `${title} ${color.dim(value)}\n`;
60
- case "cancel":
61
- cancelled = true;
62
- return `${title} ${color.strikethrough(color.dim(inactive))}\n`;
63
- default: {
64
- return `${title} ${this.value ? `${active}` : `${color.dim(active)}`} ${color.dim("/")} ${!this.value ? `${inactive}` : `${color.dim(inactive)}`}\n`;
65
- }
66
- }
67
- },
68
- }).prompt();
69
- const confirmation = await prompt;
70
- if (cancelled)
71
- return false;
72
- return confirmation;
73
- };
74
- // polyfill for Expo's git utility, see ./git.ts
75
- export const confirmAsync = confirm;
76
- export const select = (opts) => {
77
- const opt = (option, state) => {
78
- const label = option.label ?? String(option.value);
79
- if (state === "active") {
80
- return `${color.green(S_RADIO_ACTIVE)} ${label} ${option.hint ? color.dim(`(${option.hint})`) : ""}`;
81
- }
82
- else if (state === "selected") {
83
- return `${color.dim(label)}`;
84
- }
85
- else if (state === "cancelled") {
86
- return `${color.strikethrough(color.dim(label))}`;
87
- }
88
- return `${color.dim(S_RADIO_INACTIVE)} ${color.dim(label)}`;
89
- };
90
- return new SelectPrompt({
91
- options: opts.options,
92
- initialValue: opts.initialValue,
93
- render() {
94
- const title = `\n${opts.message}\n`;
95
- switch (this.state) {
96
- case "submit":
97
- return `${title} ${opt(this.options[this.cursor], "selected")}`;
98
- case "cancel":
99
- return `${title} ${opt(this.options[this.cursor], "cancelled")}`;
100
- default: {
101
- return `${title} ${this.options
102
- .map((option, i) => opt(option, i === this.cursor ? "active" : "inactive"))
103
- .join(`\n`)}\n \n`;
104
- }
105
- }
106
- },
107
- }).prompt();
108
- };
109
- export const cancel = (message = "") => {
110
- process.stdout.write(`${color.bold(`${color.red(message)}`)}\n\n`);
111
- };
112
- export const intro = (title = "") => {
113
- process.stdout.write(`${title}\n`);
114
- };
115
- export const outro = (message = "") => {
116
- process.stdout.write(`${message}\n\n`);
117
- };
118
- /**
119
- * Define a group of prompts to be displayed and return a results of objects within the group
120
- */
121
- export const group = async (prompts, opts) => {
122
- const results = {}; //eslint-disable-line
123
- const promptNames = Object.keys(prompts);
124
- for (const name of promptNames) {
125
- const prompt = prompts[name];
126
- //eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
127
- const result = await prompt({ results })?.catch((e) => {
128
- throw e;
129
- });
130
- if (typeof opts?.onCancel === "function" && isCancel(result)) {
131
- results[name] = "canceled"; //eslint-disable-line
132
- opts.onCancel({ results }); //eslint-disable-line
133
- continue;
134
- }
135
- results[name] = result; //eslint-disable-line
136
- }
137
- return results; //eslint-disable-line
138
- };