instant-cli
Advanced tools
Comparing version
#!/usr/bin/env node | ||
import "../dist/index.js"; | ||
import '../dist/index.js'; |
export const rels: { | ||
"many-false": string[]; | ||
"one-true": string[]; | ||
"many-true": string[]; | ||
"one-false": string[]; | ||
'many-false': string[]; | ||
'one-true': string[]; | ||
'many-true': string[]; | ||
'one-false': string[]; | ||
}; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -11,23 +11,23 @@ // @ts-check | ||
}; | ||
import version from "./version.js"; | ||
import { mkdir, writeFile, readFile } from "fs/promises"; | ||
import { join } from "path"; | ||
import { randomUUID } from "crypto"; | ||
import jsonDiff from "json-diff"; | ||
import dotenv from "dotenv"; | ||
import chalk from "chalk"; | ||
import { program, Option } from "commander"; | ||
import { input, select } from "@inquirer/prompts"; | ||
import envPaths from "env-paths"; | ||
import { loadConfig } from "unconfig"; | ||
import { packageDirectory } from "pkg-dir"; | ||
import openInBrowser from "open"; | ||
import ora from "ora"; | ||
import terminalLink from "terminal-link"; | ||
import { exec } from "child_process"; | ||
import { promisify } from "util"; | ||
import { detectPackageManager, getInstallCommand, } from "./util/packageManager.js"; | ||
import { pathExists, readJsonFile } from "./util/fs.js"; | ||
import prettier from "prettier"; | ||
import toggle from "./toggle.js"; | ||
import version from './version.js'; | ||
import { mkdir, writeFile, readFile } from 'fs/promises'; | ||
import { join } from 'path'; | ||
import { randomUUID } from 'crypto'; | ||
import jsonDiff from 'json-diff'; | ||
import dotenv from 'dotenv'; | ||
import chalk from 'chalk'; | ||
import { program, Option } from 'commander'; | ||
import { input, select } from '@inquirer/prompts'; | ||
import envPaths from 'env-paths'; | ||
import { loadConfig } from 'unconfig'; | ||
import { packageDirectory } from 'pkg-dir'; | ||
import openInBrowser from 'open'; | ||
import ora from 'ora'; | ||
import terminalLink from 'terminal-link'; | ||
import { exec } from 'child_process'; | ||
import { promisify } from 'util'; | ||
import { detectPackageManager, getInstallCommand, } from './util/packageManager.js'; | ||
import { pathExists, readJsonFile } from './util/fs.js'; | ||
import prettier from 'prettier'; | ||
import toggle from './toggle.js'; | ||
const execAsync = promisify(exec); | ||
@@ -40,15 +40,15 @@ // config | ||
function warn(firstArg, ...rest) { | ||
console.warn(chalk.yellow("[warning]") + " " + firstArg, ...rest); | ||
console.warn(chalk.yellow('[warning]') + ' ' + firstArg, ...rest); | ||
} | ||
function error(firstArg, ...rest) { | ||
console.error(chalk.red("[error]") + " " + firstArg, ...rest); | ||
console.error(chalk.red('[error]') + ' ' + firstArg, ...rest); | ||
} | ||
// consts | ||
const potentialEnvs = { | ||
catchall: "INSTANT_APP_ID", | ||
next: "NEXT_PUBLIC_INSTANT_APP_ID", | ||
svelte: "PUBLIC_INSTANT_APP_ID", | ||
vite: "VITE_INSTANT_APP_ID", | ||
expo: "EXPO_PUBLIC_INSTANT_APP_ID", | ||
nuxt: "NUXT_PUBLIC_INSTANT_APP_ID", | ||
catchall: 'INSTANT_APP_ID', | ||
next: 'NEXT_PUBLIC_INSTANT_APP_ID', | ||
svelte: 'PUBLIC_INSTANT_APP_ID', | ||
vite: 'VITE_INSTANT_APP_ID', | ||
expo: 'EXPO_PUBLIC_INSTANT_APP_ID', | ||
nuxt: 'NUXT_PUBLIC_INSTANT_APP_ID', | ||
}; | ||
@@ -60,31 +60,31 @@ function detectEnvType(_a) { | ||
if (!packageJSON) { | ||
return "catchall"; | ||
return 'catchall'; | ||
} | ||
if ((_b = packageJSON.dependencies) === null || _b === void 0 ? void 0 : _b.next) { | ||
return "next"; | ||
return 'next'; | ||
} | ||
if ((_c = packageJSON.devDependencies) === null || _c === void 0 ? void 0 : _c.svelte) { | ||
return "svelte"; | ||
return 'svelte'; | ||
} | ||
if ((_d = packageJSON.devDependencies) === null || _d === void 0 ? void 0 : _d.vite) { | ||
return "vite"; | ||
return 'vite'; | ||
} | ||
if ((_e = packageJSON.dependencies) === null || _e === void 0 ? void 0 : _e.expo) { | ||
return "expo"; | ||
return 'expo'; | ||
} | ||
if ((_f = packageJSON.dependencies) === null || _f === void 0 ? void 0 : _f.nuxt) { | ||
return "nuxt"; | ||
return 'nuxt'; | ||
} | ||
return "catchall"; | ||
return 'catchall'; | ||
}); | ||
} | ||
const instantDashOrigin = dev | ||
? "http://localhost:3000" | ||
: "https://instantdb.com"; | ||
? 'http://localhost:3000' | ||
: 'https://instantdb.com'; | ||
const instantBackendOrigin = process.env.INSTANT_CLI_API_URI || | ||
(dev ? "http://localhost:8888" : "https://api.instantdb.com"); | ||
const PUSH_PULL_OPTIONS = new Set(["schema", "perms", "all"]); | ||
(dev ? 'http://localhost:8888' : 'https://api.instantdb.com'); | ||
const PUSH_PULL_OPTIONS = new Set(['schema', 'perms', 'all']); | ||
function convertArgToBagWithErrorLogging(arg) { | ||
if (!arg) { | ||
return { ok: true, bag: "all" }; | ||
return { ok: true, bag: 'all' }; | ||
} | ||
@@ -95,3 +95,3 @@ else if (PUSH_PULL_OPTIONS.has(arg.trim().toLowerCase())) { | ||
else { | ||
error(`${chalk.red(arg)} must be one of ${chalk.green(Array.from(PUSH_PULL_OPTIONS).join(", "))}`); | ||
error(`${chalk.red(arg)} must be one of ${chalk.green(Array.from(PUSH_PULL_OPTIONS).join(', '))}`); | ||
return { ok: false }; | ||
@@ -107,3 +107,3 @@ } | ||
warnDeprecation(`${cmdName} ${arg}`, `${cmdName} --app ${arg}`); | ||
return { ok: true, bag: "all", opts: Object.assign(Object.assign({}, opts), { app: arg }) }; | ||
return { ok: true, bag: 'all', opts: Object.assign(Object.assign({}, opts), { app: arg }) }; | ||
} | ||
@@ -127,14 +127,14 @@ const { ok, bag } = convertArgToBagWithErrorLogging(arg); | ||
// Header -- this shows up in every command | ||
const logoChalk = chalk.bold("instant-cli"); | ||
const logoChalk = chalk.bold('instant-cli'); | ||
const versionChalk = chalk.dim(`${version.trim()}`); | ||
const headerChalk = `${logoChalk} ${versionChalk} ` + "\n"; | ||
const headerChalk = `${logoChalk} ${versionChalk} ` + '\n'; | ||
// Help Footer -- this only shows up in help commands | ||
const helpFooterChalk = "\n" + | ||
chalk.dim.bold("Want to learn more?") + | ||
"\n" + | ||
`Check out the docs: ${chalk.blueBright.underline("https://instantdb.com/docs")} | ||
Join the Discord: ${chalk.blueBright.underline("https://discord.com/invite/VU53p7uQcE")} | ||
const helpFooterChalk = '\n' + | ||
chalk.dim.bold('Want to learn more?') + | ||
'\n' + | ||
`Check out the docs: ${chalk.blueBright.underline('https://instantdb.com/docs')} | ||
Join the Discord: ${chalk.blueBright.underline('https://discord.com/invite/VU53p7uQcE')} | ||
`.trim(); | ||
program.addHelpText("after", helpFooterChalk); | ||
program.addHelpText("beforeAll", headerChalk); | ||
program.addHelpText('after', helpFooterChalk); | ||
program.addHelpText('beforeAll', headerChalk); | ||
function getLocalAndGlobalOptions(cmd, helper) { | ||
@@ -162,10 +162,10 @@ const mixOfLocalAndGlobal = helper.visibleOptions(cmd); | ||
function formatList(textArray) { | ||
return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth)); | ||
return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); | ||
} | ||
// Usage | ||
let output = [`${helper.commandUsage(cmd)}`, ""]; | ||
let output = [`${helper.commandUsage(cmd)}`, '']; | ||
// Description | ||
const commandDescription = helper.commandDescription(cmd); | ||
if (commandDescription.length > 0) { | ||
output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]); | ||
output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']); | ||
} | ||
@@ -178,5 +178,5 @@ // Arguments | ||
output = output.concat([ | ||
chalk.dim.bold("Arguments"), | ||
chalk.dim.bold('Arguments'), | ||
formatList(argumentList), | ||
"", | ||
'', | ||
]); | ||
@@ -191,5 +191,5 @@ } | ||
output = output.concat([ | ||
chalk.dim.bold("Options"), | ||
chalk.dim.bold('Options'), | ||
formatList(optionList), | ||
"", | ||
'', | ||
]); | ||
@@ -203,5 +203,5 @@ } | ||
output = output.concat([ | ||
chalk.dim.bold("Commands"), | ||
chalk.dim.bold('Commands'), | ||
formatList(commandList), | ||
"", | ||
'', | ||
]); | ||
@@ -215,9 +215,9 @@ } | ||
output = output.concat([ | ||
chalk.dim.bold("Global Options"), | ||
chalk.dim.bold('Global Options'), | ||
formatList(globalOptionList), | ||
"", | ||
'', | ||
]); | ||
} | ||
} | ||
return output.join("\n"); | ||
return output.join('\n'); | ||
} | ||
@@ -243,22 +243,22 @@ program.configureHelp({ | ||
function warnDeprecation(oldCmd, newCmd) { | ||
warn(chalk.yellow("`instant-cli " + oldCmd + "` is deprecated.") + | ||
" Use " + | ||
chalk.green("`instant-cli " + newCmd + "`") + | ||
" instead." + | ||
"\n"); | ||
warn(chalk.yellow('`instant-cli ' + oldCmd + '` is deprecated.') + | ||
' Use ' + | ||
chalk.green('`instant-cli ' + newCmd + '`') + | ||
' instead.' + | ||
'\n'); | ||
} | ||
program | ||
.name("instant-cli") | ||
.addOption(globalOption("-t --token <token>", "Auth token override")) | ||
.addOption(globalOption("-y --yes", "Answer 'yes' to all prompts")) | ||
.addOption(globalOption("-v --version", "Print the version number", () => { | ||
.name('instant-cli') | ||
.addOption(globalOption('-t --token <token>', 'Auth token override')) | ||
.addOption(globalOption('-y --yes', "Answer 'yes' to all prompts")) | ||
.addOption(globalOption('-v --version', 'Print the version number', () => { | ||
console.log(version); | ||
process.exit(0); | ||
})) | ||
.addHelpOption(globalOption("-h --help", "Print the help text for a command")) | ||
.usage(`<command> ${chalk.dim("[options] [args]")}`); | ||
.addHelpOption(globalOption('-h --help', 'Print the help text for a command')) | ||
.usage(`<command> ${chalk.dim('[options] [args]')}`); | ||
program | ||
.command("login") | ||
.description("Log into your account") | ||
.option("-p --print", "Prints the auth token into the console.") | ||
.command('login') | ||
.description('Log into your account') | ||
.option('-p --print', 'Prints the auth token into the console.') | ||
.action((opts) => __awaiter(void 0, void 0, void 0, function* () { | ||
@@ -269,8 +269,8 @@ console.log("Let's log you in!"); | ||
program | ||
.command("init") | ||
.description("Set up a new project.") | ||
.option("-a --app <app-id>", "If you have an existing app ID, we can pull schema and perms from there.") | ||
.command('init') | ||
.description('Set up a new project.') | ||
.option('-a --app <app-id>', 'If you have an existing app ID, we can pull schema and perms from there.') | ||
.action(function (opts) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
yield handlePull("all", opts); | ||
yield handlePull('all', opts); | ||
}); | ||
@@ -282,9 +282,9 @@ }); | ||
program | ||
.command("push-schema", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Push schema to production.") | ||
.option("--skip-check-types", "Don't check types on the server when pushing schema") | ||
.command('push-schema', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Push schema to production.') | ||
.option('--skip-check-types', "Don't check types on the server when pushing schema") | ||
.action((appIdOrName, opts) => __awaiter(void 0, void 0, void 0, function* () { | ||
warnDeprecation("push-schema", "push schema"); | ||
yield handlePush("schema", Object.assign({ app: appIdOrName }, opts)); | ||
warnDeprecation('push-schema', 'push schema'); | ||
yield handlePush('schema', Object.assign({ app: appIdOrName }, opts)); | ||
})); | ||
@@ -295,18 +295,18 @@ // Note: Nov 20, 2024 | ||
program | ||
.command("push-perms", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Push perms to production.") | ||
.command('push-perms', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Push perms to production.') | ||
.action((appIdOrName) => __awaiter(void 0, void 0, void 0, function* () { | ||
warnDeprecation("push-perms", "push perms"); | ||
yield handlePush("perms", { app: appIdOrName }); | ||
warnDeprecation('push-perms', 'push perms'); | ||
yield handlePush('perms', { app: appIdOrName }); | ||
})); | ||
program | ||
.command("push") | ||
.argument("[schema|perms|all]", "Which configuration to push. Defaults to `all`") | ||
.option("-a --app <app-id>", "App ID to push too. Defaults to *_INSTANT_APP_ID in .env") | ||
.option("--skip-check-types", "Don't check types on the server when pushing schema") | ||
.description("Push schema and perm files to production.") | ||
.command('push') | ||
.argument('[schema|perms|all]', 'Which configuration to push. Defaults to `all`') | ||
.option('-a --app <app-id>', 'App ID to push too. Defaults to *_INSTANT_APP_ID in .env') | ||
.option('--skip-check-types', "Don't check types on the server when pushing schema") | ||
.description('Push schema and perm files to production.') | ||
.action(function (arg, inputOpts) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const ret = convertPushPullToCurrentFormat("push", arg, inputOpts); | ||
const ret = convertPushPullToCurrentFormat('push', arg, inputOpts); | ||
if (!ret.ok) | ||
@@ -322,8 +322,8 @@ return; | ||
program | ||
.command("pull-schema", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Generate instant.schema.ts from production") | ||
.command('pull-schema', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Generate instant.schema.ts from production') | ||
.action((appIdOrName) => __awaiter(void 0, void 0, void 0, function* () { | ||
warnDeprecation("pull-schema", "pull schema"); | ||
yield handlePull("schema", { app: appIdOrName }); | ||
warnDeprecation('pull-schema', 'pull schema'); | ||
yield handlePull('schema', { app: appIdOrName }); | ||
})); | ||
@@ -334,17 +334,17 @@ // Note: Nov 20, 2024 | ||
program | ||
.command("pull-perms", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Generate instant.perms.ts from production.") | ||
.command('pull-perms', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Generate instant.perms.ts from production.') | ||
.action((appIdOrName) => __awaiter(void 0, void 0, void 0, function* () { | ||
warnDeprecation("pull-perms", "pull perms"); | ||
yield handlePull("perms", { app: appIdOrName }); | ||
warnDeprecation('pull-perms', 'pull perms'); | ||
yield handlePull('perms', { app: appIdOrName }); | ||
})); | ||
program | ||
.command("pull") | ||
.argument("[schema|perms|all]", "Which configuration to push. Defaults to `all`") | ||
.option("-a --app <app-id>", "App ID to push to. Defaults to *_INSTANT_APP_ID in .env") | ||
.description("Pull schema and perm files from production.") | ||
.command('pull') | ||
.argument('[schema|perms|all]', 'Which configuration to push. Defaults to `all`') | ||
.option('-a --app <app-id>', 'App ID to push to. Defaults to *_INSTANT_APP_ID in .env') | ||
.description('Pull schema and perm files from production.') | ||
.action(function (arg, inputOpts) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const ret = convertPushPullToCurrentFormat("pull", arg, inputOpts); | ||
const ret = convertPushPullToCurrentFormat('pull', arg, inputOpts); | ||
if (!ret.ok) | ||
@@ -371,3 +371,3 @@ return; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (bag === "schema" || bag === "all") { | ||
if (bag === 'schema' || bag === 'all') { | ||
const { ok } = yield pushSchema(appId, opts); | ||
@@ -377,3 +377,3 @@ if (!ok) | ||
} | ||
if (bag === "perms" || bag === "all") { | ||
if (bag === 'perms' || bag === 'all') { | ||
yield pushPerms(appId); | ||
@@ -385,3 +385,3 @@ } | ||
console.log(`\nPicked app ${chalk.green(appId)}!\n`); | ||
console.log(`To use this app automatically from now on, update your ${chalk.green("`.env`")} file:`); | ||
console.log(`To use this app automatically from now on, update your ${chalk.green('`.env`')} file:`); | ||
const picked = potentialEnvs[envType]; | ||
@@ -393,5 +393,5 @@ const rest = Object.assign({}, potentialEnvs); | ||
otherEnvs.sort(); | ||
const otherEnvStr = otherEnvs.map((x) => " " + chalk.green(x)).join("\n"); | ||
const otherEnvStr = otherEnvs.map((x) => ' ' + chalk.green(x)).join('\n'); | ||
console.log(`Alternative names: \n${otherEnvStr} \n`); | ||
console.log(terminalLink("Dashboard", appDashUrl(appId)) + "\n"); | ||
console.log(terminalLink('Dashboard', appDashUrl(appId)) + '\n'); | ||
} | ||
@@ -403,3 +403,3 @@ function handleEnvFile(pkgAndAuthInfo, appId) { | ||
const envName = potentialEnvs[envType]; | ||
const hasEnvFile = yield pathExists(join(pkgDir, ".env")); | ||
const hasEnvFile = yield pathExists(join(pkgDir, '.env')); | ||
if (hasEnvFile) { | ||
@@ -409,12 +409,12 @@ printDotEnvInfo(envType, appId); | ||
} | ||
console.log(`\nLooks like you don't have a ${chalk.green("`.env`")} file yet.`); | ||
console.log(`If we set ${chalk.green("`" + envName + "`")}, we can remember the app that you chose for all future commands.`); | ||
const ok = yield promptOk("Want us to create this env file for you?", | ||
console.log(`\nLooks like you don't have a ${chalk.green('`.env`')} file yet.`); | ||
console.log(`If we set ${chalk.green('`' + envName + '`')}, we can remember the app that you chose for all future commands.`); | ||
const ok = yield promptOk('Want us to create this env file for you?', | ||
/*defaultAnswer=*/ true); | ||
if (!ok) { | ||
console.log(`No .env file created. You can always set ${chalk.green("`" + envName + "`")} later. \n`); | ||
console.log(`No .env file created. You can always set ${chalk.green('`' + envName + '`')} later. \n`); | ||
return; | ||
} | ||
yield writeFile(join(pkgDir, ".env"), `${envName}=${appId}`, "utf-8"); | ||
console.log(`Created ${chalk.green("`.env`")} file!`); | ||
yield writeFile(join(pkgDir, '.env'), `${envName}=${appId}`, 'utf-8'); | ||
console.log(`Created ${chalk.green('`.env`')} file!`); | ||
}); | ||
@@ -428,3 +428,3 @@ } | ||
const { appId, source } = ret; | ||
if (source === "created" || source === "imported") { | ||
if (source === 'created' || source === 'imported') { | ||
yield handleEnvFile(pkgAndAuthInfo, appId); | ||
@@ -448,3 +448,3 @@ } | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (bag === "schema" || bag === "all") { | ||
if (bag === 'schema' || bag === 'all') { | ||
const { ok } = yield pullSchema(appId, pkgAndAuthInfo); | ||
@@ -454,3 +454,3 @@ if (!ok) | ||
} | ||
if (bag === "perms" || bag === "all") { | ||
if (bag === 'perms' || bag === 'all') { | ||
yield pullPerms(appId, pkgAndAuthInfo); | ||
@@ -463,6 +463,6 @@ } | ||
const registerRes = yield fetchJson({ | ||
method: "POST", | ||
path: "/dash/cli/auth/register", | ||
debugName: "Login register", | ||
errorMessage: "Failed to register login.", | ||
method: 'POST', | ||
path: '/dash/cli/auth/register', | ||
debugName: 'Login register', | ||
errorMessage: 'Failed to register login.', | ||
noAuth: true, | ||
@@ -478,3 +478,3 @@ }); | ||
openInBrowser(`${instantDashOrigin}/dash?ticket=${ticket}`); | ||
console.log("Waiting for authentication..."); | ||
console.log('Waiting for authentication...'); | ||
const authTokenRes = yield waitForAuthToken({ secret }); | ||
@@ -486,3 +486,3 @@ if (!authTokenRes) { | ||
if (options.print) { | ||
console.log(chalk.red("[Do not share] Your Instant auth token:", token)); | ||
console.log(chalk.red('[Do not share] Your Instant auth token:', token)); | ||
} | ||
@@ -502,3 +502,3 @@ else { | ||
} | ||
console.log("Checking for an Instant SDK..."); | ||
console.log('Checking for an Instant SDK...'); | ||
const instantModuleName = yield getInstantModuleName(pkgJson); | ||
@@ -511,8 +511,8 @@ if (instantModuleName) { | ||
const moduleName = yield select({ | ||
message: "Which package would you like to use?", | ||
message: 'Which package would you like to use?', | ||
choices: [ | ||
{ name: "@instantdb/react", value: "@instantdb/react" }, | ||
{ name: "@instantdb/react-native", value: "@instantdb/react-native" }, | ||
{ name: "@instantdb/core", value: "@instantdb/core" }, | ||
{ name: "@instantdb/admin", value: "@instantdb/admin" }, | ||
{ name: '@instantdb/react', value: '@instantdb/react' }, | ||
{ name: '@instantdb/react-native', value: '@instantdb/react-native' }, | ||
{ name: '@instantdb/core', value: '@instantdb/core' }, | ||
{ name: '@instantdb/admin', value: '@instantdb/admin' }, | ||
], | ||
@@ -540,4 +540,4 @@ }); | ||
const _title = yield input({ | ||
message: "What would you like to call it?", | ||
default: "My cool app", | ||
message: 'What would you like to call it?', | ||
default: 'My cool app', | ||
required: true, | ||
@@ -547,3 +547,3 @@ }).catch(() => null); | ||
if (!title) { | ||
error("No name provided. Exiting."); | ||
error('No name provided. Exiting.'); | ||
return { ok: false }; | ||
@@ -553,6 +553,6 @@ } | ||
const appRes = yield fetchJson({ | ||
method: "POST", | ||
path: "/dash/apps", | ||
debugName: "App create", | ||
errorMessage: "Failed to create app.", | ||
method: 'POST', | ||
path: '/dash/apps', | ||
debugName: 'App create', | ||
errorMessage: 'Failed to create app.', | ||
body: app, | ||
@@ -566,3 +566,3 @@ }); | ||
appTitle: title, | ||
source: "created", | ||
source: 'created', | ||
}; | ||
@@ -574,6 +574,6 @@ }); | ||
const res = yield fetchJson({ | ||
debugName: "Fetching apps", | ||
method: "GET", | ||
path: "/dash", | ||
errorMessage: "Failed to fetch apps.", | ||
debugName: 'Fetching apps', | ||
method: 'GET', | ||
path: '/dash', | ||
errorMessage: 'Failed to fetch apps.', | ||
}); | ||
@@ -593,3 +593,3 @@ if (!res.ok) { | ||
const choice = yield select({ | ||
message: "Which app would you like to import?", | ||
message: 'Which app would you like to import?', | ||
choices: res.data.apps.map((app) => { | ||
@@ -601,3 +601,3 @@ return { name: `${app.title} (${app.id})`, value: app.id }; | ||
return { ok: false }; | ||
return { ok: true, appId: choice, source: "imported" }; | ||
return { ok: true, appId: choice, source: 'imported' }; | ||
}); | ||
@@ -611,3 +611,3 @@ } | ||
if (fromOpts.appId) { | ||
return { ok: true, appId: fromOpts.appId, source: "opts" }; | ||
return { ok: true, appId: fromOpts.appId, source: 'opts' }; | ||
} | ||
@@ -620,12 +620,12 @@ const fromEnv = detectAppIdFromEnvWithErrorLogging(); | ||
console.log(`Found ${chalk.green(envName)}: ${value}`); | ||
return { ok: true, appId: value, source: "env" }; | ||
return { ok: true, appId: value, source: 'env' }; | ||
} | ||
const action = yield select({ | ||
message: "What would you like to do?", | ||
message: 'What would you like to do?', | ||
choices: [ | ||
{ name: "Create a new app", value: "create" }, | ||
{ name: "Import an existing app", value: "import" }, | ||
{ name: 'Create a new app', value: 'create' }, | ||
{ name: 'Import an existing app', value: 'import' }, | ||
], | ||
}).catch(() => null); | ||
if (action === "create") { | ||
if (action === 'create') { | ||
return yield promptCreateApp(); | ||
@@ -639,3 +639,3 @@ } | ||
const prettierConfig = yield prettier.resolveConfig(path); | ||
const formattedCode = yield prettier.format(content, Object.assign(Object.assign({}, prettierConfig), { parser: "typescript" })); | ||
const formattedCode = yield prettier.format(content, Object.assign(Object.assign({}, prettierConfig), { parser: 'typescript' })); | ||
return yield writeFile(path, formattedCode, encoding); | ||
@@ -648,6 +648,6 @@ }); | ||
const instantModuleName = [ | ||
"@instantdb/react", | ||
"@instantdb/react-native", | ||
"@instantdb/core", | ||
"@instantdb/admin", | ||
'@instantdb/react', | ||
'@instantdb/react-native', | ||
'@instantdb/core', | ||
'@instantdb/admin', | ||
].find((name) => deps[name]); | ||
@@ -659,3 +659,3 @@ return instantModuleName; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return yield readJsonFile(join(pkgDir, "package.json")); | ||
return yield readJsonFile(join(pkgDir, 'package.json')); | ||
}); | ||
@@ -692,7 +692,7 @@ } | ||
return __awaiter(this, arguments, void 0, function* (appId, { pkgDir, instantModuleName }) { | ||
console.log("Pulling schema..."); | ||
console.log('Pulling schema...'); | ||
const pullRes = yield fetchJson({ | ||
path: `/dash/apps/${appId}/schema/pull`, | ||
debugName: "Schema pull", | ||
errorMessage: "Failed to pull schema.", | ||
debugName: 'Schema pull', | ||
errorMessage: 'Failed to pull schema.', | ||
}); | ||
@@ -703,3 +703,3 @@ if (!pullRes.ok) | ||
!countEntities(pullRes.data.schema.blobs)) { | ||
console.log("Schema is empty. Skipping."); | ||
console.log('Schema is empty. Skipping.'); | ||
return { ok: true }; | ||
@@ -709,9 +709,9 @@ } | ||
if (prevSchema) { | ||
const ok = yield promptOk("This will overwrite your local instant.schema file, OK to proceed?"); | ||
const ok = yield promptOk('This will overwrite your local instant.schema file, OK to proceed?'); | ||
if (!ok) | ||
return { ok: true }; | ||
} | ||
const schemaPath = join(pkgDir, "instant.schema.ts"); | ||
yield writeTypescript(schemaPath, generateSchemaTypescriptFile(prevSchema, pullRes.data.schema, instantModuleName), "utf-8"); | ||
console.log("✅ Wrote schema to instant.schema.ts"); | ||
const schemaPath = join(pkgDir, 'instant.schema.ts'); | ||
yield writeTypescript(schemaPath, generateSchemaTypescriptFile(prevSchema, pullRes.data.schema, instantModuleName), 'utf-8'); | ||
console.log('✅ Wrote schema to instant.schema.ts'); | ||
return { ok: true }; | ||
@@ -722,18 +722,18 @@ }); | ||
return __awaiter(this, arguments, void 0, function* (appId, { pkgDir, instantModuleName }) { | ||
console.log("Pulling perms..."); | ||
console.log('Pulling perms...'); | ||
const pullRes = yield fetchJson({ | ||
path: `/dash/apps/${appId}/perms/pull`, | ||
debugName: "Perms pull", | ||
errorMessage: "Failed to pull perms.", | ||
debugName: 'Perms pull', | ||
errorMessage: 'Failed to pull perms.', | ||
}); | ||
if (!pullRes.ok) | ||
return; | ||
if (yield pathExists(join(pkgDir, "instant.perms.ts"))) { | ||
const ok = yield promptOk("This will overwrite your local instant.perms file, OK to proceed?"); | ||
if (yield pathExists(join(pkgDir, 'instant.perms.ts'))) { | ||
const ok = yield promptOk('This will overwrite your local instant.perms file, OK to proceed?'); | ||
if (!ok) | ||
return; | ||
} | ||
const permsPath = join(pkgDir, "instant.perms.ts"); | ||
yield writeTypescript(permsPath, generatePermsTypescriptFile(pullRes.data.perms || {}, instantModuleName), "utf-8"); | ||
console.log("✅ Wrote permissions to instant.perms.ts"); | ||
const permsPath = join(pkgDir, 'instant.perms.ts'); | ||
yield writeTypescript(permsPath, generatePermsTypescriptFile(pullRes.data.perms || {}, instantModuleName), 'utf-8'); | ||
console.log('✅ Wrote permissions to instant.perms.ts'); | ||
return true; | ||
@@ -743,18 +743,18 @@ }); | ||
function indexingJobCompletedActionMessage(job) { | ||
if (job.job_type === "check-data-type") { | ||
if (job.job_type === 'check-data-type') { | ||
return `setting type of ${job.attr_name} to ${job.checked_data_type}`; | ||
} | ||
if (job.job_type === "remove-data-type") { | ||
if (job.job_type === 'remove-data-type') { | ||
return `removing type from ${job.attr_name}`; | ||
} | ||
if (job.job_type === "index") { | ||
if (job.job_type === 'index') { | ||
return `adding index to ${job.attr_name}`; | ||
} | ||
if (job.job_type === "remove-index") { | ||
if (job.job_type === 'remove-index') { | ||
return `removing index from ${job.attr_name}`; | ||
} | ||
if (job.job_type === "unique") { | ||
if (job.job_type === 'unique') { | ||
return `adding uniqueness constraint to ${job.attr_name}`; | ||
} | ||
if (job.job_type === "remove-unique") { | ||
if (job.job_type === 'remove-unique') { | ||
return `removing uniqueness constraint from ${job.attr_name}`; | ||
@@ -777,11 +777,11 @@ } | ||
const actionMessage = indexingJobCompletedActionMessage(job); | ||
if (job.job_status === "canceled") { | ||
if (job.job_status === 'canceled') { | ||
return `Canceled ${actionMessage} before it could finish.`; | ||
} | ||
if (job.job_status === "completed") { | ||
if (job.job_status === 'completed') { | ||
return `Finished ${actionMessage}.`; | ||
} | ||
if (job.job_status === "errored") { | ||
if (job.job_status === 'errored') { | ||
if ((_a = job.invalid_triples_sample) === null || _a === void 0 ? void 0 : _a.length) { | ||
const [etype, label] = job.attr_name.split("."); | ||
const [etype, label] = job.attr_name.split('.'); | ||
const samples = formatSamples(job.invalid_triples_sample); | ||
@@ -791,22 +791,22 @@ const longestValue = samples.reduce((acc, { value }) => Math.max(acc, value.length), | ||
label.length); | ||
let msg = `${chalk.red("INVALID DATA")} ${actionMessage}.\n`; | ||
let msg = `${chalk.red('INVALID DATA')} ${actionMessage}.\n`; | ||
if (job.invalid_unique_value) { | ||
msg += ` Found multiple entities with value ${truncate(JSON.stringify(job.invalid_unique_value), 64)}.\n`; | ||
} | ||
if (job.error === "triple-too-large-error") { | ||
if (job.error === 'triple-too-large-error') { | ||
msg += ` Some of the existing data is too large to index.\n`; | ||
} | ||
msg += ` First few examples:\n`; | ||
msg += ` ${chalk.bold("id")}${" ".repeat(35)}| ${chalk.bold(label)}${" ".repeat(longestValue - label.length)} | ${chalk.bold("type")}\n`; | ||
msg += ` ${"-".repeat(37)}|${"-".repeat(longestValue + 2)}|--------\n`; | ||
msg += ` ${chalk.bold('id')}${' '.repeat(35)}| ${chalk.bold(label)}${' '.repeat(longestValue - label.length)} | ${chalk.bold('type')}\n`; | ||
msg += ` ${'-'.repeat(37)}|${'-'.repeat(longestValue + 2)}|--------\n`; | ||
for (const triple of samples) { | ||
const urlParams = new URLSearchParams({ | ||
s: "main", | ||
s: 'main', | ||
app: job.app_id, | ||
t: "explorer", | ||
t: 'explorer', | ||
ns: etype, | ||
where: JSON.stringify(["id", triple.entity_id]), | ||
where: JSON.stringify(['id', triple.entity_id]), | ||
}); | ||
const url = new URL(instantDashOrigin); | ||
url.pathname = "/dash"; | ||
url.pathname = '/dash'; | ||
url.search = urlParams.toString(); | ||
@@ -816,3 +816,3 @@ const link = terminalLink(triple.entity_id, url.toString(), { | ||
}); | ||
msg += ` ${link} | ${triple.value}${" ".repeat(longestValue - triple.value.length)} | ${triple.json_type}\n`; | ||
msg += ` ${link} | ${triple.value}${' '.repeat(longestValue - triple.value.length)} | ${triple.json_type}\n`; | ||
} | ||
@@ -826,3 +826,3 @@ return msg; | ||
if (items.length === 0) { | ||
return ""; | ||
return ''; | ||
} | ||
@@ -835,3 +835,3 @@ if (items.length === 1) { | ||
} | ||
return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`; | ||
return `${items.slice(0, -1).join(', ')}, and ${items[items.length - 1]}`; | ||
} | ||
@@ -841,8 +841,8 @@ function jobGroupDescription(jobs) { | ||
const jobActions = { | ||
"check-data-type": "updating types", | ||
"remove-data-type": "updating types", | ||
index: "updating indexes", | ||
"remove-index": "updating indexes", | ||
unique: "updating uniqueness constraints", | ||
"remove-unique": "updating uniqueness constraints", | ||
'check-data-type': 'updating types', | ||
'remove-data-type': 'updating types', | ||
index: 'updating indexes', | ||
'remove-index': 'updating indexes', | ||
unique: 'updating uniqueness constraints', | ||
'remove-unique': 'updating uniqueness constraints', | ||
}; | ||
@@ -852,3 +852,3 @@ for (const job of jobs) { | ||
} | ||
return joinInSentence([...actions].sort()) || "updating schema"; | ||
return joinInSentence([...actions].sort()) || 'updating schema'; | ||
} | ||
@@ -859,5 +859,5 @@ function waitForIndexingJobsToFinish(appId, data) { | ||
const spinner = ora({ | ||
text: "checking data types", | ||
text: 'checking data types', | ||
}).start(); | ||
const groupId = data["group-id"]; | ||
const groupId = data['group-id']; | ||
let jobs = data.jobs; | ||
@@ -880,3 +880,3 @@ let waitMs = 20; | ||
} | ||
if (job.job_status === "waiting" || job.job_status === "processing") { | ||
if (job.job_status === 'waiting' || job.job_status === 'processing') { | ||
stillRunning = true; | ||
@@ -891,3 +891,3 @@ // Default estimate to high value to prevent % from jumping around | ||
const msg = indexingJobCompletedMessage(job); | ||
if (job.job_status === "errored") { | ||
if (job.job_status === 'errored') { | ||
errorMessages.push(msg); | ||
@@ -909,3 +909,3 @@ } | ||
if (completedMessages.length) { | ||
spinner.prefixText = completedMessages.join("\n") + "\n"; | ||
spinner.prefixText = completedMessages.join('\n') + '\n'; | ||
} | ||
@@ -915,6 +915,6 @@ waitMs = updated ? 1 : Math.min(10000, waitMs * 2); | ||
const res = yield fetchJson({ | ||
debugName: "Check indexing status", | ||
method: "GET", | ||
debugName: 'Check indexing status', | ||
method: 'GET', | ||
path: `/dash/apps/${appId}/indexing-jobs/group/${groupId}`, | ||
errorMessage: "Failed to check indexing status.", | ||
errorMessage: 'Failed to check indexing status.', | ||
}); | ||
@@ -927,4 +927,4 @@ if (!res.ok) { | ||
spinner.stopAndPersist({ | ||
text: "", | ||
prefixText: completedMessages.join("\n"), | ||
text: '', | ||
prefixText: completedMessages.join('\n'), | ||
}); | ||
@@ -936,3 +936,3 @@ // Log errors at the end so that they're easier to see. | ||
} | ||
console.log(chalk.red("Some steps failed while updating schema.")); | ||
console.log(chalk.red('Some steps failed while updating schema.')); | ||
process.exit(1); | ||
@@ -947,8 +947,8 @@ } | ||
return { ok: false }; | ||
console.log("Planning schema..."); | ||
console.log('Planning schema...'); | ||
const planRes = yield fetchJson({ | ||
method: "POST", | ||
method: 'POST', | ||
path: `/dash/apps/${appId}/schema/push/plan`, | ||
debugName: "Schema plan", | ||
errorMessage: "Failed to update schema.", | ||
debugName: 'Schema plan', | ||
errorMessage: 'Failed to update schema.', | ||
body: { | ||
@@ -963,45 +963,45 @@ schema, | ||
if (!planRes.data.steps.length) { | ||
console.log("No schema changes detected. Skipping."); | ||
console.log('No schema changes detected. Skipping.'); | ||
return { ok: true }; | ||
} | ||
console.log("The following changes will be applied to your production schema:"); | ||
console.log('The following changes will be applied to your production schema:'); | ||
for (const [action, attr] of planRes.data.steps) { | ||
switch (action) { | ||
case "add-attr": | ||
case "update-attr": { | ||
const valueType = attr["value-type"]; | ||
const isAdd = action === "add-attr"; | ||
if (valueType === "blob" && attrFwdLabel(attr) === "id") { | ||
console.log(`${isAdd ? chalk.magenta("ADD ENTITY") : chalk.magenta("UPDATE ENTITY")} ${attrFwdName(attr)}`); | ||
case 'add-attr': | ||
case 'update-attr': { | ||
const valueType = attr['value-type']; | ||
const isAdd = action === 'add-attr'; | ||
if (valueType === 'blob' && attrFwdLabel(attr) === 'id') { | ||
console.log(`${isAdd ? chalk.magenta('ADD ENTITY') : chalk.magenta('UPDATE ENTITY')} ${attrFwdName(attr)}`); | ||
break; | ||
} | ||
if (valueType === "blob") { | ||
console.log(`${isAdd ? chalk.green("ADD ATTR") : chalk.blue("UPDATE ATTR")} ${attrFwdName(attr)} :: unique=${attr["unique?"]}, indexed=${attr["index?"]}`); | ||
if (valueType === 'blob') { | ||
console.log(`${isAdd ? chalk.green('ADD ATTR') : chalk.blue('UPDATE ATTR')} ${attrFwdName(attr)} :: unique=${attr['unique?']}, indexed=${attr['index?']}`); | ||
break; | ||
} | ||
console.log(`${isAdd ? chalk.green("ADD LINK") : chalk.blue("UPDATE LINK")} ${attrFwdName(attr)} <=> ${attrRevName(attr)}`); | ||
console.log(`${isAdd ? chalk.green('ADD LINK') : chalk.blue('UPDATE LINK')} ${attrFwdName(attr)} <=> ${attrRevName(attr)}`); | ||
break; | ||
} | ||
case "check-data-type": { | ||
console.log(`${chalk.green("CHECK TYPE")} ${attrFwdName(attr)} => ${attr["checked-data-type"]}`); | ||
case 'check-data-type': { | ||
console.log(`${chalk.green('CHECK TYPE')} ${attrFwdName(attr)} => ${attr['checked-data-type']}`); | ||
break; | ||
} | ||
case "remove-data-type": { | ||
console.log(`${chalk.red("REMOVE TYPE")} ${attrFwdName(attr)} => any`); | ||
case 'remove-data-type': { | ||
console.log(`${chalk.red('REMOVE TYPE')} ${attrFwdName(attr)} => any`); | ||
break; | ||
} | ||
case "index": { | ||
console.log("%s on %s", chalk.green("ADD INDEX"), attrFwdName(attr)); | ||
case 'index': { | ||
console.log('%s on %s', chalk.green('ADD INDEX'), attrFwdName(attr)); | ||
break; | ||
} | ||
case "remove-index": { | ||
console.log("%s on %s", chalk.red("REMOVE INDEX"), attrFwdName(attr)); | ||
case 'remove-index': { | ||
console.log('%s on %s', chalk.red('REMOVE INDEX'), attrFwdName(attr)); | ||
break; | ||
} | ||
case "unique": { | ||
console.log("%s to %s", chalk.green("ADD UNIQUE CONSTRAINT"), attrFwdName(attr)); | ||
case 'unique': { | ||
console.log('%s to %s', chalk.green('ADD UNIQUE CONSTRAINT'), attrFwdName(attr)); | ||
break; | ||
} | ||
case "remove-unique": { | ||
console.log("%s from %s", chalk.red("REMOVE UNIQUE CONSTRAINT"), attrFwdName(attr)); | ||
case 'remove-unique': { | ||
console.log('%s from %s', chalk.red('REMOVE UNIQUE CONSTRAINT'), attrFwdName(attr)); | ||
break; | ||
@@ -1011,10 +1011,10 @@ } | ||
} | ||
const okPush = yield promptOk("OK to proceed?"); | ||
const okPush = yield promptOk('OK to proceed?'); | ||
if (!okPush) | ||
return { ok: true }; | ||
const applyRes = yield fetchJson({ | ||
method: "POST", | ||
method: 'POST', | ||
path: `/dash/apps/${appId}/schema/push/apply`, | ||
debugName: "Schema apply", | ||
errorMessage: "Failed to update schema.", | ||
debugName: 'Schema apply', | ||
errorMessage: 'Failed to update schema.', | ||
body: { | ||
@@ -1028,6 +1028,6 @@ schema, | ||
return applyRes; | ||
if (applyRes.data["indexing-jobs"]) { | ||
yield waitForIndexingJobsToFinish(appId, applyRes.data["indexing-jobs"]); | ||
if (applyRes.data['indexing-jobs']) { | ||
yield waitForIndexingJobsToFinish(appId, applyRes.data['indexing-jobs']); | ||
} | ||
console.log(chalk.green("Schema updated!")); | ||
console.log(chalk.green('Schema updated!')); | ||
return { ok: true }; | ||
@@ -1042,7 +1042,7 @@ }); | ||
} | ||
console.log("Planning perms..."); | ||
console.log('Planning perms...'); | ||
const prodPerms = yield fetchJson({ | ||
path: `/dash/apps/${appId}/perms/pull`, | ||
debugName: "Perms pull", | ||
errorMessage: "Failed to pull perms.", | ||
debugName: 'Perms pull', | ||
errorMessage: 'Failed to pull perms.', | ||
}); | ||
@@ -1053,15 +1053,15 @@ if (!prodPerms.ok) | ||
if (!diffedStr.length) { | ||
console.log("No perms changes detected. Exiting."); | ||
console.log('No perms changes detected. Exiting.'); | ||
return; | ||
} | ||
console.log("The following changes will be applied to your perms:"); | ||
console.log('The following changes will be applied to your perms:'); | ||
console.log(diffedStr); | ||
const okPush = yield promptOk("OK to proceed?"); | ||
const okPush = yield promptOk('OK to proceed?'); | ||
if (!okPush) | ||
return; | ||
const permsRes = yield fetchJson({ | ||
method: "POST", | ||
method: 'POST', | ||
path: `/dash/apps/${appId}/rules`, | ||
debugName: "Schema apply", | ||
errorMessage: "Failed to update schema.", | ||
debugName: 'Schema apply', | ||
errorMessage: 'Failed to update schema.', | ||
body: { | ||
@@ -1073,3 +1073,3 @@ code: perms, | ||
return; | ||
console.log(chalk.green("Permissions updated!")); | ||
console.log(chalk.green('Permissions updated!')); | ||
return true; | ||
@@ -1084,6 +1084,6 @@ }); | ||
const authCheckRes = yield fetchJson({ | ||
method: "POST", | ||
debugName: "Auth check", | ||
errorMessage: "Failed to check auth status.", | ||
path: "/dash/cli/auth/check", | ||
method: 'POST', | ||
debugName: 'Auth check', | ||
errorMessage: 'Failed to check auth status.', | ||
path: '/dash/cli/auth/check', | ||
body: { secret }, | ||
@@ -1096,10 +1096,10 @@ noAuth: true, | ||
} | ||
if (((_d = (_c = (_b = authCheckRes.data) === null || _b === void 0 ? void 0 : _b.hint.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.issue) === "waiting-for-user") { | ||
if (((_d = (_c = (_b = authCheckRes.data) === null || _b === void 0 ? void 0 : _b.hint.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.issue) === 'waiting-for-user') { | ||
continue; | ||
} | ||
error("Failed to authenticate "); | ||
error('Failed to authenticate '); | ||
prettyPrintJSONErr(authCheckRes.data); | ||
return; | ||
} | ||
error("Timed out waiting for authentication"); | ||
error('Timed out waiting for authentication'); | ||
return null; | ||
@@ -1136,4 +1136,4 @@ }); | ||
const res = yield fetch(`${instantBackendOrigin}${path}`, { | ||
method: method !== null && method !== void 0 ? method : "GET", | ||
headers: Object.assign(Object.assign({}, (withAuth ? { Authorization: `Bearer ${authToken}` } : {})), { "Content-Type": "application/json", "Instant-CLI-Version": version }), | ||
method: method !== null && method !== void 0 ? method : 'GET', | ||
headers: Object.assign(Object.assign({}, (withAuth ? { Authorization: `Bearer ${authToken}` } : {})), { 'Content-Type': 'application/json', 'Instant-CLI-Version': version }), | ||
body: body ? JSON.stringify(body) : undefined, | ||
@@ -1143,3 +1143,3 @@ signal: AbortSignal.timeout(timeoutMs), | ||
if (verbose) { | ||
console.log(debugName, "response:", res.status, res.statusText); | ||
console.log(debugName, 'response:', res.status, res.statusText); | ||
} | ||
@@ -1154,3 +1154,3 @@ let data; | ||
if (verbose && data) { | ||
console.log(debugName, "json:", JSON.stringify(data, null, 2)); | ||
console.log(debugName, 'json:', JSON.stringify(data, null, 2)); | ||
} | ||
@@ -1168,3 +1168,3 @@ if (!res.ok) { | ||
if (withErrorLogging) { | ||
if (err.name === "AbortError") { | ||
if (err.name === 'AbortError') { | ||
error(`Timeout: It took more than ${timeoutMs / 60000} minutes to get the result.`); | ||
@@ -1187,7 +1187,7 @@ } | ||
for (const err of data.hint.errors) { | ||
error(`${err.in ? err.in.join("->") + ": " : ""}${err.message}`); | ||
error(`${err.in ? err.in.join('->') + ': ' : ''}${err.message}`); | ||
} | ||
} | ||
if (!data) { | ||
error("Failed to parse error response"); | ||
error('Failed to parse error response'); | ||
} | ||
@@ -1233,4 +1233,4 @@ } | ||
{ | ||
files: "instant.perms", | ||
extensions: ["ts", "mts", "cts", "js", "mjs", "cjs", "json"], | ||
files: 'instant.perms', | ||
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json'], | ||
transform: transformImports, | ||
@@ -1253,3 +1253,3 @@ }, | ||
if (!perms) { | ||
error(`We couldn't find your ${chalk.yellow("`instant.perms.ts`")} file. Make sure it's in the root directory.`); | ||
error(`We couldn't find your ${chalk.yellow('`instant.perms.ts`')} file. Make sure it's in the root directory.`); | ||
} | ||
@@ -1265,4 +1265,4 @@ return perms; | ||
{ | ||
files: "instant.schema", | ||
extensions: ["ts", "mts", "cts", "js", "mjs", "cjs"], | ||
files: 'instant.schema', | ||
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs'], | ||
transform: transformImports, | ||
@@ -1283,4 +1283,4 @@ }, | ||
{ | ||
files: "instant.config", | ||
extensions: ["ts", "mts", "cts", "js", "mjs", "cjs", "json"], | ||
files: 'instant.config', | ||
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json'], | ||
}, | ||
@@ -1298,3 +1298,3 @@ ], | ||
if (!schema) { | ||
error(`We couldn't find your ${chalk.yellow("`instant.schema.ts`")} file. Make sure it's in the root directory.`); | ||
error(`We couldn't find your ${chalk.yellow('`instant.schema.ts`')} file. Make sure it's in the root directory.`); | ||
return; | ||
@@ -1314,3 +1314,3 @@ } | ||
} | ||
const authToken = yield readFile(getAuthPaths().authConfigFilePath, "utf-8").catch(() => null); | ||
const authToken = yield readFile(getAuthPaths().authConfigFilePath, 'utf-8').catch(() => null); | ||
return authToken; | ||
@@ -1323,3 +1323,3 @@ }); | ||
if (!token) { | ||
error(`Looks like you are not logged in. Please log in with ${chalk.green("`instant-cli login`")}`); | ||
error(`Looks like you are not logged in. Please log in with ${chalk.green('`instant-cli login`')}`); | ||
} | ||
@@ -1345,9 +1345,9 @@ return token; | ||
}); | ||
return writeFile(authPaths.authConfigFilePath, authToken, "utf-8"); | ||
return writeFile(authPaths.authConfigFilePath, authToken, 'utf-8'); | ||
}); | ||
} | ||
function getAuthPaths() { | ||
const key = `instantdb-${dev ? "dev" : "prod"}`; | ||
const key = `instantdb-${dev ? 'dev' : 'prod'}`; | ||
const { config: appConfigDirPath } = envPaths(key); | ||
const authConfigFilePath = join(appConfigDirPath, "a"); | ||
const authConfigFilePath = join(appConfigDirPath, 'a'); | ||
return { authConfigFilePath, appConfigDirPath }; | ||
@@ -1371,15 +1371,15 @@ } | ||
var _a; | ||
return (_a = attr["forward-identity"]) === null || _a === void 0 ? void 0 : _a[2]; | ||
return (_a = attr['forward-identity']) === null || _a === void 0 ? void 0 : _a[2]; | ||
} | ||
function attrFwdEtype(attr) { | ||
var _a; | ||
return (_a = attr["forward-identity"]) === null || _a === void 0 ? void 0 : _a[1]; | ||
return (_a = attr['forward-identity']) === null || _a === void 0 ? void 0 : _a[1]; | ||
} | ||
function attrRevLabel(attr) { | ||
var _a; | ||
return (_a = attr["reverse-identity"]) === null || _a === void 0 ? void 0 : _a[2]; | ||
return (_a = attr['reverse-identity']) === null || _a === void 0 ? void 0 : _a[2]; | ||
} | ||
function attrRevEtype(attr) { | ||
var _a; | ||
return (_a = attr["reverse-identity"]) === null || _a === void 0 ? void 0 : _a[1]; | ||
return (_a = attr['reverse-identity']) === null || _a === void 0 ? void 0 : _a[1]; | ||
} | ||
@@ -1390,3 +1390,3 @@ function attrFwdName(attr) { | ||
function attrRevName(attr) { | ||
if (attr["reverse-identity"]) { | ||
if (attr['reverse-identity']) { | ||
return `${attrRevEtype(attr)}.${attrRevLabel(attr)}`; | ||
@@ -1397,6 +1397,6 @@ } | ||
export const rels = { | ||
"many-false": ["many", "many"], | ||
"one-true": ["one", "one"], | ||
"many-true": ["many", "one"], | ||
"one-false": ["one", "many"], | ||
'many-false': ['many', 'many'], | ||
'one-true': ['one', 'one'], | ||
'many-true': ['many', 'one'], | ||
'one-false': ['one', 'many'], | ||
}; | ||
@@ -1437,3 +1437,3 @@ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; | ||
if (found && !isUUID(found.value)) { | ||
error(`Found ${chalk.green("`" + found.envName + "`")} but it's not a valid UUID.`); | ||
error(`Found ${chalk.green('`' + found.envName + '`')} but it's not a valid UUID.`); | ||
return { ok: false, found }; | ||
@@ -1472,3 +1472,3 @@ } | ||
import type { InstantRules } from "${instantModuleName !== null && instantModuleName !== void 0 ? instantModuleName : "@instantdb/core"}"; | ||
import type { InstantRules } from "${instantModuleName !== null && instantModuleName !== void 0 ? instantModuleName : '@instantdb/core'}"; | ||
@@ -1481,3 +1481,3 @@ const rules = ${rulesTxt} satisfies InstantRules; | ||
function inferredType(config) { | ||
const inferredList = config["inferred-types"]; | ||
const inferredList = config['inferred-types']; | ||
const hasJustOne = (inferredList === null || inferredList === void 0 ? void 0 : inferredList.length) === 1; | ||
@@ -1489,10 +1489,10 @@ if (!hasJustOne) | ||
function deriveClientType(attr) { | ||
if (attr["checked-data-type"]) { | ||
return { type: attr["checked-data-type"], origin: "checked" }; | ||
if (attr['checked-data-type']) { | ||
return { type: attr['checked-data-type'], origin: 'checked' }; | ||
} | ||
const inferred = inferredType(attr); | ||
if (inferred) { | ||
return { type: inferred, origin: "inferred" }; | ||
return { type: inferred, origin: 'inferred' }; | ||
} | ||
return { type: "any", origin: "unknown" }; | ||
return { type: 'any', origin: 'unknown' }; | ||
} | ||
@@ -1510,3 +1510,3 @@ function schemaBlobToCodeStr(name, attrs) { | ||
sortedEntries(attrs) | ||
.filter(([name]) => name !== "id") | ||
.filter(([name]) => name !== 'id') | ||
.map(([name, config]) => { | ||
@@ -1519,8 +1519,8 @@ const { type } = deriveClientType(config); | ||
`i.${type}()`, | ||
config["unique?"] ? ".unique()" : "", | ||
config["index?"] ? ".indexed()" : "", | ||
config['unique?'] ? '.unique()' : '', | ||
config['index?'] ? '.indexed()' : '', | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
}) | ||
.join("\n"), | ||
.join('\n'), | ||
`\n`, | ||
@@ -1530,3 +1530,3 @@ ` `, | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
} | ||
@@ -1556,3 +1556,3 @@ /** | ||
.map(([name, attr]) => { | ||
const type = attr["valueType"] || "any"; | ||
const type = attr['valueType'] || 'any'; | ||
return [ | ||
@@ -1563,8 +1563,8 @@ ` `, | ||
`i.${type}()`, | ||
(attr === null || attr === void 0 ? void 0 : attr.config["unique"]) ? ".unique()" : "", | ||
(attr === null || attr === void 0 ? void 0 : attr.config["indexed"]) ? ".indexed()" : "", | ||
(attr === null || attr === void 0 ? void 0 : attr.config['unique']) ? '.unique()' : '', | ||
(attr === null || attr === void 0 ? void 0 : attr.config['indexed']) ? '.indexed()' : '', | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
}) | ||
.join("\n"), | ||
.join('\n'), | ||
`\n`, | ||
@@ -1574,8 +1574,8 @@ ` `, | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
} | ||
function roomDefToCodeStr(room) { | ||
let ret = "{"; | ||
let ret = '{'; | ||
if (room.presence) { | ||
ret += `${entityDefToCodeStr("presence", room.presence)}`; | ||
ret += `${entityDefToCodeStr('presence', room.presence)}`; | ||
} | ||
@@ -1589,15 +1589,15 @@ if (room.topics) { | ||
} | ||
ret += "}"; | ||
ret += '}'; | ||
return ret; | ||
} | ||
function roomsCodeStr(rooms) { | ||
let ret = "{"; | ||
let ret = '{'; | ||
for (const [roomType, roomDef] of Object.entries(rooms)) { | ||
ret += `"${roomType}": ${roomDefToCodeStr(roomDef)},`; | ||
} | ||
ret += "}"; | ||
ret += '}'; | ||
return ret; | ||
} | ||
function easyPlural(strn, n) { | ||
return n === 1 ? strn : strn + "s"; | ||
return n === 1 ? strn : strn + 's'; | ||
} | ||
@@ -1608,12 +1608,12 @@ function generateSchemaTypescriptFile(prevSchema, newSchema, instantModuleName) { | ||
.map(([name, attrs]) => schemaBlobToCodeStr(name, attrs)) | ||
.join("\n"); | ||
.join('\n'); | ||
const inferredAttrs = Object.values(newSchema.blobs) | ||
.flatMap(Object.values) | ||
.filter((attr) => attrFwdLabel(attr) !== "id" && | ||
deriveClientType(attr).origin === "inferred"); | ||
.filter((attr) => attrFwdLabel(attr) !== 'id' && | ||
deriveClientType(attr).origin === 'inferred'); | ||
const entitiesObjCode = `{\n${entitiesEntriesCode}\n}`; | ||
const etypes = Object.keys(newSchema.blobs); | ||
const hasOnlyUserTable = etypes.length === 1 && etypes[0] === "$users"; | ||
const hasOnlyUserTable = etypes.length === 1 && etypes[0] === '$users'; | ||
const entitiesComment = inferredAttrs.length > 0 | ||
? `// We inferred ${inferredAttrs.length} ${easyPlural("attribute", inferredAttrs.length)}! | ||
? `// We inferred ${inferredAttrs.length} ${easyPlural('attribute', inferredAttrs.length)}! | ||
// Take a look at this schema, and if everything looks good, | ||
@@ -1627,8 +1627,8 @@ // run \`push schema\` again to enforce the types.` | ||
`.trim() | ||
: ""; | ||
: ''; | ||
// links | ||
const linksEntries = Object.fromEntries(sortedEntries(newSchema.refs).map(([_name, config]) => { | ||
const [, fe, flabel] = config["forward-identity"]; | ||
const [, re, rlabel] = config["reverse-identity"]; | ||
const [fhas, rhas] = rels[`${config.cardinality}-${config["unique?"]}`]; | ||
const [, fe, flabel] = config['forward-identity']; | ||
const [, re, rlabel] = config['reverse-identity']; | ||
const [fhas, rhas] = rels[`${config.cardinality}-${config['unique?']}`]; | ||
return [ | ||
@@ -1650,3 +1650,3 @@ `${fe}${capitalizeFirstLetter(flabel)}`, | ||
})); | ||
const linksEntriesCode = JSON.stringify(linksEntries, null, " ").trim(); | ||
const linksEntriesCode = JSON.stringify(linksEntries, null, ' ').trim(); | ||
const hasNoLinks = Object.keys(linksEntries).length === 0; | ||
@@ -1660,3 +1660,3 @@ const linksComment = hasNoLinks | ||
`.trim() | ||
: ""; | ||
: ''; | ||
// rooms | ||
@@ -1670,3 +1670,3 @@ const rooms = (prevSchema === null || prevSchema === void 0 ? void 0 : prevSchema.rooms) || {}; | ||
`.trim() | ||
: ""; | ||
: ''; | ||
const kv = (k, v, comment) => { | ||
@@ -1681,8 +1681,8 @@ return comment | ||
return ` | ||
import { i } from "${instantModuleName !== null && instantModuleName !== void 0 ? instantModuleName : "@instantdb/core"}"; | ||
import { i } from "${instantModuleName !== null && instantModuleName !== void 0 ? instantModuleName : '@instantdb/core'}"; | ||
const _schema = i.schema({ | ||
${kv("entities", entitiesObjCode, entitiesComment)}, | ||
${kv("links", linksEntriesCode, linksComment)}, | ||
${kv("rooms", roomsCode, roomsComment)} | ||
${kv('entities', entitiesObjCode, entitiesComment)}, | ||
${kv('links', linksEntriesCode, linksComment)}, | ||
${kv('rooms', roomsCode, roomsComment)} | ||
}); | ||
@@ -1689,0 +1689,0 @@ |
@@ -1,3 +0,3 @@ | ||
import type { Theme } from "@inquirer/core"; | ||
import type { Prompt } from "@inquirer/type"; | ||
import type { Theme } from '@inquirer/core'; | ||
import type { Prompt } from '@inquirer/type'; | ||
type InquirerToggleConfig = { | ||
@@ -9,7 +9,7 @@ message: string; | ||
inactive?: string; | ||
prefix?: Theme["prefix"]; | ||
prefix?: Theme['prefix']; | ||
style?: { | ||
message?: Theme["style"]["message"]; | ||
answer?: Theme["style"]["answer"]; | ||
highlight?: Theme["style"]["highlight"]; | ||
message?: Theme['style']['message']; | ||
answer?: Theme['style']['answer']; | ||
highlight?: Theme['style']['highlight']; | ||
}; | ||
@@ -16,0 +16,0 @@ }; |
@@ -1,13 +0,13 @@ | ||
import { isDownKey, isUpKey, useKeypress, useState, isEnterKey, } from "@inquirer/core"; | ||
import { createPrompt, usePrefix, makeTheme } from "@inquirer/core"; | ||
import ansiEscapes from "ansi-escapes"; | ||
import { isDownKey, isUpKey, useKeypress, useState, isEnterKey, } from '@inquirer/core'; | ||
import { createPrompt, usePrefix, makeTheme } from '@inquirer/core'; | ||
import ansiEscapes from 'ansi-escapes'; | ||
function isLeftKey(key) { | ||
return key.name === "left"; | ||
return key.name === 'left'; | ||
} | ||
function isRightKey(key) { | ||
return key.name === "right"; | ||
return key.name === 'right'; | ||
} | ||
const prompt = createPrompt((config, done) => { | ||
var _a; | ||
const theme = makeTheme({ active: "yes", inactive: "no" }, config.theme); | ||
const theme = makeTheme({ active: 'yes', inactive: 'no' }, config.theme); | ||
const prefix = usePrefix({ theme }); | ||
@@ -14,0 +14,0 @@ const [value, setValue] = useState((_a = config.default) !== null && _a !== void 0 ? _a : false); |
@@ -1,4 +0,4 @@ | ||
import { PathLike } from "fs"; | ||
import { PathLike } from 'fs'; | ||
export declare function pathExists(p: PathLike): Promise<boolean>; | ||
export declare function readJsonFile<T = Record<string, any>>(p: PathLike): Promise<T | null>; | ||
//# sourceMappingURL=fs.d.ts.map |
@@ -10,3 +10,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
}; | ||
import { readFile, stat } from "fs/promises"; | ||
import { readFile, stat } from 'fs/promises'; | ||
export function pathExists(p) { | ||
@@ -29,3 +29,3 @@ return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const data = yield readFile(p, "utf-8"); | ||
const data = yield readFile(p, 'utf-8'); | ||
return JSON.parse(data); | ||
@@ -32,0 +32,0 @@ } |
@@ -13,11 +13,11 @@ // Note: | ||
}; | ||
import { pathExists, readJsonFile } from "./fs.js"; | ||
import path from "path"; | ||
import { pathExists, readJsonFile } from './fs.js'; | ||
import path from 'path'; | ||
function detectPackageManager(destPath) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const lockfileNames = { | ||
"yarn.lock": "yarn", | ||
"package-lock.json": "npm", | ||
"pnpm-lock.yaml": "pnpm", | ||
"bun.lockb": "bun", | ||
'yarn.lock': 'yarn', | ||
'package-lock.json': 'npm', | ||
'pnpm-lock.yaml': 'pnpm', | ||
'bun.lockb': 'bun', | ||
}; | ||
@@ -31,3 +31,3 @@ for (const dir of traverseUpDirectories(destPath)) { | ||
} | ||
const packageJsonPath = path.join(dir, "package.json"); | ||
const packageJsonPath = path.join(dir, 'package.json'); | ||
if (yield pathExists(packageJsonPath)) { | ||
@@ -46,3 +46,3 @@ const packageJson = yield readJsonFile(packageJsonPath); | ||
} | ||
return "npm"; | ||
return 'npm'; | ||
}); | ||
@@ -64,3 +64,3 @@ } | ||
return null; | ||
const atIndex = packageManager.lastIndexOf("@"); | ||
const atIndex = packageManager.lastIndexOf('@'); | ||
if (atIndex <= 0) | ||
@@ -76,3 +76,3 @@ return null; // '@' at position 0 is invalid | ||
function getInstallCommand(packageManager, moduleName) { | ||
if (packageManager === "npm") { | ||
if (packageManager === 'npm') { | ||
return `npm install ${moduleName}`; | ||
@@ -79,0 +79,0 @@ } |
export default version; | ||
declare const version: "v0.17.12"; | ||
declare const version: "v0.17.13"; | ||
//# sourceMappingURL=version.d.ts.map |
// Autogenerated by publish_packages.clj | ||
const version = "v0.17.12"; | ||
const version = 'v0.17.13'; | ||
export default version; | ||
//# sourceMappingURL=version.js.map |
{ | ||
"name": "instant-cli", | ||
"type": "module", | ||
"version": "v0.17.12", | ||
"version": "v0.17.13", | ||
"description": "Instant's CLI", | ||
@@ -6,0 +6,0 @@ "bin": { |
702
src/index.js
// @ts-check | ||
import version from "./version.js"; | ||
import { mkdir, writeFile, readFile } from "fs/promises"; | ||
import { join } from "path"; | ||
import { randomUUID } from "crypto"; | ||
import jsonDiff from "json-diff"; | ||
import dotenv from "dotenv"; | ||
import chalk from "chalk"; | ||
import { program, Option } from "commander"; | ||
import { input, select } from "@inquirer/prompts"; | ||
import envPaths from "env-paths"; | ||
import { loadConfig } from "unconfig"; | ||
import { packageDirectory } from "pkg-dir"; | ||
import openInBrowser from "open"; | ||
import ora from "ora"; | ||
import terminalLink from "terminal-link"; | ||
import { exec } from "child_process"; | ||
import { promisify } from "util"; | ||
import version from './version.js'; | ||
import { mkdir, writeFile, readFile } from 'fs/promises'; | ||
import { join } from 'path'; | ||
import { randomUUID } from 'crypto'; | ||
import jsonDiff from 'json-diff'; | ||
import dotenv from 'dotenv'; | ||
import chalk from 'chalk'; | ||
import { program, Option } from 'commander'; | ||
import { input, select } from '@inquirer/prompts'; | ||
import envPaths from 'env-paths'; | ||
import { loadConfig } from 'unconfig'; | ||
import { packageDirectory } from 'pkg-dir'; | ||
import openInBrowser from 'open'; | ||
import ora from 'ora'; | ||
import terminalLink from 'terminal-link'; | ||
import { exec } from 'child_process'; | ||
import { promisify } from 'util'; | ||
import { | ||
detectPackageManager, | ||
getInstallCommand, | ||
} from "./util/packageManager.js"; | ||
import { pathExists, readJsonFile } from "./util/fs.js"; | ||
import prettier from "prettier"; | ||
import toggle from "./toggle.js"; | ||
} from './util/packageManager.js'; | ||
import { pathExists, readJsonFile } from './util/fs.js'; | ||
import prettier from 'prettier'; | ||
import toggle from './toggle.js'; | ||
@@ -39,7 +39,7 @@ const execAsync = promisify(exec); | ||
function warn(firstArg, ...rest) { | ||
console.warn(chalk.yellow("[warning]") + " " + firstArg, ...rest); | ||
console.warn(chalk.yellow('[warning]') + ' ' + firstArg, ...rest); | ||
} | ||
function error(firstArg, ...rest) { | ||
console.error(chalk.red("[error]") + " " + firstArg, ...rest); | ||
console.error(chalk.red('[error]') + ' ' + firstArg, ...rest); | ||
} | ||
@@ -50,8 +50,8 @@ | ||
const potentialEnvs = { | ||
catchall: "INSTANT_APP_ID", | ||
next: "NEXT_PUBLIC_INSTANT_APP_ID", | ||
svelte: "PUBLIC_INSTANT_APP_ID", | ||
vite: "VITE_INSTANT_APP_ID", | ||
expo: "EXPO_PUBLIC_INSTANT_APP_ID", | ||
nuxt: "NUXT_PUBLIC_INSTANT_APP_ID", | ||
catchall: 'INSTANT_APP_ID', | ||
next: 'NEXT_PUBLIC_INSTANT_APP_ID', | ||
svelte: 'PUBLIC_INSTANT_APP_ID', | ||
vite: 'VITE_INSTANT_APP_ID', | ||
expo: 'EXPO_PUBLIC_INSTANT_APP_ID', | ||
nuxt: 'NUXT_PUBLIC_INSTANT_APP_ID', | ||
}; | ||
@@ -62,35 +62,35 @@ | ||
if (!packageJSON) { | ||
return "catchall"; | ||
return 'catchall'; | ||
} | ||
if (packageJSON.dependencies?.next) { | ||
return "next"; | ||
return 'next'; | ||
} | ||
if (packageJSON.devDependencies?.svelte) { | ||
return "svelte"; | ||
return 'svelte'; | ||
} | ||
if (packageJSON.devDependencies?.vite) { | ||
return "vite"; | ||
return 'vite'; | ||
} | ||
if (packageJSON.dependencies?.expo) { | ||
return "expo"; | ||
return 'expo'; | ||
} | ||
if (packageJSON.dependencies?.nuxt) { | ||
return "nuxt"; | ||
return 'nuxt'; | ||
} | ||
return "catchall"; | ||
return 'catchall'; | ||
} | ||
const instantDashOrigin = dev | ||
? "http://localhost:3000" | ||
: "https://instantdb.com"; | ||
? 'http://localhost:3000' | ||
: 'https://instantdb.com'; | ||
const instantBackendOrigin = | ||
process.env.INSTANT_CLI_API_URI || | ||
(dev ? "http://localhost:8888" : "https://api.instantdb.com"); | ||
(dev ? 'http://localhost:8888' : 'https://api.instantdb.com'); | ||
const PUSH_PULL_OPTIONS = new Set(["schema", "perms", "all"]); | ||
const PUSH_PULL_OPTIONS = new Set(['schema', 'perms', 'all']); | ||
function convertArgToBagWithErrorLogging(arg) { | ||
if (!arg) { | ||
return { ok: true, bag: "all" }; | ||
return { ok: true, bag: 'all' }; | ||
} else if (PUSH_PULL_OPTIONS.has(arg.trim().toLowerCase())) { | ||
@@ -100,3 +100,3 @@ return { ok: true, bag: arg }; | ||
error( | ||
`${chalk.red(arg)} must be one of ${chalk.green(Array.from(PUSH_PULL_OPTIONS).join(", "))}`, | ||
`${chalk.red(arg)} must be one of ${chalk.green(Array.from(PUSH_PULL_OPTIONS).join(', '))}`, | ||
); | ||
@@ -114,3 +114,3 @@ return { ok: false }; | ||
warnDeprecation(`${cmdName} ${arg}`, `${cmdName} --app ${arg}`); | ||
return { ok: true, bag: "all", opts: { ...opts, app: arg } }; | ||
return { ok: true, bag: 'all', opts: { ...opts, app: arg } }; | ||
} | ||
@@ -134,18 +134,18 @@ const { ok, bag } = convertArgToBagWithErrorLogging(arg); | ||
// Header -- this shows up in every command | ||
const logoChalk = chalk.bold("instant-cli"); | ||
const logoChalk = chalk.bold('instant-cli'); | ||
const versionChalk = chalk.dim(`${version.trim()}`); | ||
const headerChalk = `${logoChalk} ${versionChalk} ` + "\n"; | ||
const headerChalk = `${logoChalk} ${versionChalk} ` + '\n'; | ||
// Help Footer -- this only shows up in help commands | ||
const helpFooterChalk = | ||
"\n" + | ||
chalk.dim.bold("Want to learn more?") + | ||
"\n" + | ||
`Check out the docs: ${chalk.blueBright.underline("https://instantdb.com/docs")} | ||
Join the Discord: ${chalk.blueBright.underline("https://discord.com/invite/VU53p7uQcE")} | ||
'\n' + | ||
chalk.dim.bold('Want to learn more?') + | ||
'\n' + | ||
`Check out the docs: ${chalk.blueBright.underline('https://instantdb.com/docs')} | ||
Join the Discord: ${chalk.blueBright.underline('https://discord.com/invite/VU53p7uQcE')} | ||
`.trim(); | ||
program.addHelpText("after", helpFooterChalk); | ||
program.addHelpText('after', helpFooterChalk); | ||
program.addHelpText("beforeAll", headerChalk); | ||
program.addHelpText('beforeAll', headerChalk); | ||
@@ -184,7 +184,7 @@ function getLocalAndGlobalOptions(cmd, helper) { | ||
function formatList(textArray) { | ||
return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth)); | ||
return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); | ||
} | ||
// Usage | ||
let output = [`${helper.commandUsage(cmd)}`, ""]; | ||
let output = [`${helper.commandUsage(cmd)}`, '']; | ||
@@ -194,3 +194,3 @@ // Description | ||
if (commandDescription.length > 0) { | ||
output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]); | ||
output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']); | ||
} | ||
@@ -207,5 +207,5 @@ | ||
output = output.concat([ | ||
chalk.dim.bold("Arguments"), | ||
chalk.dim.bold('Arguments'), | ||
formatList(argumentList), | ||
"", | ||
'', | ||
]); | ||
@@ -227,5 +227,5 @@ } | ||
output = output.concat([ | ||
chalk.dim.bold("Options"), | ||
chalk.dim.bold('Options'), | ||
formatList(optionList), | ||
"", | ||
'', | ||
]); | ||
@@ -242,5 +242,5 @@ } | ||
output = output.concat([ | ||
chalk.dim.bold("Commands"), | ||
chalk.dim.bold('Commands'), | ||
formatList(commandList), | ||
"", | ||
'', | ||
]); | ||
@@ -258,5 +258,5 @@ } | ||
output = output.concat([ | ||
chalk.dim.bold("Global Options"), | ||
chalk.dim.bold('Global Options'), | ||
formatList(globalOptionList), | ||
"", | ||
'', | ||
]); | ||
@@ -266,3 +266,3 @@ } | ||
return output.join("\n"); | ||
return output.join('\n'); | ||
} | ||
@@ -292,7 +292,7 @@ | ||
warn( | ||
chalk.yellow("`instant-cli " + oldCmd + "` is deprecated.") + | ||
" Use " + | ||
chalk.green("`instant-cli " + newCmd + "`") + | ||
" instead." + | ||
"\n", | ||
chalk.yellow('`instant-cli ' + oldCmd + '` is deprecated.') + | ||
' Use ' + | ||
chalk.green('`instant-cli ' + newCmd + '`') + | ||
' instead.' + | ||
'\n', | ||
); | ||
@@ -302,7 +302,7 @@ } | ||
program | ||
.name("instant-cli") | ||
.addOption(globalOption("-t --token <token>", "Auth token override")) | ||
.addOption(globalOption("-y --yes", "Answer 'yes' to all prompts")) | ||
.name('instant-cli') | ||
.addOption(globalOption('-t --token <token>', 'Auth token override')) | ||
.addOption(globalOption('-y --yes', "Answer 'yes' to all prompts")) | ||
.addOption( | ||
globalOption("-v --version", "Print the version number", () => { | ||
globalOption('-v --version', 'Print the version number', () => { | ||
console.log(version); | ||
@@ -312,9 +312,9 @@ process.exit(0); | ||
) | ||
.addHelpOption(globalOption("-h --help", "Print the help text for a command")) | ||
.usage(`<command> ${chalk.dim("[options] [args]")}`); | ||
.addHelpOption(globalOption('-h --help', 'Print the help text for a command')) | ||
.usage(`<command> ${chalk.dim('[options] [args]')}`); | ||
program | ||
.command("login") | ||
.description("Log into your account") | ||
.option("-p --print", "Prints the auth token into the console.") | ||
.command('login') | ||
.description('Log into your account') | ||
.option('-p --print', 'Prints the auth token into the console.') | ||
.action(async (opts) => { | ||
@@ -326,10 +326,10 @@ console.log("Let's log you in!"); | ||
program | ||
.command("init") | ||
.description("Set up a new project.") | ||
.command('init') | ||
.description('Set up a new project.') | ||
.option( | ||
"-a --app <app-id>", | ||
"If you have an existing app ID, we can pull schema and perms from there.", | ||
'-a --app <app-id>', | ||
'If you have an existing app ID, we can pull schema and perms from there.', | ||
) | ||
.action(async function (opts) { | ||
await handlePull("all", opts); | ||
await handlePull('all', opts); | ||
}); | ||
@@ -341,12 +341,12 @@ | ||
program | ||
.command("push-schema", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Push schema to production.") | ||
.command('push-schema', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Push schema to production.') | ||
.option( | ||
"--skip-check-types", | ||
'--skip-check-types', | ||
"Don't check types on the server when pushing schema", | ||
) | ||
.action(async (appIdOrName, opts) => { | ||
warnDeprecation("push-schema", "push schema"); | ||
await handlePush("schema", { app: appIdOrName, ...opts }); | ||
warnDeprecation('push-schema', 'push schema'); | ||
await handlePush('schema', { app: appIdOrName, ...opts }); | ||
}); | ||
@@ -358,27 +358,27 @@ | ||
program | ||
.command("push-perms", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Push perms to production.") | ||
.command('push-perms', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Push perms to production.') | ||
.action(async (appIdOrName) => { | ||
warnDeprecation("push-perms", "push perms"); | ||
await handlePush("perms", { app: appIdOrName }); | ||
warnDeprecation('push-perms', 'push perms'); | ||
await handlePush('perms', { app: appIdOrName }); | ||
}); | ||
program | ||
.command("push") | ||
.command('push') | ||
.argument( | ||
"[schema|perms|all]", | ||
"Which configuration to push. Defaults to `all`", | ||
'[schema|perms|all]', | ||
'Which configuration to push. Defaults to `all`', | ||
) | ||
.option( | ||
"-a --app <app-id>", | ||
"App ID to push too. Defaults to *_INSTANT_APP_ID in .env", | ||
'-a --app <app-id>', | ||
'App ID to push too. Defaults to *_INSTANT_APP_ID in .env', | ||
) | ||
.option( | ||
"--skip-check-types", | ||
'--skip-check-types', | ||
"Don't check types on the server when pushing schema", | ||
) | ||
.description("Push schema and perm files to production.") | ||
.description('Push schema and perm files to production.') | ||
.action(async function (arg, inputOpts) { | ||
const ret = convertPushPullToCurrentFormat("push", arg, inputOpts); | ||
const ret = convertPushPullToCurrentFormat('push', arg, inputOpts); | ||
if (!ret.ok) return; | ||
@@ -393,8 +393,8 @@ const { bag, opts } = ret; | ||
program | ||
.command("pull-schema", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Generate instant.schema.ts from production") | ||
.command('pull-schema', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Generate instant.schema.ts from production') | ||
.action(async (appIdOrName) => { | ||
warnDeprecation("pull-schema", "pull schema"); | ||
await handlePull("schema", { app: appIdOrName }); | ||
warnDeprecation('pull-schema', 'pull schema'); | ||
await handlePull('schema', { app: appIdOrName }); | ||
}); | ||
@@ -406,23 +406,23 @@ | ||
program | ||
.command("pull-perms", { hidden: true }) | ||
.argument("[app-id]") | ||
.description("Generate instant.perms.ts from production.") | ||
.command('pull-perms', { hidden: true }) | ||
.argument('[app-id]') | ||
.description('Generate instant.perms.ts from production.') | ||
.action(async (appIdOrName) => { | ||
warnDeprecation("pull-perms", "pull perms"); | ||
await handlePull("perms", { app: appIdOrName }); | ||
warnDeprecation('pull-perms', 'pull perms'); | ||
await handlePull('perms', { app: appIdOrName }); | ||
}); | ||
program | ||
.command("pull") | ||
.command('pull') | ||
.argument( | ||
"[schema|perms|all]", | ||
"Which configuration to push. Defaults to `all`", | ||
'[schema|perms|all]', | ||
'Which configuration to push. Defaults to `all`', | ||
) | ||
.option( | ||
"-a --app <app-id>", | ||
"App ID to push to. Defaults to *_INSTANT_APP_ID in .env", | ||
'-a --app <app-id>', | ||
'App ID to push to. Defaults to *_INSTANT_APP_ID in .env', | ||
) | ||
.description("Pull schema and perm files from production.") | ||
.description('Pull schema and perm files from production.') | ||
.action(async function (arg, inputOpts) { | ||
const ret = convertPushPullToCurrentFormat("pull", arg, inputOpts); | ||
const ret = convertPushPullToCurrentFormat('pull', arg, inputOpts); | ||
if (!ret.ok) return; | ||
@@ -448,7 +448,7 @@ const { bag, opts } = ret; | ||
async function push(bag, appId, opts) { | ||
if (bag === "schema" || bag === "all") { | ||
if (bag === 'schema' || bag === 'all') { | ||
const { ok } = await pushSchema(appId, opts); | ||
if (!ok) return; | ||
} | ||
if (bag === "perms" || bag === "all") { | ||
if (bag === 'perms' || bag === 'all') { | ||
await pushPerms(appId); | ||
@@ -461,3 +461,3 @@ } | ||
console.log( | ||
`To use this app automatically from now on, update your ${chalk.green("`.env`")} file:`, | ||
`To use this app automatically from now on, update your ${chalk.green('`.env`')} file:`, | ||
); | ||
@@ -470,5 +470,5 @@ const picked = potentialEnvs[envType]; | ||
otherEnvs.sort(); | ||
const otherEnvStr = otherEnvs.map((x) => " " + chalk.green(x)).join("\n"); | ||
const otherEnvStr = otherEnvs.map((x) => ' ' + chalk.green(x)).join('\n'); | ||
console.log(`Alternative names: \n${otherEnvStr} \n`); | ||
console.log(terminalLink("Dashboard", appDashUrl(appId)) + "\n"); | ||
console.log(terminalLink('Dashboard', appDashUrl(appId)) + '\n'); | ||
} | ||
@@ -481,3 +481,3 @@ | ||
const hasEnvFile = await pathExists(join(pkgDir, ".env")); | ||
const hasEnvFile = await pathExists(join(pkgDir, '.env')); | ||
if (hasEnvFile) { | ||
@@ -488,9 +488,9 @@ printDotEnvInfo(envType, appId); | ||
console.log( | ||
`\nLooks like you don't have a ${chalk.green("`.env`")} file yet.`, | ||
`\nLooks like you don't have a ${chalk.green('`.env`')} file yet.`, | ||
); | ||
console.log( | ||
`If we set ${chalk.green("`" + envName + "`")}, we can remember the app that you chose for all future commands.`, | ||
`If we set ${chalk.green('`' + envName + '`')}, we can remember the app that you chose for all future commands.`, | ||
); | ||
const ok = await promptOk( | ||
"Want us to create this env file for you?", | ||
'Want us to create this env file for you?', | ||
/*defaultAnswer=*/ true, | ||
@@ -500,8 +500,8 @@ ); | ||
console.log( | ||
`No .env file created. You can always set ${chalk.green("`" + envName + "`")} later. \n`, | ||
`No .env file created. You can always set ${chalk.green('`' + envName + '`')} later. \n`, | ||
); | ||
return; | ||
} | ||
await writeFile(join(pkgDir, ".env"), `${envName}=${appId}`, "utf-8"); | ||
console.log(`Created ${chalk.green("`.env`")} file!`); | ||
await writeFile(join(pkgDir, '.env'), `${envName}=${appId}`, 'utf-8'); | ||
console.log(`Created ${chalk.green('`.env`')} file!`); | ||
} | ||
@@ -513,3 +513,3 @@ | ||
const { appId, source } = ret; | ||
if (source === "created" || source === "imported") { | ||
if (source === 'created' || source === 'imported') { | ||
await handleEnvFile(pkgAndAuthInfo, appId); | ||
@@ -532,7 +532,7 @@ } | ||
async function pull(bag, appId, pkgAndAuthInfo) { | ||
if (bag === "schema" || bag === "all") { | ||
if (bag === 'schema' || bag === 'all') { | ||
const { ok } = await pullSchema(appId, pkgAndAuthInfo); | ||
if (!ok) return; | ||
} | ||
if (bag === "perms" || bag === "all") { | ||
if (bag === 'perms' || bag === 'all') { | ||
await pullPerms(appId, pkgAndAuthInfo); | ||
@@ -544,6 +544,6 @@ } | ||
const registerRes = await fetchJson({ | ||
method: "POST", | ||
path: "/dash/cli/auth/register", | ||
debugName: "Login register", | ||
errorMessage: "Failed to register login.", | ||
method: 'POST', | ||
path: '/dash/cli/auth/register', | ||
debugName: 'Login register', | ||
errorMessage: 'Failed to register login.', | ||
noAuth: true, | ||
@@ -565,3 +565,3 @@ }); | ||
console.log("Waiting for authentication..."); | ||
console.log('Waiting for authentication...'); | ||
const authTokenRes = await waitForAuthToken({ secret }); | ||
@@ -575,3 +575,3 @@ if (!authTokenRes) { | ||
if (options.print) { | ||
console.log(chalk.red("[Do not share] Your Instant auth token:", token)); | ||
console.log(chalk.red('[Do not share] Your Instant auth token:', token)); | ||
} else { | ||
@@ -589,3 +589,3 @@ await saveConfigAuthToken(token); | ||
} | ||
console.log("Checking for an Instant SDK..."); | ||
console.log('Checking for an Instant SDK...'); | ||
const instantModuleName = await getInstantModuleName(pkgJson); | ||
@@ -602,8 +602,8 @@ if (instantModuleName) { | ||
const moduleName = await select({ | ||
message: "Which package would you like to use?", | ||
message: 'Which package would you like to use?', | ||
choices: [ | ||
{ name: "@instantdb/react", value: "@instantdb/react" }, | ||
{ name: "@instantdb/react-native", value: "@instantdb/react-native" }, | ||
{ name: "@instantdb/core", value: "@instantdb/core" }, | ||
{ name: "@instantdb/admin", value: "@instantdb/admin" }, | ||
{ name: '@instantdb/react', value: '@instantdb/react' }, | ||
{ name: '@instantdb/react-native', value: '@instantdb/react-native' }, | ||
{ name: '@instantdb/core', value: '@instantdb/core' }, | ||
{ name: '@instantdb/admin', value: '@instantdb/admin' }, | ||
], | ||
@@ -635,4 +635,4 @@ }); | ||
const _title = await input({ | ||
message: "What would you like to call it?", | ||
default: "My cool app", | ||
message: 'What would you like to call it?', | ||
default: 'My cool app', | ||
required: true, | ||
@@ -644,3 +644,3 @@ }).catch(() => null); | ||
if (!title) { | ||
error("No name provided. Exiting."); | ||
error('No name provided. Exiting.'); | ||
return { ok: false }; | ||
@@ -650,6 +650,6 @@ } | ||
const appRes = await fetchJson({ | ||
method: "POST", | ||
path: "/dash/apps", | ||
debugName: "App create", | ||
errorMessage: "Failed to create app.", | ||
method: 'POST', | ||
path: '/dash/apps', | ||
debugName: 'App create', | ||
errorMessage: 'Failed to create app.', | ||
body: app, | ||
@@ -663,3 +663,3 @@ }); | ||
appTitle: title, | ||
source: "created", | ||
source: 'created', | ||
}; | ||
@@ -670,6 +670,6 @@ } | ||
const res = await fetchJson({ | ||
debugName: "Fetching apps", | ||
method: "GET", | ||
path: "/dash", | ||
errorMessage: "Failed to fetch apps.", | ||
debugName: 'Fetching apps', | ||
method: 'GET', | ||
path: '/dash', | ||
errorMessage: 'Failed to fetch apps.', | ||
}); | ||
@@ -692,3 +692,3 @@ if (!res.ok) { | ||
const choice = await select({ | ||
message: "Which app would you like to import?", | ||
message: 'Which app would you like to import?', | ||
choices: res.data.apps.map((app) => { | ||
@@ -699,3 +699,3 @@ return { name: `${app.title} (${app.id})`, value: app.id }; | ||
if (!choice) return { ok: false }; | ||
return { ok: true, appId: choice, source: "imported" }; | ||
return { ok: true, appId: choice, source: 'imported' }; | ||
} | ||
@@ -707,3 +707,3 @@ | ||
if (fromOpts.appId) { | ||
return { ok: true, appId: fromOpts.appId, source: "opts" }; | ||
return { ok: true, appId: fromOpts.appId, source: 'opts' }; | ||
} | ||
@@ -716,14 +716,14 @@ | ||
console.log(`Found ${chalk.green(envName)}: ${value}`); | ||
return { ok: true, appId: value, source: "env" }; | ||
return { ok: true, appId: value, source: 'env' }; | ||
} | ||
const action = await select({ | ||
message: "What would you like to do?", | ||
message: 'What would you like to do?', | ||
choices: [ | ||
{ name: "Create a new app", value: "create" }, | ||
{ name: "Import an existing app", value: "import" }, | ||
{ name: 'Create a new app', value: 'create' }, | ||
{ name: 'Import an existing app', value: 'import' }, | ||
], | ||
}).catch(() => null); | ||
if (action === "create") { | ||
if (action === 'create') { | ||
return await promptCreateApp(); | ||
@@ -739,3 +739,3 @@ } | ||
...prettierConfig, | ||
parser: "typescript", | ||
parser: 'typescript', | ||
}); | ||
@@ -748,6 +748,6 @@ return await writeFile(path, formattedCode, encoding); | ||
const instantModuleName = [ | ||
"@instantdb/react", | ||
"@instantdb/react-native", | ||
"@instantdb/core", | ||
"@instantdb/admin", | ||
'@instantdb/react', | ||
'@instantdb/react-native', | ||
'@instantdb/core', | ||
'@instantdb/admin', | ||
].find((name) => deps[name]); | ||
@@ -758,3 +758,3 @@ return instantModuleName; | ||
async function getPackageJson(pkgDir) { | ||
return await readJsonFile(join(pkgDir, "package.json")); | ||
return await readJsonFile(join(pkgDir, 'package.json')); | ||
} | ||
@@ -789,8 +789,8 @@ | ||
async function pullSchema(appId, { pkgDir, instantModuleName }) { | ||
console.log("Pulling schema..."); | ||
console.log('Pulling schema...'); | ||
const pullRes = await fetchJson({ | ||
path: `/dash/apps/${appId}/schema/pull`, | ||
debugName: "Schema pull", | ||
errorMessage: "Failed to pull schema.", | ||
debugName: 'Schema pull', | ||
errorMessage: 'Failed to pull schema.', | ||
}); | ||
@@ -804,3 +804,3 @@ | ||
) { | ||
console.log("Schema is empty. Skipping."); | ||
console.log('Schema is empty. Skipping.'); | ||
return { ok: true }; | ||
@@ -811,3 +811,3 @@ } | ||
const ok = await promptOk( | ||
"This will overwrite your local instant.schema file, OK to proceed?", | ||
'This will overwrite your local instant.schema file, OK to proceed?', | ||
); | ||
@@ -818,3 +818,3 @@ | ||
const schemaPath = join(pkgDir, "instant.schema.ts"); | ||
const schemaPath = join(pkgDir, 'instant.schema.ts'); | ||
await writeTypescript( | ||
@@ -827,6 +827,6 @@ schemaPath, | ||
), | ||
"utf-8", | ||
'utf-8', | ||
); | ||
console.log("✅ Wrote schema to instant.schema.ts"); | ||
console.log('✅ Wrote schema to instant.schema.ts'); | ||
@@ -837,8 +837,8 @@ return { ok: true }; | ||
async function pullPerms(appId, { pkgDir, instantModuleName }) { | ||
console.log("Pulling perms..."); | ||
console.log('Pulling perms...'); | ||
const pullRes = await fetchJson({ | ||
path: `/dash/apps/${appId}/perms/pull`, | ||
debugName: "Perms pull", | ||
errorMessage: "Failed to pull perms.", | ||
debugName: 'Perms pull', | ||
errorMessage: 'Failed to pull perms.', | ||
}); | ||
@@ -848,5 +848,5 @@ | ||
if (await pathExists(join(pkgDir, "instant.perms.ts"))) { | ||
if (await pathExists(join(pkgDir, 'instant.perms.ts'))) { | ||
const ok = await promptOk( | ||
"This will overwrite your local instant.perms file, OK to proceed?", | ||
'This will overwrite your local instant.perms file, OK to proceed?', | ||
); | ||
@@ -857,10 +857,10 @@ | ||
const permsPath = join(pkgDir, "instant.perms.ts"); | ||
const permsPath = join(pkgDir, 'instant.perms.ts'); | ||
await writeTypescript( | ||
permsPath, | ||
generatePermsTypescriptFile(pullRes.data.perms || {}, instantModuleName), | ||
"utf-8", | ||
'utf-8', | ||
); | ||
console.log("✅ Wrote permissions to instant.perms.ts"); | ||
console.log('✅ Wrote permissions to instant.perms.ts'); | ||
@@ -871,18 +871,18 @@ return true; | ||
function indexingJobCompletedActionMessage(job) { | ||
if (job.job_type === "check-data-type") { | ||
if (job.job_type === 'check-data-type') { | ||
return `setting type of ${job.attr_name} to ${job.checked_data_type}`; | ||
} | ||
if (job.job_type === "remove-data-type") { | ||
if (job.job_type === 'remove-data-type') { | ||
return `removing type from ${job.attr_name}`; | ||
} | ||
if (job.job_type === "index") { | ||
if (job.job_type === 'index') { | ||
return `adding index to ${job.attr_name}`; | ||
} | ||
if (job.job_type === "remove-index") { | ||
if (job.job_type === 'remove-index') { | ||
return `removing index from ${job.attr_name}`; | ||
} | ||
if (job.job_type === "unique") { | ||
if (job.job_type === 'unique') { | ||
return `adding uniqueness constraint to ${job.attr_name}`; | ||
} | ||
if (job.job_type === "remove-unique") { | ||
if (job.job_type === 'remove-unique') { | ||
return `removing uniqueness constraint from ${job.attr_name}`; | ||
@@ -907,11 +907,11 @@ } | ||
const actionMessage = indexingJobCompletedActionMessage(job); | ||
if (job.job_status === "canceled") { | ||
if (job.job_status === 'canceled') { | ||
return `Canceled ${actionMessage} before it could finish.`; | ||
} | ||
if (job.job_status === "completed") { | ||
if (job.job_status === 'completed') { | ||
return `Finished ${actionMessage}.`; | ||
} | ||
if (job.job_status === "errored") { | ||
if (job.job_status === 'errored') { | ||
if (job.invalid_triples_sample?.length) { | ||
const [etype, label] = job.attr_name.split("."); | ||
const [etype, label] = job.attr_name.split('.'); | ||
const samples = formatSamples(job.invalid_triples_sample); | ||
@@ -924,22 +924,22 @@ const longestValue = samples.reduce( | ||
let msg = `${chalk.red("INVALID DATA")} ${actionMessage}.\n`; | ||
let msg = `${chalk.red('INVALID DATA')} ${actionMessage}.\n`; | ||
if (job.invalid_unique_value) { | ||
msg += ` Found multiple entities with value ${truncate(JSON.stringify(job.invalid_unique_value), 64)}.\n`; | ||
} | ||
if (job.error === "triple-too-large-error") { | ||
if (job.error === 'triple-too-large-error') { | ||
msg += ` Some of the existing data is too large to index.\n`; | ||
} | ||
msg += ` First few examples:\n`; | ||
msg += ` ${chalk.bold("id")}${" ".repeat(35)}| ${chalk.bold(label)}${" ".repeat(longestValue - label.length)} | ${chalk.bold("type")}\n`; | ||
msg += ` ${"-".repeat(37)}|${"-".repeat(longestValue + 2)}|--------\n`; | ||
msg += ` ${chalk.bold('id')}${' '.repeat(35)}| ${chalk.bold(label)}${' '.repeat(longestValue - label.length)} | ${chalk.bold('type')}\n`; | ||
msg += ` ${'-'.repeat(37)}|${'-'.repeat(longestValue + 2)}|--------\n`; | ||
for (const triple of samples) { | ||
const urlParams = new URLSearchParams({ | ||
s: "main", | ||
s: 'main', | ||
app: job.app_id, | ||
t: "explorer", | ||
t: 'explorer', | ||
ns: etype, | ||
where: JSON.stringify(["id", triple.entity_id]), | ||
where: JSON.stringify(['id', triple.entity_id]), | ||
}); | ||
const url = new URL(instantDashOrigin); | ||
url.pathname = "/dash"; | ||
url.pathname = '/dash'; | ||
url.search = urlParams.toString(); | ||
@@ -950,3 +950,3 @@ | ||
}); | ||
msg += ` ${link} | ${triple.value}${" ".repeat(longestValue - triple.value.length)} | ${triple.json_type}\n`; | ||
msg += ` ${link} | ${triple.value}${' '.repeat(longestValue - triple.value.length)} | ${triple.json_type}\n`; | ||
} | ||
@@ -961,3 +961,3 @@ return msg; | ||
if (items.length === 0) { | ||
return ""; | ||
return ''; | ||
} | ||
@@ -970,3 +970,3 @@ if (items.length === 1) { | ||
} | ||
return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`; | ||
return `${items.slice(0, -1).join(', ')}, and ${items[items.length - 1]}`; | ||
} | ||
@@ -977,8 +977,8 @@ | ||
const jobActions = { | ||
"check-data-type": "updating types", | ||
"remove-data-type": "updating types", | ||
index: "updating indexes", | ||
"remove-index": "updating indexes", | ||
unique: "updating uniqueness constraints", | ||
"remove-unique": "updating uniqueness constraints", | ||
'check-data-type': 'updating types', | ||
'remove-data-type': 'updating types', | ||
index: 'updating indexes', | ||
'remove-index': 'updating indexes', | ||
unique: 'updating uniqueness constraints', | ||
'remove-unique': 'updating uniqueness constraints', | ||
}; | ||
@@ -988,3 +988,3 @@ for (const job of jobs) { | ||
} | ||
return joinInSentence([...actions].sort()) || "updating schema"; | ||
return joinInSentence([...actions].sort()) || 'updating schema'; | ||
} | ||
@@ -994,5 +994,5 @@ | ||
const spinner = ora({ | ||
text: "checking data types", | ||
text: 'checking data types', | ||
}).start(); | ||
const groupId = data["group-id"]; | ||
const groupId = data['group-id']; | ||
let jobs = data.jobs; | ||
@@ -1019,3 +1019,3 @@ let waitMs = 20; | ||
} | ||
if (job.job_status === "waiting" || job.job_status === "processing") { | ||
if (job.job_status === 'waiting' || job.job_status === 'processing') { | ||
stillRunning = true; | ||
@@ -1029,3 +1029,3 @@ // Default estimate to high value to prevent % from jumping around | ||
const msg = indexingJobCompletedMessage(job); | ||
if (job.job_status === "errored") { | ||
if (job.job_status === 'errored') { | ||
errorMessages.push(msg); | ||
@@ -1048,3 +1048,3 @@ } else { | ||
if (completedMessages.length) { | ||
spinner.prefixText = completedMessages.join("\n") + "\n"; | ||
spinner.prefixText = completedMessages.join('\n') + '\n'; | ||
} | ||
@@ -1054,6 +1054,6 @@ waitMs = updated ? 1 : Math.min(10000, waitMs * 2); | ||
const res = await fetchJson({ | ||
debugName: "Check indexing status", | ||
method: "GET", | ||
debugName: 'Check indexing status', | ||
method: 'GET', | ||
path: `/dash/apps/${appId}/indexing-jobs/group/${groupId}`, | ||
errorMessage: "Failed to check indexing status.", | ||
errorMessage: 'Failed to check indexing status.', | ||
}); | ||
@@ -1066,4 +1066,4 @@ if (!res.ok) { | ||
spinner.stopAndPersist({ | ||
text: "", | ||
prefixText: completedMessages.join("\n"), | ||
text: '', | ||
prefixText: completedMessages.join('\n'), | ||
}); | ||
@@ -1076,3 +1076,3 @@ | ||
} | ||
console.log(chalk.red("Some steps failed while updating schema.")); | ||
console.log(chalk.red('Some steps failed while updating schema.')); | ||
process.exit(1); | ||
@@ -1086,9 +1086,9 @@ } | ||
console.log("Planning schema..."); | ||
console.log('Planning schema...'); | ||
const planRes = await fetchJson({ | ||
method: "POST", | ||
method: 'POST', | ||
path: `/dash/apps/${appId}/schema/push/plan`, | ||
debugName: "Schema plan", | ||
errorMessage: "Failed to update schema.", | ||
debugName: 'Schema plan', | ||
errorMessage: 'Failed to update schema.', | ||
body: { | ||
@@ -1104,3 +1104,3 @@ schema, | ||
if (!planRes.data.steps.length) { | ||
console.log("No schema changes detected. Skipping."); | ||
console.log('No schema changes detected. Skipping.'); | ||
return { ok: true }; | ||
@@ -1110,3 +1110,3 @@ } | ||
console.log( | ||
"The following changes will be applied to your production schema:", | ||
'The following changes will be applied to your production schema:', | ||
); | ||
@@ -1116,9 +1116,9 @@ | ||
switch (action) { | ||
case "add-attr": | ||
case "update-attr": { | ||
const valueType = attr["value-type"]; | ||
const isAdd = action === "add-attr"; | ||
if (valueType === "blob" && attrFwdLabel(attr) === "id") { | ||
case 'add-attr': | ||
case 'update-attr': { | ||
const valueType = attr['value-type']; | ||
const isAdd = action === 'add-attr'; | ||
if (valueType === 'blob' && attrFwdLabel(attr) === 'id') { | ||
console.log( | ||
`${isAdd ? chalk.magenta("ADD ENTITY") : chalk.magenta("UPDATE ENTITY")} ${attrFwdName(attr)}`, | ||
`${isAdd ? chalk.magenta('ADD ENTITY') : chalk.magenta('UPDATE ENTITY')} ${attrFwdName(attr)}`, | ||
); | ||
@@ -1128,5 +1128,5 @@ break; | ||
if (valueType === "blob") { | ||
if (valueType === 'blob') { | ||
console.log( | ||
`${isAdd ? chalk.green("ADD ATTR") : chalk.blue("UPDATE ATTR")} ${attrFwdName(attr)} :: unique=${attr["unique?"]}, indexed=${attr["index?"]}`, | ||
`${isAdd ? chalk.green('ADD ATTR') : chalk.blue('UPDATE ATTR')} ${attrFwdName(attr)} :: unique=${attr['unique?']}, indexed=${attr['index?']}`, | ||
); | ||
@@ -1137,28 +1137,28 @@ break; | ||
console.log( | ||
`${isAdd ? chalk.green("ADD LINK") : chalk.blue("UPDATE LINK")} ${attrFwdName(attr)} <=> ${attrRevName(attr)}`, | ||
`${isAdd ? chalk.green('ADD LINK') : chalk.blue('UPDATE LINK')} ${attrFwdName(attr)} <=> ${attrRevName(attr)}`, | ||
); | ||
break; | ||
} | ||
case "check-data-type": { | ||
case 'check-data-type': { | ||
console.log( | ||
`${chalk.green("CHECK TYPE")} ${attrFwdName(attr)} => ${attr["checked-data-type"]}`, | ||
`${chalk.green('CHECK TYPE')} ${attrFwdName(attr)} => ${attr['checked-data-type']}`, | ||
); | ||
break; | ||
} | ||
case "remove-data-type": { | ||
console.log(`${chalk.red("REMOVE TYPE")} ${attrFwdName(attr)} => any`); | ||
case 'remove-data-type': { | ||
console.log(`${chalk.red('REMOVE TYPE')} ${attrFwdName(attr)} => any`); | ||
break; | ||
} | ||
case "index": { | ||
console.log("%s on %s", chalk.green("ADD INDEX"), attrFwdName(attr)); | ||
case 'index': { | ||
console.log('%s on %s', chalk.green('ADD INDEX'), attrFwdName(attr)); | ||
break; | ||
} | ||
case "remove-index": { | ||
console.log("%s on %s", chalk.red("REMOVE INDEX"), attrFwdName(attr)); | ||
case 'remove-index': { | ||
console.log('%s on %s', chalk.red('REMOVE INDEX'), attrFwdName(attr)); | ||
break; | ||
} | ||
case "unique": { | ||
case 'unique': { | ||
console.log( | ||
"%s to %s", | ||
chalk.green("ADD UNIQUE CONSTRAINT"), | ||
'%s to %s', | ||
chalk.green('ADD UNIQUE CONSTRAINT'), | ||
attrFwdName(attr), | ||
@@ -1168,6 +1168,6 @@ ); | ||
} | ||
case "remove-unique": { | ||
case 'remove-unique': { | ||
console.log( | ||
"%s from %s", | ||
chalk.red("REMOVE UNIQUE CONSTRAINT"), | ||
'%s from %s', | ||
chalk.red('REMOVE UNIQUE CONSTRAINT'), | ||
attrFwdName(attr), | ||
@@ -1180,10 +1180,10 @@ ); | ||
const okPush = await promptOk("OK to proceed?"); | ||
const okPush = await promptOk('OK to proceed?'); | ||
if (!okPush) return { ok: true }; | ||
const applyRes = await fetchJson({ | ||
method: "POST", | ||
method: 'POST', | ||
path: `/dash/apps/${appId}/schema/push/apply`, | ||
debugName: "Schema apply", | ||
errorMessage: "Failed to update schema.", | ||
debugName: 'Schema apply', | ||
errorMessage: 'Failed to update schema.', | ||
body: { | ||
@@ -1198,7 +1198,7 @@ schema, | ||
if (applyRes.data["indexing-jobs"]) { | ||
await waitForIndexingJobsToFinish(appId, applyRes.data["indexing-jobs"]); | ||
if (applyRes.data['indexing-jobs']) { | ||
await waitForIndexingJobsToFinish(appId, applyRes.data['indexing-jobs']); | ||
} | ||
console.log(chalk.green("Schema updated!")); | ||
console.log(chalk.green('Schema updated!')); | ||
@@ -1214,8 +1214,8 @@ return { ok: true }; | ||
console.log("Planning perms..."); | ||
console.log('Planning perms...'); | ||
const prodPerms = await fetchJson({ | ||
path: `/dash/apps/${appId}/perms/pull`, | ||
debugName: "Perms pull", | ||
errorMessage: "Failed to pull perms.", | ||
debugName: 'Perms pull', | ||
errorMessage: 'Failed to pull perms.', | ||
}); | ||
@@ -1230,17 +1230,17 @@ | ||
if (!diffedStr.length) { | ||
console.log("No perms changes detected. Exiting."); | ||
console.log('No perms changes detected. Exiting.'); | ||
return; | ||
} | ||
console.log("The following changes will be applied to your perms:"); | ||
console.log('The following changes will be applied to your perms:'); | ||
console.log(diffedStr); | ||
const okPush = await promptOk("OK to proceed?"); | ||
const okPush = await promptOk('OK to proceed?'); | ||
if (!okPush) return; | ||
const permsRes = await fetchJson({ | ||
method: "POST", | ||
method: 'POST', | ||
path: `/dash/apps/${appId}/rules`, | ||
debugName: "Schema apply", | ||
errorMessage: "Failed to update schema.", | ||
debugName: 'Schema apply', | ||
errorMessage: 'Failed to update schema.', | ||
body: { | ||
@@ -1253,3 +1253,3 @@ code: perms, | ||
console.log(chalk.green("Permissions updated!")); | ||
console.log(chalk.green('Permissions updated!')); | ||
@@ -1263,6 +1263,6 @@ return true; | ||
const authCheckRes = await fetchJson({ | ||
method: "POST", | ||
debugName: "Auth check", | ||
errorMessage: "Failed to check auth status.", | ||
path: "/dash/cli/auth/check", | ||
method: 'POST', | ||
debugName: 'Auth check', | ||
errorMessage: 'Failed to check auth status.', | ||
path: '/dash/cli/auth/check', | ||
body: { secret }, | ||
@@ -1275,10 +1275,10 @@ noAuth: true, | ||
} | ||
if (authCheckRes.data?.hint.errors?.[0]?.issue === "waiting-for-user") { | ||
if (authCheckRes.data?.hint.errors?.[0]?.issue === 'waiting-for-user') { | ||
continue; | ||
} | ||
error("Failed to authenticate "); | ||
error('Failed to authenticate '); | ||
prettyPrintJSONErr(authCheckRes.data); | ||
return; | ||
} | ||
error("Timed out waiting for authentication"); | ||
error('Timed out waiting for authentication'); | ||
return null; | ||
@@ -1324,7 +1324,7 @@ } | ||
const res = await fetch(`${instantBackendOrigin}${path}`, { | ||
method: method ?? "GET", | ||
method: method ?? 'GET', | ||
headers: { | ||
...(withAuth ? { Authorization: `Bearer ${authToken}` } : {}), | ||
"Content-Type": "application/json", | ||
"Instant-CLI-Version": version, | ||
'Content-Type': 'application/json', | ||
'Instant-CLI-Version': version, | ||
}, | ||
@@ -1336,3 +1336,3 @@ body: body ? JSON.stringify(body) : undefined, | ||
if (verbose) { | ||
console.log(debugName, "response:", res.status, res.statusText); | ||
console.log(debugName, 'response:', res.status, res.statusText); | ||
} | ||
@@ -1347,3 +1347,3 @@ | ||
if (verbose && data) { | ||
console.log(debugName, "json:", JSON.stringify(data, null, 2)); | ||
console.log(debugName, 'json:', JSON.stringify(data, null, 2)); | ||
} | ||
@@ -1361,3 +1361,3 @@ if (!res.ok) { | ||
if (withErrorLogging) { | ||
if (err.name === "AbortError") { | ||
if (err.name === 'AbortError') { | ||
error( | ||
@@ -1380,7 +1380,7 @@ `Timeout: It took more than ${timeoutMs / 60000} minutes to get the result.`, | ||
for (const err of data.hint.errors) { | ||
error(`${err.in ? err.in.join("->") + ": " : ""}${err.message}`); | ||
error(`${err.in ? err.in.join('->') + ': ' : ''}${err.message}`); | ||
} | ||
} | ||
if (!data) { | ||
error("Failed to parse error response"); | ||
error('Failed to parse error response'); | ||
} | ||
@@ -1429,4 +1429,4 @@ } | ||
{ | ||
files: "instant.perms", | ||
extensions: ["ts", "mts", "cts", "js", "mjs", "cjs", "json"], | ||
files: 'instant.perms', | ||
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json'], | ||
transform: transformImports, | ||
@@ -1450,3 +1450,3 @@ }, | ||
error( | ||
`We couldn't find your ${chalk.yellow("`instant.perms.ts`")} file. Make sure it's in the root directory.`, | ||
`We couldn't find your ${chalk.yellow('`instant.perms.ts`')} file. Make sure it's in the root directory.`, | ||
); | ||
@@ -1463,4 +1463,4 @@ } | ||
{ | ||
files: "instant.schema", | ||
extensions: ["ts", "mts", "cts", "js", "mjs", "cjs"], | ||
files: 'instant.schema', | ||
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs'], | ||
transform: transformImports, | ||
@@ -1482,4 +1482,4 @@ }, | ||
{ | ||
files: "instant.config", | ||
extensions: ["ts", "mts", "cts", "js", "mjs", "cjs", "json"], | ||
files: 'instant.config', | ||
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json'], | ||
}, | ||
@@ -1499,3 +1499,3 @@ ], | ||
error( | ||
`We couldn't find your ${chalk.yellow("`instant.schema.ts`")} file. Make sure it's in the root directory.`, | ||
`We couldn't find your ${chalk.yellow('`instant.schema.ts`')} file. Make sure it's in the root directory.`, | ||
); | ||
@@ -1520,3 +1520,3 @@ return; | ||
getAuthPaths().authConfigFilePath, | ||
"utf-8", | ||
'utf-8', | ||
).catch(() => null); | ||
@@ -1531,3 +1531,3 @@ | ||
error( | ||
`Looks like you are not logged in. Please log in with ${chalk.green("`instant-cli login`")}`, | ||
`Looks like you are not logged in. Please log in with ${chalk.green('`instant-cli login`')}`, | ||
); | ||
@@ -1553,9 +1553,9 @@ } | ||
return writeFile(authPaths.authConfigFilePath, authToken, "utf-8"); | ||
return writeFile(authPaths.authConfigFilePath, authToken, 'utf-8'); | ||
} | ||
function getAuthPaths() { | ||
const key = `instantdb-${dev ? "dev" : "prod"}`; | ||
const key = `instantdb-${dev ? 'dev' : 'prod'}`; | ||
const { config: appConfigDirPath } = envPaths(key); | ||
const authConfigFilePath = join(appConfigDirPath, "a"); | ||
const authConfigFilePath = join(appConfigDirPath, 'a'); | ||
@@ -1586,15 +1586,15 @@ return { authConfigFilePath, appConfigDirPath }; | ||
function attrFwdLabel(attr) { | ||
return attr["forward-identity"]?.[2]; | ||
return attr['forward-identity']?.[2]; | ||
} | ||
function attrFwdEtype(attr) { | ||
return attr["forward-identity"]?.[1]; | ||
return attr['forward-identity']?.[1]; | ||
} | ||
function attrRevLabel(attr) { | ||
return attr["reverse-identity"]?.[2]; | ||
return attr['reverse-identity']?.[2]; | ||
} | ||
function attrRevEtype(attr) { | ||
return attr["reverse-identity"]?.[1]; | ||
return attr['reverse-identity']?.[1]; | ||
} | ||
@@ -1607,3 +1607,3 @@ | ||
function attrRevName(attr) { | ||
if (attr["reverse-identity"]) { | ||
if (attr['reverse-identity']) { | ||
return `${attrRevEtype(attr)}.${attrRevLabel(attr)}`; | ||
@@ -1616,6 +1616,6 @@ } | ||
export const rels = { | ||
"many-false": ["many", "many"], | ||
"one-true": ["one", "one"], | ||
"many-true": ["many", "one"], | ||
"one-false": ["one", "many"], | ||
'many-false': ['many', 'many'], | ||
'one-true': ['one', 'one'], | ||
'many-true': ['many', 'one'], | ||
'one-false': ['one', 'many'], | ||
}; | ||
@@ -1658,3 +1658,3 @@ | ||
error( | ||
`Found ${chalk.green("`" + found.envName + "`")} but it's not a valid UUID.`, | ||
`Found ${chalk.green('`' + found.envName + '`')} but it's not a valid UUID.`, | ||
); | ||
@@ -1697,3 +1697,3 @@ return { ok: false, found }; | ||
import type { InstantRules } from "${instantModuleName ?? "@instantdb/core"}"; | ||
import type { InstantRules } from "${instantModuleName ?? '@instantdb/core'}"; | ||
@@ -1707,3 +1707,3 @@ const rules = ${rulesTxt} satisfies InstantRules; | ||
function inferredType(config) { | ||
const inferredList = config["inferred-types"]; | ||
const inferredList = config['inferred-types']; | ||
const hasJustOne = inferredList?.length === 1; | ||
@@ -1715,10 +1715,10 @@ if (!hasJustOne) return null; | ||
function deriveClientType(attr) { | ||
if (attr["checked-data-type"]) { | ||
return { type: attr["checked-data-type"], origin: "checked" }; | ||
if (attr['checked-data-type']) { | ||
return { type: attr['checked-data-type'], origin: 'checked' }; | ||
} | ||
const inferred = inferredType(attr); | ||
if (inferred) { | ||
return { type: inferred, origin: "inferred" }; | ||
return { type: inferred, origin: 'inferred' }; | ||
} | ||
return { type: "any", origin: "unknown" }; | ||
return { type: 'any', origin: 'unknown' }; | ||
} | ||
@@ -1737,3 +1737,3 @@ | ||
sortedEntries(attrs) | ||
.filter(([name]) => name !== "id") | ||
.filter(([name]) => name !== 'id') | ||
.map(([name, config]) => { | ||
@@ -1747,8 +1747,8 @@ const { type } = deriveClientType(config); | ||
`i.${type}()`, | ||
config["unique?"] ? ".unique()" : "", | ||
config["index?"] ? ".indexed()" : "", | ||
config['unique?'] ? '.unique()' : '', | ||
config['index?'] ? '.indexed()' : '', | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
}) | ||
.join("\n"), | ||
.join('\n'), | ||
`\n`, | ||
@@ -1758,3 +1758,3 @@ ` `, | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
} | ||
@@ -1785,3 +1785,3 @@ | ||
.map(([name, attr]) => { | ||
const type = attr["valueType"] || "any"; | ||
const type = attr['valueType'] || 'any'; | ||
@@ -1793,8 +1793,8 @@ return [ | ||
`i.${type}()`, | ||
attr?.config["unique"] ? ".unique()" : "", | ||
attr?.config["indexed"] ? ".indexed()" : "", | ||
attr?.config['unique'] ? '.unique()' : '', | ||
attr?.config['indexed'] ? '.indexed()' : '', | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
}) | ||
.join("\n"), | ||
.join('\n'), | ||
`\n`, | ||
@@ -1804,9 +1804,9 @@ ` `, | ||
`,`, | ||
].join(""); | ||
].join(''); | ||
} | ||
function roomDefToCodeStr(room) { | ||
let ret = "{"; | ||
let ret = '{'; | ||
if (room.presence) { | ||
ret += `${entityDefToCodeStr("presence", room.presence)}`; | ||
ret += `${entityDefToCodeStr('presence', room.presence)}`; | ||
} | ||
@@ -1820,3 +1820,3 @@ if (room.topics) { | ||
} | ||
ret += "}"; | ||
ret += '}'; | ||
return ret; | ||
@@ -1826,7 +1826,7 @@ } | ||
function roomsCodeStr(rooms) { | ||
let ret = "{"; | ||
let ret = '{'; | ||
for (const [roomType, roomDef] of Object.entries(rooms)) { | ||
ret += `"${roomType}": ${roomDefToCodeStr(roomDef)},`; | ||
} | ||
ret += "}"; | ||
ret += '}'; | ||
return ret; | ||
@@ -1836,3 +1836,3 @@ } | ||
function easyPlural(strn, n) { | ||
return n === 1 ? strn : strn + "s"; | ||
return n === 1 ? strn : strn + 's'; | ||
} | ||
@@ -1848,3 +1848,3 @@ | ||
.map(([name, attrs]) => schemaBlobToCodeStr(name, attrs)) | ||
.join("\n"); | ||
.join('\n'); | ||
const inferredAttrs = Object.values(newSchema.blobs) | ||
@@ -1854,4 +1854,4 @@ .flatMap(Object.values) | ||
(attr) => | ||
attrFwdLabel(attr) !== "id" && | ||
deriveClientType(attr).origin === "inferred", | ||
attrFwdLabel(attr) !== 'id' && | ||
deriveClientType(attr).origin === 'inferred', | ||
); | ||
@@ -1861,6 +1861,6 @@ | ||
const etypes = Object.keys(newSchema.blobs); | ||
const hasOnlyUserTable = etypes.length === 1 && etypes[0] === "$users"; | ||
const hasOnlyUserTable = etypes.length === 1 && etypes[0] === '$users'; | ||
const entitiesComment = | ||
inferredAttrs.length > 0 | ||
? `// We inferred ${inferredAttrs.length} ${easyPlural("attribute", inferredAttrs.length)}! | ||
? `// We inferred ${inferredAttrs.length} ${easyPlural('attribute', inferredAttrs.length)}! | ||
// Take a look at this schema, and if everything looks good, | ||
@@ -1874,3 +1874,3 @@ // run \`push schema\` again to enforce the types.` | ||
`.trim() | ||
: ""; | ||
: ''; | ||
@@ -1880,5 +1880,5 @@ // links | ||
sortedEntries(newSchema.refs).map(([_name, config]) => { | ||
const [, fe, flabel] = config["forward-identity"]; | ||
const [, re, rlabel] = config["reverse-identity"]; | ||
const [fhas, rhas] = rels[`${config.cardinality}-${config["unique?"]}`]; | ||
const [, fe, flabel] = config['forward-identity']; | ||
const [, re, rlabel] = config['reverse-identity']; | ||
const [fhas, rhas] = rels[`${config.cardinality}-${config['unique?']}`]; | ||
return [ | ||
@@ -1901,3 +1901,3 @@ `${fe}${capitalizeFirstLetter(flabel)}`, | ||
); | ||
const linksEntriesCode = JSON.stringify(linksEntries, null, " ").trim(); | ||
const linksEntriesCode = JSON.stringify(linksEntries, null, ' ').trim(); | ||
const hasNoLinks = Object.keys(linksEntries).length === 0; | ||
@@ -1911,3 +1911,3 @@ const linksComment = hasNoLinks | ||
`.trim() | ||
: ""; | ||
: ''; | ||
@@ -1923,3 +1923,3 @@ // rooms | ||
`.trim() | ||
: ""; | ||
: ''; | ||
@@ -1936,8 +1936,8 @@ const kv = (k, v, comment) => { | ||
return ` | ||
import { i } from "${instantModuleName ?? "@instantdb/core"}"; | ||
import { i } from "${instantModuleName ?? '@instantdb/core'}"; | ||
const _schema = i.schema({ | ||
${kv("entities", entitiesObjCode, entitiesComment)}, | ||
${kv("links", linksEntriesCode, linksComment)}, | ||
${kv("rooms", roomsCode, roomsComment)} | ||
${kv('entities', entitiesObjCode, entitiesComment)}, | ||
${kv('links', linksEntriesCode, linksComment)}, | ||
${kv('rooms', roomsCode, roomsComment)} | ||
}); | ||
@@ -1944,0 +1944,0 @@ |
// From: | ||
// https://github.com/skarahoda/inquirer-toggle | ||
import type { Theme } from "@inquirer/core"; | ||
import type { Prompt } from "@inquirer/type"; | ||
import type { Theme } from '@inquirer/core'; | ||
import type { Prompt } from '@inquirer/type'; | ||
@@ -12,5 +12,5 @@ import { | ||
isEnterKey, | ||
} from "@inquirer/core"; | ||
import { createPrompt, usePrefix, makeTheme } from "@inquirer/core"; | ||
import ansiEscapes from "ansi-escapes"; | ||
} from '@inquirer/core'; | ||
import { createPrompt, usePrefix, makeTheme } from '@inquirer/core'; | ||
import ansiEscapes from 'ansi-escapes'; | ||
@@ -23,7 +23,7 @@ type InquirerToggleConfig = { | ||
inactive?: string; | ||
prefix?: Theme["prefix"]; | ||
prefix?: Theme['prefix']; | ||
style?: { | ||
message?: Theme["style"]["message"]; | ||
answer?: Theme["style"]["answer"]; | ||
highlight?: Theme["style"]["highlight"]; | ||
message?: Theme['style']['message']; | ||
answer?: Theme['style']['answer']; | ||
highlight?: Theme['style']['highlight']; | ||
}; | ||
@@ -34,7 +34,7 @@ }; | ||
function isLeftKey(key) { | ||
return key.name === "left"; | ||
return key.name === 'left'; | ||
} | ||
function isRightKey(key) { | ||
return key.name === "right"; | ||
return key.name === 'right'; | ||
} | ||
@@ -46,3 +46,3 @@ | ||
>((config, done) => { | ||
const theme = makeTheme({ active: "yes", inactive: "no" }, config.theme); | ||
const theme = makeTheme({ active: 'yes', inactive: 'no' }, config.theme); | ||
const prefix = usePrefix({ theme }); | ||
@@ -49,0 +49,0 @@ const [value, setValue] = useState(config.default ?? false); |
@@ -1,3 +0,3 @@ | ||
import { PathLike } from "fs"; | ||
import { readFile, stat } from "fs/promises"; | ||
import { PathLike } from 'fs'; | ||
import { readFile, stat } from 'fs/promises'; | ||
@@ -21,3 +21,3 @@ export async function pathExists(p: PathLike): Promise<boolean> { | ||
try { | ||
const data = await readFile(p, "utf-8"); | ||
const data = await readFile(p, 'utf-8'); | ||
return JSON.parse(data); | ||
@@ -24,0 +24,0 @@ } catch (error) {} |
@@ -5,11 +5,11 @@ // Note: | ||
import { pathExists, readJsonFile } from "./fs.js"; | ||
import path from "path"; | ||
import { pathExists, readJsonFile } from './fs.js'; | ||
import path from 'path'; | ||
async function detectPackageManager(destPath) { | ||
const lockfileNames = { | ||
"yarn.lock": "yarn", | ||
"package-lock.json": "npm", | ||
"pnpm-lock.yaml": "pnpm", | ||
"bun.lockb": "bun", | ||
'yarn.lock': 'yarn', | ||
'package-lock.json': 'npm', | ||
'pnpm-lock.yaml': 'pnpm', | ||
'bun.lockb': 'bun', | ||
}; | ||
@@ -25,3 +25,3 @@ | ||
const packageJsonPath = path.join(dir, "package.json"); | ||
const packageJsonPath = path.join(dir, 'package.json'); | ||
if (await pathExists(packageJsonPath)) { | ||
@@ -44,3 +44,3 @@ const packageJson = await readJsonFile(packageJsonPath); | ||
return "npm"; | ||
return 'npm'; | ||
} | ||
@@ -62,3 +62,3 @@ | ||
if (!packageManager) return null; | ||
const atIndex = packageManager.lastIndexOf("@"); | ||
const atIndex = packageManager.lastIndexOf('@'); | ||
if (atIndex <= 0) return null; // '@' at position 0 is invalid | ||
@@ -74,3 +74,3 @@ const packageName = packageManager.slice(0, atIndex); | ||
function getInstallCommand(packageManager, moduleName) { | ||
if (packageManager === "npm") { | ||
if (packageManager === 'npm') { | ||
return `npm install ${moduleName}`; | ||
@@ -77,0 +77,0 @@ } else { |
// Autogenerated by publish_packages.clj | ||
const version = "v0.17.12"; | ||
const version = 'v0.17.13'; | ||
export default version; |
@@ -7,5 +7,5 @@ { | ||
"outDir": "dist", | ||
"rootDir": "src", | ||
"rootDir": "src", | ||
"skipLibCheck": true // `unconfig` currently imports a broken type from `@antfu/utils` | ||
// remove once fixed | ||
// remove once fixed | ||
}, | ||
@@ -12,0 +12,0 @@ "include": ["src"], |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
Found 1 instance in 1 package
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
Found 1 instance in 1 package
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
236997
-0.41%