instant-cli 0.22.121-experimental.drewh-clief.21610676979.1 → 0.22.121

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.
Files changed (103) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/ui/index.d.ts +1 -1
  5. package/dist/ui/index.d.ts.map +1 -1
  6. package/dist/ui/index.js.map +1 -1
  7. package/dist/util/getAuthPaths.d.ts.map +1 -1
  8. package/dist/util/getAuthPaths.js.map +1 -1
  9. package/package.json +5 -14
  10. package/src/index.js +1 -1
  11. package/src/ui/index.ts +1 -1
  12. package/src/util/getAuthPaths.ts +0 -1
  13. package/tsconfig.json +2 -7
  14. package/dist/new/commands/init.d.ts +0 -9
  15. package/dist/new/commands/init.d.ts.map +0 -1
  16. package/dist/new/commands/init.js +0 -9
  17. package/dist/new/commands/init.js.map +0 -1
  18. package/dist/new/commands/initWithoutFiles.d.ts +0 -10
  19. package/dist/new/commands/initWithoutFiles.d.ts.map +0 -1
  20. package/dist/new/commands/initWithoutFiles.js +0 -36
  21. package/dist/new/commands/initWithoutFiles.js.map +0 -1
  22. package/dist/new/commands/login.d.ts +0 -9
  23. package/dist/new/commands/login.d.ts.map +0 -1
  24. package/dist/new/commands/login.js +0 -51
  25. package/dist/new/commands/login.js.map +0 -1
  26. package/dist/new/commands/logout.d.ts +0 -4
  27. package/dist/new/commands/logout.d.ts.map +0 -1
  28. package/dist/new/commands/logout.js +0 -22
  29. package/dist/new/commands/logout.js.map +0 -1
  30. package/dist/new/context/authToken.d.ts +0 -19
  31. package/dist/new/context/authToken.d.ts.map +0 -1
  32. package/dist/new/context/authToken.js +0 -51
  33. package/dist/new/context/authToken.js.map +0 -1
  34. package/dist/new/context/currentApp.d.ts +0 -36
  35. package/dist/new/context/currentApp.d.ts.map +0 -1
  36. package/dist/new/context/currentApp.js +0 -145
  37. package/dist/new/context/currentApp.js.map +0 -1
  38. package/dist/new/context/globalOpts.d.ts +0 -11
  39. package/dist/new/context/globalOpts.d.ts.map +0 -1
  40. package/dist/new/context/globalOpts.js +0 -10
  41. package/dist/new/context/globalOpts.js.map +0 -1
  42. package/dist/new/context/platformApi.d.ts +0 -19
  43. package/dist/new/context/platformApi.d.ts.map +0 -1
  44. package/dist/new/context/platformApi.js +0 -24
  45. package/dist/new/context/platformApi.js.map +0 -1
  46. package/dist/new/context/projectInfo.d.ts +0 -25
  47. package/dist/new/context/projectInfo.d.ts.map +0 -1
  48. package/dist/new/context/projectInfo.js +0 -120
  49. package/dist/new/context/projectInfo.js.map +0 -1
  50. package/dist/new/errors.d.ts +0 -10
  51. package/dist/new/errors.d.ts.map +0 -1
  52. package/dist/new/errors.js +0 -6
  53. package/dist/new/errors.js.map +0 -1
  54. package/dist/new/index.d.ts +0 -17
  55. package/dist/new/index.d.ts.map +0 -1
  56. package/dist/new/index.js +0 -159
  57. package/dist/new/index.js.map +0 -1
  58. package/dist/new/layer.d.ts +0 -15
  59. package/dist/new/layer.d.ts.map +0 -1
  60. package/dist/new/layer.js +0 -41
  61. package/dist/new/layer.js.map +0 -1
  62. package/dist/new/lib/createApp.d.ts +0 -4
  63. package/dist/new/lib/createApp.d.ts.map +0 -1
  64. package/dist/new/lib/createApp.js +0 -13
  65. package/dist/new/lib/createApp.js.map +0 -1
  66. package/dist/new/lib/handleEnv.d.ts +0 -7
  67. package/dist/new/lib/handleEnv.d.ts.map +0 -1
  68. package/dist/new/lib/handleEnv.js +0 -88
  69. package/dist/new/lib/handleEnv.js.map +0 -1
  70. package/dist/new/lib/http.d.ts +0 -15
  71. package/dist/new/lib/http.d.ts.map +0 -1
  72. package/dist/new/lib/http.js +0 -32
  73. package/dist/new/lib/http.js.map +0 -1
  74. package/dist/new/lib/login.d.ts +0 -13
  75. package/dist/new/lib/login.d.ts.map +0 -1
  76. package/dist/new/lib/login.js +0 -36
  77. package/dist/new/lib/login.js.map +0 -1
  78. package/dist/new/lib/ui.d.ts +0 -16
  79. package/dist/new/lib/ui.d.ts.map +0 -1
  80. package/dist/new/lib/ui.js +0 -30
  81. package/dist/new/lib/ui.js.map +0 -1
  82. package/dist/new/logging.d.ts +0 -3
  83. package/dist/new/logging.d.ts.map +0 -1
  84. package/dist/new/logging.js +0 -8
  85. package/dist/new/logging.js.map +0 -1
  86. package/src/new/commands/init.ts +0 -12
  87. package/src/new/commands/initWithoutFiles.ts +0 -44
  88. package/src/new/commands/login.ts +0 -73
  89. package/src/new/commands/logout.ts +0 -23
  90. package/src/new/context/authToken.ts +0 -77
  91. package/src/new/context/currentApp.ts +0 -207
  92. package/src/new/context/globalOpts.ts +0 -22
  93. package/src/new/context/platformApi.ts +0 -35
  94. package/src/new/context/projectInfo.ts +0 -172
  95. package/src/new/errors.ts +0 -7
  96. package/src/new/index.ts +0 -245
  97. package/src/new/layer.ts +0 -78
  98. package/src/new/lib/createApp.ts +0 -18
  99. package/src/new/lib/handleEnv.ts +0 -107
  100. package/src/new/lib/http.ts +0 -63
  101. package/src/new/lib/login.ts +0 -50
  102. package/src/new/lib/ui.ts +0 -45
  103. package/src/new/logging.ts +0 -9
@@ -1,35 +0,0 @@
1
- import { Data, Effect, Schema } from 'effect';
2
- import { getBaseUrl } from '../lib/http.js';
3
- import { PlatformApi as InstantPlatformApi } from '@instantdb/platform';
4
-
5
- export class PlatformApiError extends Data.TaggedError('PlatformApiError')<{
6
- message: string;
7
- cause: unknown;
8
- }> {}
9
-
10
- export class PlatformApi extends Effect.Service<PlatformApi>()(
11
- 'instant-cli/new/context/platformApi',
12
- {
13
- effect: Effect.gen(function* () {
14
- const origin = yield* getBaseUrl;
15
- const apiClient = new InstantPlatformApi({
16
- apiURI: origin,
17
- });
18
-
19
- return {
20
- use: <R>(
21
- fun: (api: typeof apiClient) => Promise<R>,
22
- errorMessage?: string,
23
- ) =>
24
- Effect.tryPromise({
25
- try: (_signal) => fun(apiClient),
26
- catch: (e) =>
27
- new PlatformApiError({
28
- message: errorMessage || 'Error using platform api',
29
- cause: e,
30
- }),
31
- }),
32
- };
33
- }),
34
- },
35
- ) {}
@@ -1,172 +0,0 @@
1
- import { Context, Data, Effect, Layer } from 'effect';
2
- import { detect } from 'package-manager-detector/detect';
3
- import { PackageJson, readPackage } from 'pkg-types';
4
-
5
- import { exec } from 'child_process';
6
- import { promisify } from 'util';
7
- import { UI } from '../../ui/index.js';
8
- import { findProjectDir } from '../../util/projectDir.js';
9
- import { runUIEffect } from '../lib/ui.js';
10
-
11
- export class ProjectInfo extends Context.Tag(
12
- 'instant-cli/new/context/projectInfo',
13
- )<
14
- ProjectInfo,
15
- {
16
- pkgDir: string;
17
- projectType: 'node' | 'deno';
18
- instantModuleName: string;
19
- }
20
- >() {}
21
-
22
- const execAsync = promisify(exec);
23
-
24
- export const PACKAGE_ALIAS_AND_FULL_NAMES = {
25
- react: '@instantdb/react',
26
- 'react-native': '@instantdb/react-native',
27
- core: '@instantdb/core',
28
- admin: '@instantdb/admin',
29
- };
30
-
31
- export class ProjectInfoError extends Data.TaggedError('ProjectInfoError')<{
32
- message: string;
33
- cause?: unknown;
34
- }> {}
35
-
36
- const getProjectInfo = (
37
- coerce: boolean = true,
38
- packageName?: keyof typeof PACKAGE_ALIAS_AND_FULL_NAMES,
39
- ) =>
40
- Effect.gen(function* () {
41
- const projectDir = yield* Effect.tryPromise({
42
- try: () => findProjectDir(),
43
- catch: (e) =>
44
- new ProjectInfoError({ message: "Couldn't get project dir" }),
45
- });
46
-
47
- if (!projectDir) {
48
- return yield* new ProjectInfoError({
49
- message: "Couldn't find a project directory (package.json)",
50
- });
51
- }
52
-
53
- if (projectDir.type === 'deno') {
54
- return {
55
- pkgDir: projectDir.dir,
56
- projectType: projectDir.type,
57
- instantModuleName: '@instantdb/core',
58
- };
59
- }
60
-
61
- const pkgJson = yield* Effect.tryPromise({
62
- try: () => readPackage(),
63
- catch: () =>
64
- new ProjectInfoError({ message: "Couldn't read package.json" }),
65
- });
66
-
67
- let moduleName = getInstantModuleName(pkgJson);
68
- if (!moduleName && !coerce) {
69
- return yield* new ProjectInfoError({
70
- message: 'No instant client library installed',
71
- });
72
- }
73
-
74
- // TODO: Clean up with option
75
- const packageManager = yield* Effect.tryPromise(() => detect()).pipe(
76
- Effect.flatMap(Effect.fromNullable),
77
- Effect.mapError(
78
- () =>
79
- new ProjectInfoError({
80
- message: 'Failed to detect package manager',
81
- }),
82
- ),
83
- );
84
-
85
- if (!moduleName && coerce) {
86
- // install the packages
87
- if (packageName) {
88
- moduleName = PACKAGE_ALIAS_AND_FULL_NAMES[packageName];
89
- } else {
90
- moduleName = yield* runUIEffect(
91
- new UI.Select({
92
- promptText: 'Which package would you like to use?',
93
- options: [
94
- { label: '@instantdb/react', value: '@instantdb/react' },
95
- {
96
- label: '@instantdb/react-native',
97
- value: '@instantdb/react-native',
98
- },
99
- { label: '@instantdb/core', value: '@instantdb/core' },
100
- { label: '@instantdb/admin', value: '@instantdb/admin' },
101
- ],
102
- }),
103
- ).pipe(
104
- Effect.flatMap(Effect.fromNullable),
105
- Effect.mapError(
106
- () =>
107
- new ProjectInfoError({
108
- message: 'Failed to select package',
109
- }),
110
- ),
111
- );
112
- }
113
- const packagesToInstall = [moduleName];
114
- if (moduleName === '@instantdb/react-native') {
115
- packagesToInstall.push(
116
- 'react-native-get-random-values',
117
- '@react-native-async-storage/async-storage',
118
- );
119
- }
120
- const installCommand = getInstallCommand(
121
- packageManager.agent,
122
- packagesToInstall.join(' '),
123
- );
124
- console.log(installCommand);
125
- yield* runUIEffect(
126
- new UI.Spinner({
127
- promise: execAsync(installCommand, {
128
- cwd: projectDir.dir,
129
- }),
130
- errorText: 'Failed to install packages',
131
- workingText: `Installing ${packagesToInstall.join(', ')} using ${packageManager.agent}...`,
132
- doneText: `Installed ${packagesToInstall.join(', ')} using ${packageManager.agent}.`,
133
- }),
134
- );
135
- return {
136
- pkgDir: projectDir.dir,
137
- projectType: projectDir.type,
138
- instantModuleName: moduleName,
139
- };
140
- } else {
141
- return {
142
- pkgDir: projectDir.dir,
143
- projectType: projectDir.type,
144
- instantModuleName: moduleName!,
145
- };
146
- }
147
- });
148
-
149
- export const ProjectInfoLive = (
150
- coerce: boolean = true,
151
- packageName?: keyof typeof PACKAGE_ALIAS_AND_FULL_NAMES,
152
- ) => Layer.effect(ProjectInfo, getProjectInfo(coerce, packageName));
153
-
154
- function getInstantModuleName(pkgJson: PackageJson) {
155
- const deps = pkgJson.dependencies || {};
156
- const devDeps = pkgJson.devDependencies || {};
157
- const instantModuleName = [
158
- '@instantdb/react',
159
- '@instantdb/react-native',
160
- '@instantdb/core',
161
- '@instantdb/admin',
162
- ].find((name) => deps[name] || devDeps[name]);
163
- return instantModuleName;
164
- }
165
-
166
- function getInstallCommand(packageManager: string, moduleName: string) {
167
- if (packageManager === 'npm') {
168
- return `npm install ${moduleName}`;
169
- } else {
170
- return `${packageManager} add ${moduleName}`;
171
- }
172
- }
package/src/new/errors.ts DELETED
@@ -1,7 +0,0 @@
1
- import { Schema } from 'effect';
2
-
3
- export class BadArgsError extends Schema.TaggedError<BadArgsError>(
4
- 'BadArgsError',
5
- )('BadArgsError', {
6
- message: Schema.String,
7
- }) {}
package/src/new/index.ts DELETED
@@ -1,245 +0,0 @@
1
- import { Command, Option, program } from '@commander-js/extra-typings';
2
- import chalk from 'chalk';
3
- import { Effect } from 'effect';
4
- import version from '../version.js';
5
- import { initCommand } from './commands/init.js';
6
- import { initWithoutFilesCommand } from './commands/initWithoutFiles.js';
7
- import { loginCommand } from './commands/login.js';
8
- import { logoutCommand } from './commands/logout.js';
9
- import { loadEnv } from '../util/loadEnv.js';
10
- import {
11
- AuthLayerLive,
12
- BaseLayerLive,
13
- printRedErrors,
14
- WithAppLayer,
15
- } from './layer.js';
16
-
17
- loadEnv();
18
-
19
- export type ArgsFromCommand<C> =
20
- C extends Command<any, infer R, any> ? R : never;
21
-
22
- program
23
- .name('instant-cli')
24
- .addOption(globalOption('-t --token <token>', 'Auth token override'))
25
- .addOption(globalOption('-y --yes', "Answer 'yes' to all prompts"))
26
- .addOption(globalOption('--env <file>', 'Use a specific .env file'))
27
- .addOption(
28
- globalOption('-v --version', 'Print the version number', () => {
29
- console.log(version);
30
- process.exit(0);
31
- }),
32
- )
33
- .addHelpOption(globalOption('-h --help', 'Print the help text for a command'))
34
- .usage(`<command> ${chalk.dim('[options] [args]')}`);
35
-
36
- // Command List
37
- export const initDef = program
38
- .command('init')
39
- .description('Set up a new project.')
40
- .option(
41
- '-a --app <app-id>',
42
- 'If you have an existing app ID, we can pull schema and perms from there.',
43
- )
44
- .option(
45
- '-p --package <react|react-native|core|admin>',
46
- 'Which package to automatically install if there is not one installed already.',
47
- )
48
- .option('--title <title>', 'Title for the created app')
49
- .action((options) => {
50
- return Effect.runPromise(
51
- initCommand(options).pipe(
52
- Effect.provide(
53
- WithAppLayer({
54
- coerce: true,
55
- title: options.title,
56
- appId: options.app,
57
- packageName: options.package as any,
58
- applyEnv: true,
59
- }),
60
- ),
61
- printRedErrors,
62
- ),
63
- );
64
- });
65
-
66
- export const initWithoutFilesDef = program
67
- .command('init-without-files')
68
- .description('Generate a new app id and admin token pair without any files.')
69
- .option('--title <title>', 'Title for the created app.')
70
- .option(
71
- '--org-id <org-id>',
72
- 'Organization id for app. Cannot be used with --temp flag.',
73
- )
74
- .option(
75
- '--temp',
76
- 'Create a temporary app which will automatically delete itself after >24 hours.',
77
- )
78
- .action((opts) => {
79
- return Effect.runPromise(
80
- initWithoutFilesCommand(opts).pipe(
81
- Effect.provide(AuthLayerLive),
82
- printRedErrors,
83
- ),
84
- );
85
- });
86
-
87
- export const loginDef = program
88
- .command('login')
89
- .description('Log into your account')
90
- .option('-p --print', 'Prints the auth token into the console.')
91
- .option(
92
- '--headless',
93
- 'Print the login URL instead of trying to open the browser',
94
- )
95
- .action(async (opts) => {
96
- Effect.runPromise(
97
- loginCommand(opts).pipe(Effect.provide(BaseLayerLive), printRedErrors),
98
- );
99
- });
100
-
101
- const _logoutDef = program
102
- .command('logout')
103
- .description('Log out of your Instant account')
104
- .action(async () => {
105
- Effect.runPromise(
106
- logoutCommand().pipe(Effect.provide(BaseLayerLive), printRedErrors),
107
- );
108
- });
109
-
110
- //// Program setup /////
111
-
112
- function globalOption(
113
- flags: string,
114
- description?: string,
115
- argParser?: (value: string, prev?: unknown) => unknown,
116
- ) {
117
- const opt = new Option(flags, description);
118
- if (argParser) {
119
- opt.argParser(argParser);
120
- }
121
- // @ts-ignore
122
- // __global does not exist on `Option`,
123
- // but we use it in `getLocalAndGlobalOptions`, to produce
124
- // our own custom list of local and global options.
125
- // For more info, see the original PR:
126
- // https://github.com/instantdb/instant/pull/505
127
- opt.__global = true;
128
- return opt;
129
- }
130
-
131
- function getLocalAndGlobalOptions(cmd, helper) {
132
- const mixOfLocalAndGlobal = helper.visibleOptions(cmd);
133
- const localOptionsFromMix = mixOfLocalAndGlobal.filter(
134
- (option) => !option.__global,
135
- );
136
- const globalOptionsFromMix = mixOfLocalAndGlobal.filter(
137
- (option) => option.__global,
138
- );
139
- const globalOptions = helper.visibleGlobalOptions(cmd);
140
-
141
- return [localOptionsFromMix, globalOptionsFromMix.concat(globalOptions)];
142
- }
143
-
144
- function formatHelp(cmd, helper) {
145
- const termWidth = helper.padWidth(cmd, helper);
146
- const helpWidth = helper.helpWidth || 80;
147
- const itemIndentWidth = 2;
148
- const itemSeparatorWidth = 2; // between term and description
149
- function formatItem(term, description) {
150
- if (description) {
151
- const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
152
- return helper.wrap(
153
- fullText,
154
- helpWidth - itemIndentWidth,
155
- termWidth + itemSeparatorWidth,
156
- );
157
- }
158
- return term;
159
- }
160
- function formatList(textArray) {
161
- return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
162
- }
163
-
164
- // Usage
165
- let output = [`${helper.commandUsage(cmd)}`, ''];
166
-
167
- // Description
168
- const commandDescription = helper.commandDescription(cmd);
169
- if (commandDescription.length > 0) {
170
- output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);
171
- }
172
-
173
- // Arguments
174
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
175
- return formatItem(
176
- helper.argumentTerm(argument),
177
- helper.argumentDescription(argument),
178
- );
179
- });
180
- if (argumentList.length > 0) {
181
- output = output.concat([
182
- chalk.dim.bold('Arguments'),
183
- formatList(argumentList),
184
- '',
185
- ]);
186
- }
187
- const [visibleOptions, visibleGlobalOptions] = getLocalAndGlobalOptions(
188
- cmd,
189
- helper,
190
- );
191
-
192
- // Options
193
- const optionList = visibleOptions.map((option) => {
194
- return formatItem(
195
- helper.optionTerm(option),
196
- helper.optionDescription(option),
197
- );
198
- });
199
- if (optionList.length > 0) {
200
- output = output.concat([
201
- chalk.dim.bold('Options'),
202
- formatList(optionList),
203
- '',
204
- ]);
205
- }
206
- // Commands
207
- const commandList = helper.visibleCommands(cmd).map((cmd) => {
208
- return formatItem(
209
- helper.subcommandTerm(cmd),
210
- helper.subcommandDescription(cmd),
211
- );
212
- });
213
- if (commandList.length > 0) {
214
- output = output.concat([
215
- chalk.dim.bold('Commands'),
216
- formatList(commandList),
217
- '',
218
- ]);
219
- }
220
-
221
- if (this.showGlobalOptions) {
222
- const globalOptionList = visibleGlobalOptions.map((option) => {
223
- return formatItem(
224
- helper.optionTerm(option),
225
- helper.optionDescription(option),
226
- );
227
- });
228
- if (globalOptionList.length > 0) {
229
- output = output.concat([
230
- chalk.dim.bold('Global Options'),
231
- formatList(globalOptionList),
232
- '',
233
- ]);
234
- }
235
- }
236
-
237
- return output.join('\n');
238
- }
239
-
240
- program.configureHelp({
241
- showGlobalOptions: true,
242
- formatHelp,
243
- });
244
-
245
- program.parse(process.argv);
package/src/new/layer.ts DELETED
@@ -1,78 +0,0 @@
1
- import { NodeContext, NodeHttpClient } from '@effect/platform-node';
2
- import chalk from 'chalk';
3
- import { Cause, Console, Effect, Layer } from 'effect';
4
- import { InstantHttpAuthedLive, InstantHttpLive } from './lib/http.js';
5
- import { AuthTokenLive } from './context/authToken.js';
6
- import { PlatformApi } from './context/platformApi.js';
7
- import { GlobalOptsLive } from './context/globalOpts.js';
8
- import {
9
- PACKAGE_ALIAS_AND_FULL_NAMES,
10
- ProjectInfoLive,
11
- } from './context/projectInfo.js';
12
- import { CurrentAppLive } from './context/currentApp.js';
13
-
14
- export const printRedErrors = Effect.catchAllCause((cause) => {
15
- const failure = Cause.failureOption(cause);
16
-
17
- // Print just the message if the error has a message attribute and no cause
18
- if (
19
- failure._tag === 'Some' &&
20
- typeof failure.value === 'object' &&
21
- failure.value !== null &&
22
- 'message' in failure.value &&
23
- !('cause' in failure.value)
24
- ) {
25
- return Console.error(
26
- chalk.red((failure.value as { message: string }).message),
27
- );
28
- }
29
- return Console.error(
30
- chalk.red(Cause.pretty(cause, { renderErrorCause: true })),
31
- );
32
- });
33
-
34
- /**
35
- * Note:
36
- Avoid Duplicate Layer Creation
37
-
38
- Layers are memoized using reference equality. Therefore, if you have a layer that is created by calling a function like f(), you should only call that f once and re-use the resulting layer so that you are always using the same instance.
39
- */
40
-
41
- // Base layers
42
- const AuthTokenLayer = Layer.provide(AuthTokenLive, NodeContext.layer);
43
- const InstantHttpLayer = Layer.provide(InstantHttpLive, NodeHttpClient.layer);
44
-
45
- // Unauthenticated layer with InstantHttp + PlatformApi + GlobalOpts + NodeContext
46
- export const BaseLayerLive = Layer.provideMerge(
47
- Layer.mergeAll(InstantHttpLayer, PlatformApi.Default, GlobalOptsLive),
48
- NodeContext.layer,
49
- );
50
-
51
- // Authenticated layer extends BaseLayerLive with InstantHttpAuthed
52
- export const AuthLayerLive = Layer.provideMerge(
53
- Layer.provideMerge(
54
- InstantHttpAuthedLive,
55
- Layer.merge(AuthTokenLayer, InstantHttpLayer),
56
- ),
57
- BaseLayerLive,
58
- );
59
-
60
- export const WithAppLayer = (args: {
61
- appId?: string;
62
- title?: string;
63
- coerce: boolean;
64
- packageName: keyof typeof PACKAGE_ALIAS_AND_FULL_NAMES;
65
- applyEnv?: boolean;
66
- }) =>
67
- Layer.mergeAll(
68
- CurrentAppLive({
69
- coerce: args.coerce,
70
- appId: args.appId,
71
- title: args.title,
72
- applyEnv: args.applyEnv,
73
- }),
74
- ).pipe(
75
- Layer.provideMerge(GlobalOptsLive),
76
- Layer.provideMerge(AuthLayerLive),
77
- Layer.provideMerge(ProjectInfoLive(args.coerce, args.packageName)),
78
- );
@@ -1,18 +0,0 @@
1
- import { randomUUID } from 'crypto';
2
- import { Effect } from 'effect';
3
- import { InstantHttpAuthed } from './http.js';
4
- import { HttpClientRequest } from '@effect/platform';
5
-
6
- export const createApp = Effect.fn(function* (title: string, orgId?: string) {
7
- const http = yield* InstantHttpAuthed;
8
- const id = randomUUID();
9
- const token = randomUUID();
10
- const app = { id, title, admin_token: token, org_id: orgId };
11
-
12
- const res = yield* HttpClientRequest.post('/dash/apps').pipe(
13
- HttpClientRequest.bodyJson(app),
14
- Effect.flatMap(http.execute),
15
- Effect.flatMap((res) => res.json),
16
- );
17
- return res;
18
- });
@@ -1,107 +0,0 @@
1
- import { Effect } from 'effect';
2
- import { CurrentAppInfo, potentialEnvs } from '../context/currentApp.js';
3
- import { ProjectInfo, ProjectInfoError } from '../context/projectInfo.js';
4
- import { readPackage } from 'pkg-types';
5
- import { GlobalOpts } from '../context/globalOpts.js';
6
- import { FileSystem, Path } from '@effect/platform';
7
- import chalk from 'chalk';
8
- import terminalLink from 'terminal-link';
9
- import { getDashUrl } from './http.js';
10
- import { promptOk } from './ui.js';
11
-
12
- export const handleEnv = Effect.fn(function* (app: CurrentAppInfo) {
13
- const opts = yield* GlobalOpts;
14
- const { pkgDir } = yield* ProjectInfo;
15
- const envType = yield* detectEnvType;
16
- const envName = potentialEnvs[envType];
17
- const envFile = opts.env ?? '.env';
18
- const fs = yield* FileSystem.FileSystem;
19
- const path = yield* Path.Path;
20
- const hasEnvFile = yield* fs.exists(path.join(pkgDir, envFile));
21
- const dashOrigin = yield* getDashUrl;
22
- if (hasEnvFile) {
23
- return printDotEnvInfo(envType, app.appId, dashOrigin);
24
- }
25
- console.log(
26
- `\nLooks like you don't have a ${chalk.green(`\`${envFile}\``)} file yet.`,
27
- );
28
- console.log(
29
- `If we set ${chalk.green(envName)} & ${chalk.green('INSTANT_APP_ADMIN_TOKEN')}, we can remember the app that you chose for all future commands.`,
30
- );
31
- const saveExtraInfo =
32
- envFile !== '.env' ? chalk.green(' (will create `' + envFile + '`)') : '';
33
-
34
- const ok = yield* promptOk(
35
- {
36
- inline: true,
37
- promptText: 'Want us to create this env file for you?' + saveExtraInfo,
38
- modifyOutput: (a) => a,
39
- },
40
- true,
41
- );
42
- if (!ok) {
43
- console.log(
44
- `No .env file created. You can always set ${chalk.green('`' + envName + '`')} later. \n`,
45
- );
46
- return;
47
- }
48
- const content =
49
- [
50
- [envName, app.appId],
51
- ['INSTANT_APP_ADMIN_TOKEN', app.adminToken],
52
- ]
53
- .map(([k, v]) => `${k}=${v}`)
54
- .join('\n') + '\n';
55
-
56
- yield* fs.writeFileString(path.join(pkgDir, envFile), content);
57
-
58
- if (envFile !== '.env') {
59
- console.log(`Created ${chalk.green(envFile)}!`);
60
- } else {
61
- console.log(`Created ${chalk.green('.env')} file!`);
62
- }
63
- });
64
-
65
- const detectEnvType = Effect.gen(function* () {
66
- const pkgJson = yield* Effect.tryPromise({
67
- try: () => readPackage(),
68
- catch: () =>
69
- new ProjectInfoError({ message: "Couldn't read package.json" }),
70
- });
71
- if (pkgJson.dependencies?.next) {
72
- return 'next';
73
- }
74
- if (pkgJson.devDependencies?.svelte) {
75
- return 'svelte';
76
- }
77
- if (pkgJson.devDependencies?.vite) {
78
- return 'vite';
79
- }
80
- if (pkgJson.dependencies?.expo) {
81
- return 'expo';
82
- }
83
- if (pkgJson.dependencies?.nuxt) {
84
- return 'nuxt';
85
- }
86
- return 'catchall';
87
- }).pipe(Effect.catchTag('ProjectInfoError', () => Effect.succeed('catchall')));
88
-
89
- function printDotEnvInfo(envType, appId, dashOrigin: string) {
90
- console.log(`\nPicked app ${chalk.green(appId)}!\n`);
91
- console.log(
92
- `To use this app automatically from now on, update your ${chalk.green('`.env`')} file:`,
93
- );
94
- const picked = potentialEnvs[envType];
95
- const rest = { ...potentialEnvs };
96
- delete rest[envType];
97
- console.log(` ${chalk.green(picked)}=${appId}`);
98
- const otherEnvs = Object.values(rest);
99
- otherEnvs.sort();
100
- const otherEnvStr = otherEnvs.map((x) => ' ' + chalk.green(x)).join('\n');
101
- console.log(`Alternative names: \n${otherEnvStr} \n`);
102
- console.log(terminalLink('Dashboard:', appDashUrl(appId, dashOrigin)) + '\n');
103
- }
104
-
105
- function appDashUrl(id, instantOrigin: string) {
106
- return `${instantOrigin}/dash?s=main&t=home&app=${id}`;
107
- }