@gadgetinc/ggt 0.1.16 → 0.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/lib/commands/help.d.ts +2 -2
- package/lib/commands/help.js +2 -1
- package/lib/commands/help.js.map +1 -1
- package/lib/commands/list.d.ts +1 -0
- package/lib/commands/list.js +15 -6
- package/lib/commands/list.js.map +1 -1
- package/lib/commands/sync.d.ts +88 -6
- package/lib/commands/sync.js +196 -122
- package/lib/commands/sync.js.map +1 -1
- package/lib/utils/base-command.d.ts +16 -10
- package/lib/utils/base-command.js +27 -14
- package/lib/utils/base-command.js.map +1 -1
- package/lib/utils/client.d.ts +6 -0
- package/lib/utils/client.js +6 -0
- package/lib/utils/client.js.map +1 -1
- package/lib/utils/context.d.ts +3 -2
- package/lib/utils/context.js +3 -2
- package/lib/utils/context.js.map +1 -1
- package/lib/utils/fs-utils.d.ts +2 -2
- package/lib/utils/fs-utils.js +3 -3
- package/lib/utils/fs-utils.js.map +1 -1
- package/lib/utils/promise.d.ts +35 -0
- package/lib/utils/promise.js +114 -0
- package/lib/utils/promise.js.map +1 -0
- package/npm-shrinkwrap.json +17320 -11197
- package/oclif.manifest.json +1 -1
- package/package.json +23 -23
package/lib/commands/sync.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.js","sourceRoot":"/","sources":["commands/sync.ts"],"names":[],"mappings":";;;;AAAA,sCAA0C;AAC1C,0DAA0B;AAC1B,4DAA4B;AAC5B,uCAAqC;AACrC,qEAAqC;AACrC,0DAA0B;AAE1B,gEAA0B;AAC1B,uCAAkC;AAElC,mCAAgC;AAChC,mCAAkC;AAClC,mCAAkC;AAClC,4EAA2C;AAC3C,0DAAyB;AACzB,8DAA6B;AAC7B,wDAAwB;AACxB,kEAAkC;AAClC,kEAA+B;AAC/B,0DAA0B;AAC1B,wDAAoD;AAEpD,4CAAyC;AACzC,8CAA2C;AAC3C,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oDAA0C,CAAA;AAC5C,CAAC,EAJW,MAAM,GAAN,cAAM,KAAN,cAAM,QAIjB;AAEY,QAAA,oCAAoC,GAG/B;;;;;;;;;;;;;;;CAejB,CAAC;AAEW,QAAA,0BAA0B,GAAmF;;;;CAIzH,CAAC;AAEW,QAAA,iCAAiC,GAG5B;;;;;;CAMjB,CAAC","sourcesContent":["import { Args, Flags } from \"@oclif/core\";\nimport chalk from \"chalk\";\nimport assert from \"assert\";\nimport { FSWatcher } from \"chokidar\";\nimport format from \"date-fns/format\";\nimport execa from \"execa\";\nimport type { Stats } from \"fs-extra\";\nimport fs from \"fs-extra\";\nimport { prompt } from \"inquirer\";\nimport type { DebouncedFunc } from \"lodash\";\nimport { sortBy } from \"lodash\";\nimport { isString } from \"lodash\";\nimport { debounce } from \"lodash\";\nimport normalizePath from \"normalize-path\";\nimport pMap from \"p-map\";\nimport PQueue from \"p-queue\";\nimport path from \"path\";\nimport pluralize from \"pluralize\";\nimport dedent from \"ts-dedent\";\nimport which from \"which\";\nimport { BaseCommand } from \"../utils/base-command\";\nimport type { Query } from \"../utils/client\";\nimport { Client } from \"../utils/client\";\nimport { context } from \"../utils/context\";\nimport { InvalidSyncAppFlagError, InvalidSyncFileError, YarnNotFoundError } from \"../utils/errors\";\nimport { app } from \"../utils/flags\";\nimport { ignoreEnoent, Ignorer, isEmptyDir, walkDir } from \"../utils/fs-utils\";\nimport type {\n FileSyncChangedEvent,\n FileSyncChangedEventInput,\n FileSyncDeletedEvent,\n FileSyncDeletedEventInput,\n PublishFileSyncEventsMutation,\n PublishFileSyncEventsMutationVariables,\n RemoteFilesVersionQuery,\n RemoteFilesVersionQueryVariables,\n RemoteFileSyncEventsSubscription,\n RemoteFileSyncEventsSubscriptionVariables,\n} from \"../__generated__/graphql\";\nimport { FileSyncEncoding } from \"../__generated__/graphql\";\n\nexport default class Sync extends BaseCommand<typeof Sync> {\n static override priority = 1;\n\n static override summary = \"Sync your Gadget application's source code to and from your local filesystem.\";\n\n static override usage = \"sync [DIRECTORY] [--app <name>]\";\n\n static override description = dedent(chalk`\n Sync provides the ability to sync your Gadget application's source code to and from your local\n filesystem. While {gray ggt sync} is running, local file changes are immediately reflected within\n Gadget, while files that are changed remotely are immediately saved to your local filesystem.\n\n Use cases for this include:\n - Developing locally with your own editor like VSCode {gray (https://code.visualstudio.com/)}\n - Storing your source code in a Git repository like GitHub {gray (https://github.com/)}\n\n Sync includes the concept of a {gray .ignore} file. This file may contain a list of files and\n directories that won't be received or sent to Gadget when syncing. The format of this file is\n identical to the one used by Git {gray (https://git-scm.com/docs/gitignore)}.\n\n The following files and directories are always ignored:\n - .gadget\n - .git\n - node_modules\n\n Note:\n - If you have separate development and production environments, {gray ggt sync} will only sync with your development environment\n - Gadget applications only support installing dependencies with Yarn 1 {gray (https://classic.yarnpkg.com/lang/en/)}\n - Since file changes are immediately reflected in Gadget, avoid the following while {gray ggt sync} is running:\n - Deleting all your files\n - Moving all your files to a different directory\n `);\n\n static override args = {\n directory: Args.string({\n description: \"The directory to sync files to. If the directory doesn't exist, it will be created.\",\n default: \".\",\n }),\n };\n\n static override flags = {\n app: app({\n summary: \"The Gadget application to sync files to.\",\n }),\n force: Flags.boolean({\n summary: \"Whether to sync even if we can't determine the state of your local files relative to your remote ones.\",\n default: false,\n }),\n \"file-push-delay\": Flags.integer({\n summary: \"Delay in milliseconds before pushing files to your app.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 100,\n hidden: true,\n }),\n \"file-stability-threshold\": Flags.integer({\n name: \"file-stability-threshold\",\n summary: \"Time in milliseconds a file's size must remain the same.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 500,\n hidden: true,\n }),\n \"file-poll-interval\": Flags.integer({\n name: \"file-poll-interval\",\n description: \"Interval in milliseconds between polling a file's size.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 100,\n hidden: true,\n }),\n };\n\n static override examples = [\n dedent(chalk`\n {gray $ ggt sync --app my-app ~/gadget/my-app}\n\n App my-app\n Editor https://my-app.gadget.app/edit\n Playground https://my-app.gadget.app/api/graphql/playground\n Docs https://docs.gadget.dev/api/my-app\n\n {underline Endpoints}\n - https://my-app.gadget.app\n - https://my-app--development.gadget.app\n\n Watching for file changes... {gray Press Ctrl+C to stop}\n\n Received {gray 12:00:00 PM}\n {green ←} routes/GET.js {gray (changed)}\n {green ←} user/signUp/signIn.js {gray (changed)}\n {gray 2 files in total. 2 changed, 0 deleted.}\n\n Sent {gray 12:00:03 PM}\n {green →} routes/GET.ts {gray (changed)}\n {gray 1 file in total. 1 changed, 0 deleted.}\n\n ^C Stopping... {gray (press Ctrl+C again to force)}\n Goodbye!\n `),\n ];\n\n override requireUser = true;\n\n status = SyncStatus.STARTING;\n\n dir!: string;\n\n recentWrites = new Set();\n\n queue = new PQueue({ concurrency: 1 });\n\n client!: Client;\n\n ignorer!: Ignorer;\n\n watcher!: FSWatcher;\n\n metadata = {\n app: \"\",\n filesVersion: \"0\",\n mtime: 0,\n };\n\n publish!: DebouncedFunc<() => void>;\n\n stop!: (error?: unknown) => Promise<void>;\n\n finished!: Promise<void>;\n markFinished!: () => void;\n\n relative(to: string): string {\n return path.relative(this.dir, to);\n }\n\n absolute(...pathSegments: string[]): string {\n return path.resolve(this.dir, ...pathSegments);\n }\n\n normalize(filepath: string, isDirectory = false): string {\n return normalizePath(path.isAbsolute(filepath) ? this.relative(filepath) : filepath) + (isDirectory ? \"/\" : \"\");\n }\n\n logPaths(prefix: string, changed: string[], deleted: string[], { limit = 10 } = {}): void {\n const lines = sortBy(\n [\n ...changed.map((filepath) => chalk`{green ${prefix}} ${this.normalize(filepath)} {gray (changed)}`),\n ...deleted.map((filepath) => chalk`{red ${prefix}} ${this.normalize(filepath)} {gray (deleted)}`),\n ],\n (line) => line.slice(line.indexOf(\" \") + 1)\n );\n\n let logged = 0;\n for (const line of lines) {\n this.log(line);\n if (++logged == limit && !this.debugEnabled) break;\n }\n\n if (lines.length > logged) {\n this.log(chalk`{gray … ${lines.length - logged} more}`);\n }\n\n this.log(chalk`{gray ${pluralize(\"file\", lines.length, true)} in total. ${changed.length} changed, ${deleted.length} deleted.}`);\n this.log();\n }\n\n override async init(): Promise<void> {\n await super.init();\n\n assert(isString(this.args[\"directory\"]));\n\n this.dir =\n this.config.windows && this.args[\"directory\"].startsWith(\"~/\")\n ? path.join(this.config.home, this.args[\"directory\"].slice(2))\n : path.resolve(this.args[\"directory\"]);\n\n const getApp = async (): Promise<string> => {\n if (this.flags.app) return this.flags.app;\n if (this.metadata.app) return this.metadata.app;\n const selected = await prompt<{ app: string }>({\n type: \"list\",\n name: \"app\",\n message: \"Please select the app to sync to.\",\n choices: await context.getAvailableApps().then((apps) => apps.map((app) => app.slug)),\n });\n return selected.app;\n };\n\n if (await isEmptyDir(this.dir)) {\n this.metadata.app = await getApp();\n } else {\n try {\n this.metadata = await fs.readJson(this.absolute(\".gadget\", \"sync.json\"));\n if (!this.metadata.app) {\n this.metadata.app = await getApp();\n }\n } catch (error) {\n if (!this.flags.force) {\n throw new InvalidSyncFileError(error, this, this.flags.app);\n }\n this.metadata.app = await getApp();\n }\n }\n\n if (this.flags.app && this.flags.app !== this.metadata.app && !this.flags.force) {\n throw new InvalidSyncAppFlagError(this);\n }\n\n await context.setApp(this.metadata.app);\n\n this.client = new Client();\n\n // local files/folders that should never be published\n this.ignorer = new Ignorer(this.dir, [\"node_modules\", \".gadget\", \".git\"]);\n\n this.watcher = new FSWatcher({\n ignored: (filepath) => this.ignorer.ignores(filepath),\n // don't emit an event for every watched file on boot\n ignoreInitial: true,\n // make sure stats are always present on add/change events\n alwaysStat: true,\n // wait for the entire file to be written before emitting add/change events\n awaitWriteFinish: { pollInterval: this.flags[\"file-poll-interval\"], stabilityThreshold: this.flags[\"file-stability-threshold\"] },\n });\n\n this.debug(\"starting\");\n\n if (!which.sync(\"yarn\", { nothrow: true })) {\n throw new YarnNotFoundError();\n }\n\n await fs.ensureDir(this.dir);\n\n const { remoteFilesVersion } = await this.client.queryUnwrap({ query: REMOTE_FILES_VERSION_QUERY });\n const hasRemoteChanges = BigInt(remoteFilesVersion) > BigInt(this.metadata.filesVersion);\n\n const getChangedFiles = async (): Promise<Map<string, Stats>> => {\n const files = new Map();\n for await (const filepath of walkDir(this.dir, { ignorer: this.ignorer })) {\n const stats = await fs.stat(filepath);\n if (stats.mtime.getTime() > this.metadata.mtime) {\n files.set(this.absolute(filepath), stats);\n }\n }\n\n // don't include the root directory\n files.delete(this.dir);\n\n return files;\n };\n\n const changedFiles = await getChangedFiles();\n const hasLocalChanges = changedFiles.size > 0;\n if (hasLocalChanges) {\n this.log(\"Local files have changed since you last synced\");\n this.logPaths(\"-\", Array.from(changedFiles.keys()), [], { limit: changedFiles.size });\n this.log();\n }\n\n this.debug(\"init %O\", { metadata: this.metadata, remoteFilesVersion, hasRemoteChanges, hasLocalChanges });\n\n let action: Action | undefined;\n if (hasLocalChanges) {\n ({ action } = await prompt({\n type: \"list\",\n name: \"action\",\n choices: [Action.CANCEL, Action.MERGE, Action.RESET],\n message: hasRemoteChanges ? \"Remote files have also changed. How would you like to proceed?\" : \"How would you like to proceed?\",\n }));\n }\n\n switch (action) {\n case Action.MERGE: {\n // get all the changed files again in case more changed\n const files = await getChangedFiles();\n\n // we purposefully don't set the returned remoteFilesVersion here because we haven't processed the in-between versions yet\n await this.client.queryUnwrap({\n query: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: {\n input: {\n expectedRemoteFilesVersion: remoteFilesVersion,\n changed: await pMap(files, async ([filepath, stats]) => {\n if (stats.mtime.getTime() > this.metadata.mtime) {\n this.metadata.mtime = stats.mtime.getTime();\n }\n\n const isDirectory = stats.isDirectory();\n\n return {\n path: this.normalize(filepath, isDirectory),\n mode: stats.mode,\n content: isDirectory ? \"\" : await fs.readFile(filepath, \"base64\"),\n encoding: FileSyncEncoding.Base64,\n };\n }),\n deleted: [],\n },\n },\n });\n break;\n }\n case Action.RESET: {\n await pMap(changedFiles, ([filepath]) => fs.remove(filepath));\n this.metadata.filesVersion = \"0\";\n break;\n }\n case Action.CANCEL: {\n process.exit(0);\n }\n }\n\n this.debug(\"started\");\n }\n\n async run(): Promise<void> {\n let error: unknown;\n this.finished = new Promise((resolve) => {\n this.markFinished = resolve;\n });\n\n this.stop = async (e?: unknown) => {\n if (this.status != SyncStatus.RUNNING) return;\n\n error = e;\n this.debug(\"stopping\");\n this.status = SyncStatus.STOPPING;\n\n try {\n unsubscribe();\n this.watcher.removeAllListeners();\n this.publish.flush();\n await this.queue.onIdle();\n } finally {\n await fs.outputJSON(this.absolute(\".gadget\", \"sync.json\"), this.metadata, { spaces: 2 });\n await Promise.allSettled([this.watcher.close(), this.client.dispose()]);\n\n this.debug(\"stopped\");\n this.status = SyncStatus.STOPPED;\n this.markFinished();\n }\n };\n\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.on(signal, () => {\n if (this.status != SyncStatus.RUNNING) return;\n\n this.log(chalk` Stopping... {gray (press Ctrl+C again to force)}`);\n void this.stop();\n\n // When ggt is run via npx, and the user presses Ctrl+C, npx sends SIGINT twice in quick succession. In order to prevent the second\n // SIGINT from triggering the force exit listener, we wait a bit before registering it. This is a bit of a hack, but it works.\n setTimeout(() => {\n process.once(signal, () => {\n this.log(\" Exiting immediately. Note that files may not have finished syncing.\");\n process.exit(1);\n });\n }, 100).unref();\n });\n }\n\n const unsubscribe = this.client.subscribeUnwrap(\n {\n query: REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n variables: () => ({ localFilesVersion: this.metadata.filesVersion }),\n },\n {\n error: (error) => void this.stop(error),\n next: ({ remoteFileSyncEvents: { remoteFilesVersion, changed, deleted } }) => {\n const remoteFiles = new Map(\n [...deleted, ...changed]\n .filter((event) => event.path.startsWith(\".gadget/\") || !this.ignorer.ignores(event.path))\n .map((e) => [e.path, e])\n );\n\n void this.queue\n .add(async () => {\n if (!remoteFiles.size) {\n if (BigInt(remoteFilesVersion) > BigInt(this.metadata.filesVersion)) {\n // we still need to update filesVersion, otherwise our expectedFilesVersion will be behind the next time we publish\n this.debug(\"updated local files version from %s to %s\", this.metadata.filesVersion, remoteFilesVersion);\n this.metadata.filesVersion = remoteFilesVersion;\n }\n return;\n }\n\n this.log(chalk`Received {gray ${format(new Date(), \"pp\")}}`);\n this.logPaths(\n \"←\",\n changed.map((x) => x.path).filter((x) => remoteFiles.has(x)),\n deleted.map((x) => x.path).filter((x) => remoteFiles.has(x))\n );\n\n const handleFiles = async (files: (FileSyncChangedEvent | FileSyncDeletedEvent)[]) =>\n await pMap(\n files,\n async (file) => {\n if (!remoteFiles.has(file.path)) {\n return;\n }\n\n const filepath = this.absolute(file.path);\n this.recentWrites.add(filepath);\n\n if (\"content\" in file) {\n if (!file.path.endsWith(\"/\")) {\n this.recentWrites.add(path.dirname(filepath));\n await fs.ensureDir(path.dirname(filepath), { mode: 0o755 });\n await fs.writeFile(filepath, Buffer.from(file.content, file.encoding ?? FileSyncEncoding.Utf8), {\n mode: file.mode,\n });\n } else {\n await fs.ensureDir(filepath, { mode: 0o755 });\n }\n if (filepath == this.absolute(\"yarn.lock\")) {\n await execa(\"yarn\", [\"install\"], { cwd: this.dir }).catch((err) => {\n this.debug(\"yarn install failed\");\n this.debug(err.message);\n });\n }\n } else {\n await fs.remove(filepath);\n }\n\n if (filepath == this.ignorer.filepath) {\n this.ignorer.reload();\n }\n },\n { stopOnError: false }\n );\n\n // we need to processed deleted files first as we may delete an empty directory once a file has been put into it. if processed out of order the new file is deleted as well\n await handleFiles(deleted);\n await handleFiles(changed);\n\n this.debug(\"updated local files version from %s to %s\", this.metadata.filesVersion, remoteFilesVersion);\n this.metadata.filesVersion = remoteFilesVersion;\n })\n .catch(this.stop);\n },\n }\n );\n\n const localFilesBuffer = new Map<\n string,\n { mode: number; mtime: number; isDirectory: boolean } | { isDeleted: true; isDirectory: boolean }\n >();\n\n this.publish = debounce(() => {\n const localFiles = new Map(localFilesBuffer.entries());\n localFilesBuffer.clear();\n\n void this.queue\n .add(async () => {\n const changed: FileSyncChangedEventInput[] = [];\n const deleted: FileSyncDeletedEventInput[] = [];\n\n await pMap(\n localFiles,\n async ([filepath, file]) => {\n if (\"isDeleted\" in file) {\n deleted.push({ path: this.normalize(filepath, file.isDirectory) });\n } else {\n try {\n changed.push({\n path: this.normalize(filepath, file.isDirectory),\n mode: file.mode,\n content: file.isDirectory ? \"\" : await fs.readFile(filepath, \"base64\"),\n encoding: FileSyncEncoding.Base64,\n });\n } catch (error) {\n // A file could have been changed and then deleted before we process the change event, so the readFile above will raise\n // an ENOENT. This is normal operation, so just ignore this event.\n ignoreEnoent(error);\n }\n }\n },\n { stopOnError: false }\n );\n\n if (changed.length > 0 || deleted.length > 0) {\n const data = await this.client.queryUnwrap({\n query: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: { input: { expectedRemoteFilesVersion: this.metadata.filesVersion, changed, deleted } },\n });\n\n this.log(chalk`Sent {gray ${format(new Date(), \"pp\")}}`);\n this.logPaths(\n \"→\",\n changed.map((x) => x.path),\n deleted.map((x) => x.path)\n );\n\n const { remoteFilesVersion } = data.publishFileSyncEvents;\n this.debug(\"remote files version after publishing %s\", remoteFilesVersion);\n\n if (BigInt(remoteFilesVersion) > BigInt(this.metadata.filesVersion)) {\n this.debug(\"updated local files version from %s to %s\", this.metadata.filesVersion, remoteFilesVersion);\n this.metadata.filesVersion = remoteFilesVersion;\n }\n }\n })\n .catch(this.stop);\n }, this.flags[\"file-push-delay\"]);\n\n this.watcher\n .add(`${this.dir}/**/*`)\n .on(\"error\", (error) => void this.stop(error))\n .on(\"all\", (event, filepath, stats) => {\n const relativePath = this.relative(filepath);\n\n if (stats?.isSymbolicLink?.()) {\n this.debug(\"skipping event caused by symlink %s\", relativePath);\n return;\n }\n\n if (filepath == this.ignorer.filepath) {\n this.ignorer.reload();\n } else if (this.ignorer.ignores(filepath)) {\n this.debug(\"skipping event caused by ignored file %s\", relativePath);\n return;\n }\n\n // we only update the mtime if the file is not ignored, because if we restart and the mtime is set to an ignored file, then it could\n // be greater than the mtime of all non ignored files and we'll think that local files have changed when only an ignored one has\n if (stats && stats.mtime.getTime() > this.metadata.mtime) {\n this.metadata.mtime = stats.mtime.getTime();\n }\n\n if (this.recentWrites.delete(filepath)) {\n this.debug(\"skipping event caused by recent write %s\", relativePath);\n return;\n }\n\n this.debug(\"file changed %s\", relativePath, event);\n\n switch (event) {\n case \"add\":\n case \"change\":\n assert(stats, \"missing stats on add/change event\");\n localFilesBuffer.set(filepath, { mode: stats.mode, mtime: stats.mtime.getTime(), isDirectory: false });\n break;\n case \"addDir\":\n assert(stats, \"missing stats on addDir event\");\n localFilesBuffer.set(filepath, { mode: stats.mode, mtime: stats.mtime.getTime(), isDirectory: true });\n break;\n case \"unlinkDir\":\n case \"unlink\":\n localFilesBuffer.set(filepath, { isDeleted: true, isDirectory: event === \"unlinkDir\" });\n break;\n }\n\n this.publish();\n });\n\n this.status = SyncStatus.RUNNING;\n\n // app should be defined at this point\n assert(context.app);\n\n this.log();\n this.log(\n dedent(chalk`\n {bold ggt v${this.config.version}}\n\n App ${context.app.slug}\n Editor https://${context.app.slug}.gadget.app/edit\n Playground https://${context.app.slug}.gadget.app/api/graphql/playground\n Docs https://docs.gadget.dev/api/${context.app.slug}\n\n {underline Endpoints} ${\n context.app.hasSplitEnvironments\n ? `\n - https://${context.app.primaryDomain}\n - https://${context.app.slug}--development.gadget.app`\n : `\n - https://${context.app.primaryDomain}`\n }\n\n Watching for file changes... {gray Press Ctrl+C to stop}\n `)\n );\n this.log();\n\n await this.finished;\n\n if (error) {\n this.notify({ subtitle: \"Uh oh!\", message: \"An error occurred while syncing files\" });\n throw error;\n } else {\n this.log(\"Goodbye!\");\n }\n }\n}\n\nexport enum SyncStatus {\n STARTING,\n RUNNING,\n STOPPING,\n STOPPED,\n}\n\nexport enum Action {\n CANCEL = \"Cancel (Ctrl+C)\",\n MERGE = \"Merge local files with remote ones\",\n RESET = \"Reset local files to remote ones\",\n}\n\nexport const REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION: Query<\n RemoteFileSyncEventsSubscription,\n RemoteFileSyncEventsSubscriptionVariables\n> = /* GraphQL */ `\n subscription RemoteFileSyncEvents($localFilesVersion: String!) {\n remoteFileSyncEvents(localFilesVersion: $localFilesVersion, encoding: base64) {\n remoteFilesVersion\n changed {\n path\n mode\n content\n encoding\n }\n deleted {\n path\n }\n }\n }\n`;\n\nexport const REMOTE_FILES_VERSION_QUERY: Query<RemoteFilesVersionQuery, RemoteFilesVersionQueryVariables> = /* GraphQL */ `\n query RemoteFilesVersion {\n remoteFilesVersion\n }\n`;\n\nexport const PUBLISH_FILE_SYNC_EVENTS_MUTATION: Query<\n PublishFileSyncEventsMutation,\n PublishFileSyncEventsMutationVariables\n> = /* GraphQL */ `\n mutation PublishFileSyncEvents($input: PublishFileSyncEventsInput!) {\n publishFileSyncEvents(input: $input) {\n remoteFilesVersion\n }\n }\n`;\n"]}
|
|
1
|
+
{"version":3,"file":"sync.js","sourceRoot":"/","sources":["commands/sync.ts"],"names":[],"mappings":";;;;AAAA,sCAA0C;AAC1C,0DAA0B;AAC1B,4DAA4B;AAC5B,uCAAqC;AACrC,qEAAqC;AACrC,0DAA0B;AAE1B,gEAA0B;AAC1B,uCAAkC;AAElC,mCAAgC;AAChC,mCAAkC;AAClC,4EAA2C;AAC3C,0DAAyB;AACzB,8DAA6B;AAC7B,wDAAwB;AACxB,kEAAkC;AAClC,kEAA+B;AAC/B,0DAA0B;AAC1B,wDAAoD;AAEpD,4CAAyC;AACzC,8CAA2C;AAC3C,4CAAmG;AACnG,0CAAqC;AACrC,gDAAiF;AAWjF,sDAA4D;AAC5D,8CAAiD;AAEjD,MAAqB,IAAK,SAAQ,0BAAwB;IAA1D;;QAsGW;;;;mBAAc,IAAI;WAAC;QAE5B;;WAEG;QACH;;;;mBAAS,UAAU,CAAC,QAAQ;WAAC;QAE7B;;WAEG;QACH;;;;;WAAa;QAEb;;;WAGG;QACH;;;;mBAAsB,IAAI,GAAG,EAAU;WAA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AS,EAAE,MAAM;YACjB,SAAS,EAAE,IAAI;YACf,OAAO,EAAE,GAAG;YACZ,MAAM,EAAE,IAAI;SACb,CAAC;QACF,0BAA0B,EAAE,YAAK,CAAC,OAAO,CAAC;YACxC,IAAI,EAAE,0BAA0B;YAChC,OAAO,EAAE,0DAA0D;YACnE,SAAS,EAAE,MAAM;YACjB,SAAS,EAAE,IAAI;YACf,OAAO,EAAE,GAAG;YACZ,MAAM,EAAE,IAAI;SACb,CAAC;QACF,oBAAoB,EAAE,YAAK,CAAC,OAAO,CAAC;YAClC,IAAI,EAAE,oBAAoB;YAC1B,WAAW,EAAE,yDAAyD;YACtE,SAAS,EAAE,MAAM;YACjB,SAAS,EAAE,IAAI;YACf,OAAO,EAAE,GAAG;YACZ,MAAM,EAAE,IAAI;SACb,CAAC;KACH;EA/BoB,CA+BnB;AAEc;;;;WAAW;QACzB,IAAA,mBAAM,EAAC,IAAA,eAAK,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;KAyBX,CAAC;KACH;EA3BuB,CA2BtB;kBApGiB,IAAI;AAkqBzB,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,mDAAQ,CAAA;IACR,iDAAO,CAAA;IACP,mDAAQ,CAAA;IACR,iDAAO,CAAA;AACT,CAAC,EALW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAKrB;AAED,IAAY,MAIX;AAJD,WAAY,MAAM;IAChB,oCAA0B,CAAA;IAC1B,sDAA4C,CAAA;IAC5C,oDAA0C,CAAA;AAC5C,CAAC,EAJW,MAAM,GAAN,cAAM,KAAN,cAAM,QAIjB;AAEY,QAAA,oCAAoC,GAG/B;;;;;;;;;;;;;;;CAejB,CAAC;AAEW,QAAA,0BAA0B,GAAmF;;;;CAIzH,CAAC;AAEW,QAAA,iCAAiC,GAG5B;;;;;;CAMjB,CAAC","sourcesContent":["import { Args, Flags } from \"@oclif/core\";\nimport chalk from \"chalk\";\nimport assert from \"assert\";\nimport { FSWatcher } from \"chokidar\";\nimport format from \"date-fns/format\";\nimport execa from \"execa\";\nimport type { Stats } from \"fs-extra\";\nimport fs from \"fs-extra\";\nimport { prompt } from \"inquirer\";\nimport type { DebouncedFunc } from \"lodash\";\nimport { sortBy } from \"lodash\";\nimport { debounce } from \"lodash\";\nimport normalizePath from \"normalize-path\";\nimport pMap from \"p-map\";\nimport PQueue from \"p-queue\";\nimport path from \"path\";\nimport pluralize from \"pluralize\";\nimport dedent from \"ts-dedent\";\nimport which from \"which\";\nimport { BaseCommand } from \"../utils/base-command\";\nimport type { Query } from \"../utils/client\";\nimport { Client } from \"../utils/client\";\nimport { context } from \"../utils/context\";\nimport { InvalidSyncAppFlagError, InvalidSyncFileError, YarnNotFoundError } from \"../utils/errors\";\nimport { app } from \"../utils/flags\";\nimport { ignoreEnoent, FSIgnorer, isEmptyDir, walkDir } from \"../utils/fs-utils\";\nimport type {\n FileSyncChangedEventInput,\n FileSyncDeletedEventInput,\n PublishFileSyncEventsMutation,\n PublishFileSyncEventsMutationVariables,\n RemoteFilesVersionQuery,\n RemoteFilesVersionQueryVariables,\n RemoteFileSyncEventsSubscription,\n RemoteFileSyncEventsSubscriptionVariables,\n} from \"../__generated__/graphql\";\nimport { FileSyncEncoding } from \"../__generated__/graphql\";\nimport { PromiseSignal } from \"../utils/promise\";\n\nexport default class Sync extends BaseCommand<typeof Sync> {\n static override priority = 1;\n\n static override summary = \"Sync your Gadget application's source code to and from your local filesystem.\";\n\n static override usage = \"sync [DIRECTORY] [--app <name>]\";\n\n static override description = dedent(chalk`\n Sync provides the ability to sync your Gadget application's source code to and from your local\n filesystem. While {gray ggt sync} is running, local file changes are immediately reflected within\n Gadget, while files that are changed remotely are immediately saved to your local filesystem.\n\n Use cases for this include:\n - Developing locally with your own editor like VSCode {gray (https://code.visualstudio.com/)}\n - Storing your source code in a Git repository like GitHub {gray (https://github.com/)}\n\n Sync includes the concept of a {gray .ignore} file. This file may contain a list of files and\n directories that won't be received or sent to Gadget when syncing. The format of this file is\n identical to the one used by Git {gray (https://git-scm.com/docs/gitignore)}.\n\n The following files and directories are always ignored:\n - .gadget\n - .git\n - node_modules\n\n Note:\n - If you have separate development and production environments, {gray ggt sync} will only sync with your development environment\n - Gadget applications only support installing dependencies with Yarn 1 {gray (https://classic.yarnpkg.com/lang/en/)}\n - Since file changes are immediately reflected in Gadget, avoid the following while {gray ggt sync} is running:\n - Deleting all your files\n - Moving all your files to a different directory\n `);\n\n static override args = {\n directory: Args.string({\n description: \"The directory to sync files to. If the directory doesn't exist, it will be created.\",\n default: \".\",\n }),\n };\n\n static override flags = {\n app: app({\n summary: \"The Gadget application to sync files to.\",\n }),\n force: Flags.boolean({\n summary: \"Whether to sync even if we can't determine the state of your local files relative to your remote ones.\",\n default: false,\n }),\n \"file-push-delay\": Flags.integer({\n summary: \"Delay in milliseconds before pushing files to your app.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 100,\n hidden: true,\n }),\n \"file-stability-threshold\": Flags.integer({\n name: \"file-stability-threshold\",\n summary: \"Time in milliseconds a file's size must remain the same.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 500,\n hidden: true,\n }),\n \"file-poll-interval\": Flags.integer({\n name: \"file-poll-interval\",\n description: \"Interval in milliseconds between polling a file's size.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 100,\n hidden: true,\n }),\n };\n\n static override examples = [\n dedent(chalk`\n {gray $ ggt sync --app my-app ~/gadget/my-app}\n\n App my-app\n Editor https://my-app.gadget.app/edit\n Playground https://my-app.gadget.app/api/graphql/playground\n Docs https://docs.gadget.dev/api/my-app\n\n {underline Endpoints}\n - https://my-app.gadget.app\n - https://my-app--development.gadget.app\n\n Watching for file changes... {gray Press Ctrl+C to stop}\n\n Received {gray 12:00:00 PM}\n {green ←} routes/GET.js {gray (changed)}\n {green ←} user/signUp/signIn.js {gray (changed)}\n {gray 2 files in total. 2 changed, 0 deleted.}\n\n Sent {gray 12:00:03 PM}\n {green →} routes/GET.ts {gray (changed)}\n {gray 1 file in total. 1 changed, 0 deleted.}\n\n ^C Stopping... {gray (press Ctrl+C again to force)}\n Goodbye!\n `),\n ];\n\n override requireUser = true;\n\n /**\n * The current status of the sync process.\n */\n status = SyncStatus.STARTING;\n\n /**\n * The absolute path to the directory to sync files to.\n */\n dir!: string;\n\n /**\n * A list of filepaths that have changed because of a remote file-sync event. This is used to avoid sending files that\n * we recently received from a remote file-sync event.\n */\n recentRemoteChanges = new Set<string>();\n\n /**\n * A FIFO async callback queue that ensures we process file-sync events in the order they occurred.\n */\n queue = new PQueue({ concurrency: 1 });\n\n /**\n * A GraphQL client connected to the app's /edit/api/graphql-ws endpoint\n */\n client!: Client;\n\n /**\n * Loads the .ignore file and provides methods for checking if a file should be ignored.\n */\n ignorer!: FSIgnorer;\n\n /**\n * Watches the local filesystem for changes.\n */\n watcher!: FSWatcher;\n\n /**\n * Holds information about the state of the local filesystem. It's persisted to `.gadget/sync.json`.\n */\n metadata = {\n /**\n * The app this filesystem is synced to.\n */\n app: \"\",\n\n /**\n * The last filesVersion that was successfully written to the filesystem. This is used to determine if the remote\n * filesystem is ahead of the local one.\n */\n filesVersion: \"0\",\n\n /**\n * The largest mtime that was seen on the local filesystem before `ggt sync` stopped. This is used to determine if\n * the local filesystem has changed since the last sync.\n *\n * Note: This does not include the mtime of files that are ignored.\n */\n mtime: 0,\n };\n\n /**\n * A debounced function that enqueue's local file changes to be sent to Gadget.\n */\n publish!: DebouncedFunc<() => void>;\n\n /**\n * Gracefully stops the sync.\n */\n stop!: (error?: unknown) => Promise<void>;\n\n /**\n * Turns an absolute filepath into a relative one from {@linkcode dir}.\n */\n relative(to: string): string {\n return path.relative(this.dir, to);\n }\n\n /**\n * Combines path segments into an absolute filepath that starts at {@linkcode dir}.\n */\n absolute(...pathSegments: string[]): string {\n return path.resolve(this.dir, ...pathSegments);\n }\n\n /**\n * Similar to {@linkcode relative} in that it turns a filepath into a relative one from {@linkcode dir}. However, it\n * also changes any slashes to be posix/unix-like forward slashes, condenses repeated slashes into a single slash, and\n * adds a trailing slash if the filepath is a directory.\n *\n * This is used when sending file-sync events to Gadget to ensure that the paths are consistent across platforms.\n *\n * @see https://www.npmjs.com/package/normalize-path\n */\n normalize(filepath: string, isDirectory: boolean): string {\n return normalizePath(path.isAbsolute(filepath) ? this.relative(filepath) : filepath) + (isDirectory ? \"/\" : \"\");\n }\n\n /**\n * Pretty-prints changed and deleted filepaths to the console.\n *\n * @param prefix The prefix to print before each line.\n * @param changed The normalized paths that have changed.\n * @param deleted The normalized paths that have been deleted.\n * @param options.limit The maximum number of lines to print. Defaults to 10. If debug is enabled, this is ignored.\n */\n logPaths(prefix: string, changed: string[], deleted: string[], { limit = 10 } = {}): void {\n const lines = sortBy(\n [\n ...changed.map((normalizedPath) => chalk`{green ${prefix}} ${normalizedPath} {gray (changed)}`),\n ...deleted.map((normalizedPath) => chalk`{red ${prefix}} ${normalizedPath} {gray (deleted)}`),\n ],\n (line) => line.slice(line.indexOf(\" \") + 1)\n );\n\n let logged = 0;\n for (const line of lines) {\n this.log(line);\n if (++logged == limit && !this.debugEnabled) break;\n }\n\n if (lines.length > logged) {\n this.log(chalk`{gray … ${lines.length - logged} more}`);\n }\n\n this.log(chalk`{gray ${pluralize(\"file\", lines.length, true)} in total. ${changed.length} changed, ${deleted.length} deleted.}`);\n this.log();\n }\n\n /**\n * Initializes the sync process.\n * - Ensures the directory exists.\n * - Ensures the directory is empty or contains a `.gadget/sync.json` file.\n * - Ensures an app is selected and that it matches the app the directory was previously synced to.\n * - Ensures yarn v1 is installed.\n * - Prompts the user how to resolve conflicts if the local filesystem has changed since the last sync.\n */\n override async init(): Promise<void> {\n await super.init();\n\n this.dir =\n this.config.windows && this.args[\"directory\"].startsWith(\"~/\")\n ? path.join(this.config.home, this.args[\"directory\"].slice(2))\n : path.resolve(this.args[\"directory\"]);\n\n const getApp = async (): Promise<string> => {\n if (this.flags.app) return this.flags.app;\n if (this.metadata.app) return this.metadata.app;\n const selected = await prompt<{ app: string }>({\n type: \"list\",\n name: \"app\",\n message: \"Please select the app to sync to.\",\n choices: await context.getAvailableApps().then((apps) => apps.map((app) => app.slug)),\n });\n return selected.app;\n };\n\n if (await isEmptyDir(this.dir)) {\n this.metadata.app = await getApp();\n } else {\n try {\n this.metadata = await fs.readJson(this.absolute(\".gadget\", \"sync.json\"));\n if (!this.metadata.app) {\n this.metadata.app = await getApp();\n }\n } catch (error) {\n if (!this.flags.force) {\n throw new InvalidSyncFileError(error, this, this.flags.app);\n }\n this.metadata.app = await getApp();\n }\n }\n\n if (this.flags.app && this.flags.app !== this.metadata.app && !this.flags.force) {\n throw new InvalidSyncAppFlagError(this);\n }\n\n await context.setApp(this.metadata.app);\n\n this.client = new Client();\n\n // local files/folders that should never be published\n this.ignorer = new FSIgnorer(this.dir, [\"node_modules\", \".gadget\", \".git\"]);\n\n this.watcher = new FSWatcher({\n ignored: (filepath) => this.ignorer.ignores(filepath),\n // don't emit an event for every watched file on boot\n ignoreInitial: true,\n // make sure stats are always present on add/change events\n alwaysStat: true,\n // wait for the entire file to be written before emitting add/change events\n awaitWriteFinish: { pollInterval: this.flags[\"file-poll-interval\"], stabilityThreshold: this.flags[\"file-stability-threshold\"] },\n });\n\n this.debug(\"starting\");\n\n if (!which.sync(\"yarn\", { nothrow: true })) {\n throw new YarnNotFoundError();\n }\n\n await fs.ensureDir(this.dir);\n\n const { remoteFilesVersion } = await this.client.queryUnwrap({ query: REMOTE_FILES_VERSION_QUERY });\n const hasRemoteChanges = BigInt(remoteFilesVersion) > BigInt(this.metadata.filesVersion);\n\n const getChangedFiles = async (): Promise<Map<string, Stats>> => {\n const files = new Map();\n for await (const absolutePath of walkDir(this.dir, { ignorer: this.ignorer })) {\n const stats = await fs.stat(absolutePath);\n if (stats.mtime.getTime() > this.metadata.mtime) {\n files.set(this.normalize(absolutePath, stats.isDirectory()), stats);\n }\n }\n\n // never include the root directory\n files.delete(\"/\");\n\n return files;\n };\n\n const changedFiles = await getChangedFiles();\n const hasLocalChanges = changedFiles.size > 0;\n if (hasLocalChanges) {\n this.log(\"Local files have changed since you last synced\");\n this.logPaths(\"-\", Array.from(changedFiles.keys()), [], { limit: changedFiles.size });\n this.log();\n }\n\n this.debug(\"init %O\", { metadata: this.metadata, remoteFilesVersion, hasRemoteChanges, hasLocalChanges });\n\n let action: Action | undefined;\n if (hasLocalChanges) {\n ({ action } = await prompt({\n type: \"list\",\n name: \"action\",\n choices: [Action.CANCEL, Action.MERGE, Action.RESET],\n message: hasRemoteChanges ? \"Remote files have also changed. How would you like to proceed?\" : \"How would you like to proceed?\",\n }));\n }\n\n switch (action) {\n case Action.MERGE: {\n // get all the changed files again in case more changed\n const files = await getChangedFiles();\n\n // We purposefully don't set the returned remoteFilesVersion here because we haven't received the remote changes\n // yet. This will cause us to receive the local files that we just published + the remote files that were\n // changed since the last sync.\n await this.client.queryUnwrap({\n query: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: {\n input: {\n expectedRemoteFilesVersion: remoteFilesVersion,\n changed: await pMap(files, async ([normalizedPath, stats]) => {\n if (stats.mtime.getTime() > this.metadata.mtime) {\n this.metadata.mtime = stats.mtime.getTime();\n }\n\n return {\n path: normalizedPath,\n mode: stats.mode,\n content: stats.isDirectory() ? \"\" : await fs.readFile(this.absolute(normalizedPath), \"base64\"),\n encoding: FileSyncEncoding.Base64,\n };\n }),\n deleted: [],\n },\n },\n });\n break;\n }\n case Action.RESET: {\n // delete all the local files that have changed since the last sync and set the files version to 0 so we receive\n // all the remote files again, including any files that we just deleted that still exist\n await pMap(changedFiles.keys(), (normalizedPath) => fs.remove(this.absolute(normalizedPath)));\n this.metadata.filesVersion = \"0\";\n break;\n }\n case Action.CANCEL: {\n process.exit(0);\n }\n }\n\n this.debug(\"started\");\n }\n\n /**\n * Runs the sync process until it is stopped or an error occurs.\n */\n async run(): Promise<void> {\n let error: unknown;\n const stopped = new PromiseSignal();\n\n this.stop = async (e?: unknown) => {\n if (this.status != SyncStatus.RUNNING) return;\n\n error = e;\n this.debug(\"stopping\");\n this.status = SyncStatus.STOPPING;\n\n try {\n unsubscribe();\n this.watcher.removeAllListeners();\n this.publish.flush();\n await this.queue.onIdle();\n } finally {\n await fs.outputJSON(this.absolute(\".gadget\", \"sync.json\"), this.metadata, { spaces: 2 });\n await Promise.allSettled([this.watcher.close(), this.client.dispose()]);\n\n this.debug(\"stopped\");\n this.status = SyncStatus.STOPPED;\n stopped.resolve();\n }\n };\n\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.on(signal, () => {\n if (this.status != SyncStatus.RUNNING) return;\n\n this.log(chalk` Stopping... {gray (press Ctrl+C again to force)}`);\n void this.stop();\n\n // When ggt is run via npx, and the user presses Ctrl+C, npx sends SIGINT twice in quick succession. In order to prevent the second\n // SIGINT from triggering the force exit listener, we wait a bit before registering it. This is a bit of a hack, but it works.\n setTimeout(() => {\n process.once(signal, () => {\n this.log(\" Exiting immediately. Note that files may not have finished syncing.\");\n process.exit(1);\n });\n }, 100).unref();\n });\n }\n\n const unsubscribe = this.client.subscribeUnwrap(\n {\n query: REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n variables: () => ({ localFilesVersion: this.metadata.filesVersion }),\n },\n {\n error: (error) => void this.stop(error),\n next: ({ remoteFileSyncEvents }) => {\n const remoteFilesVersion = remoteFileSyncEvents.remoteFilesVersion;\n\n // we always ignore .gadget/ files so that we don't publish them (they're managed by gadget), but we still want to receive them\n const filter = (event: { path: string }) => event.path.startsWith(\".gadget/\") || !this.ignorer.ignores(event.path);\n const changed = remoteFileSyncEvents.changed.filter(filter);\n const deleted = remoteFileSyncEvents.deleted.filter(filter);\n\n this._enqueue(async () => {\n if (!changed.length && !deleted.length) {\n if (BigInt(remoteFilesVersion) > BigInt(this.metadata.filesVersion)) {\n // we still need to update filesVersion, otherwise our expectedFilesVersion will be behind the next time we publish\n this.debug(\"updated local files version from %s to %s\", this.metadata.filesVersion, remoteFilesVersion);\n this.metadata.filesVersion = remoteFilesVersion;\n }\n return;\n }\n\n this.log(chalk`Received {gray ${format(new Date(), \"pp\")}}`);\n this.logPaths(\n \"←\",\n changed.map((x) => x.path),\n deleted.map((x) => x.path)\n );\n\n // we need to processed deleted files first as we may delete an empty directory after a file has been put\n // into it. if processed out of order the new file is deleted as well\n await pMap(deleted, async (file) => {\n this.recentRemoteChanges.add(file.path);\n await fs.remove(this.absolute(file.path));\n });\n\n await pMap(changed, async (file) => {\n this.recentRemoteChanges.add(file.path);\n\n const absolutePath = this.absolute(file.path);\n if (file.path.endsWith(\"/\")) {\n await fs.ensureDir(absolutePath, { mode: 0o755 });\n return;\n }\n\n // we need to add the parent directory to recentRemoteChanges so that we don't try to publish it\n this.recentRemoteChanges.add(path.dirname(file.path) + \"/\");\n await fs.ensureDir(path.dirname(absolutePath), { mode: 0o755 });\n await fs.writeFile(absolutePath, Buffer.from(file.content, file.encoding), { mode: file.mode });\n\n if (absolutePath == this.absolute(\"yarn.lock\")) {\n await execa(\"yarn\", [\"install\"], { cwd: this.dir }).catch((err) => {\n this.debug(\"yarn install failed\");\n this.debug(err.message);\n });\n }\n\n if (absolutePath == this.ignorer.filepath) {\n this.ignorer.reload();\n }\n });\n\n this.debug(\"updated local files version from %s to %s\", this.metadata.filesVersion, remoteFilesVersion);\n this.metadata.filesVersion = remoteFilesVersion;\n\n // always remove the root directory from recentRemoteChanges\n this.recentRemoteChanges.delete(\"./\");\n\n // remove any files in recentRemoteChanges that are ignored (e.g. .gadget/ files)\n for (const filepath of this.recentRemoteChanges) {\n if (this.ignorer.ignores(filepath)) {\n this.recentRemoteChanges.delete(filepath);\n }\n }\n });\n },\n }\n );\n\n const localFilesBuffer = new Map<string, { mode: number; isDirectory: boolean } | { isDeleted: true; isDirectory: boolean }>();\n\n this.publish = debounce(() => {\n const localFiles = new Map(localFilesBuffer.entries());\n localFilesBuffer.clear();\n\n this._enqueue(async () => {\n const changed: FileSyncChangedEventInput[] = [];\n const deleted: FileSyncDeletedEventInput[] = [];\n\n await pMap(localFiles, async ([normalizedPath, file]) => {\n if (\"isDeleted\" in file) {\n deleted.push({ path: normalizedPath });\n return;\n }\n\n try {\n changed.push({\n path: normalizedPath,\n mode: file.mode,\n content: file.isDirectory ? \"\" : await fs.readFile(this.absolute(normalizedPath), \"base64\"),\n encoding: FileSyncEncoding.Base64,\n });\n } catch (error) {\n // A file could have been changed and then deleted before we process the change event, so the readFile\n // above will raise an ENOENT. This is normal operation, so just ignore this event.\n ignoreEnoent(error);\n }\n });\n\n if (!changed.length && !deleted.length) {\n return;\n }\n\n const data = await this.client.queryUnwrap({\n query: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: { input: { expectedRemoteFilesVersion: this.metadata.filesVersion, changed, deleted } },\n });\n\n this.log(chalk`Sent {gray ${format(new Date(), \"pp\")}}`);\n this.logPaths(\n \"→\",\n changed.map((x) => x.path),\n deleted.map((x) => x.path)\n );\n\n const { remoteFilesVersion } = data.publishFileSyncEvents;\n this.debug(\"remote files version after publishing %s\", remoteFilesVersion);\n\n if (BigInt(remoteFilesVersion) > BigInt(this.metadata.filesVersion)) {\n this.debug(\"updated local files version from %s to %s\", this.metadata.filesVersion, remoteFilesVersion);\n this.metadata.filesVersion = remoteFilesVersion;\n }\n });\n }, this.flags[\"file-push-delay\"]);\n\n this.watcher\n .add(`${this.dir}/**/*`)\n .on(\"error\", (error) => void this.stop(error))\n .on(\"all\", (event, absolutePath, stats) => {\n const normalizedPath = this.normalize(absolutePath, event == \"addDir\" || event == \"unlinkDir\");\n\n if (stats?.isSymbolicLink?.()) {\n this.debug(\"skipping event caused by symlink %s\", normalizedPath);\n return;\n }\n\n if (absolutePath == this.ignorer.filepath) {\n this.ignorer.reload();\n } else if (this.ignorer.ignores(absolutePath)) {\n this.debug(\"skipping event caused by ignored file %s\", normalizedPath);\n return;\n }\n\n // we only update the mtime if the file is not ignored, because if we restart and the mtime is set to an ignored\n // file, then it could be greater than the mtime of all non ignored files and we'll think that local files have\n // changed when only an ignored one has\n if (stats && stats.mtime.getTime() > this.metadata.mtime) {\n this.metadata.mtime = stats.mtime.getTime();\n }\n\n if (this.recentRemoteChanges.delete(normalizedPath)) {\n this.debug(\"skipping event caused by recent write %s\", normalizedPath);\n return;\n }\n\n this.debug(\"file changed %s\", normalizedPath, event);\n\n switch (event) {\n case \"add\":\n case \"change\":\n assert(stats, \"missing stats on add/change event\");\n localFilesBuffer.set(normalizedPath, { mode: stats.mode, isDirectory: false });\n break;\n case \"addDir\":\n assert(stats, \"missing stats on addDir event\");\n localFilesBuffer.set(normalizedPath, { mode: stats.mode, isDirectory: true });\n break;\n case \"unlinkDir\":\n case \"unlink\":\n localFilesBuffer.set(normalizedPath, { isDeleted: true, isDirectory: event === \"unlinkDir\" });\n break;\n }\n\n this.publish();\n });\n\n this.status = SyncStatus.RUNNING;\n\n // app should be defined at this point\n assert(context.app);\n\n this.log();\n this.log(\n dedent(chalk`\n {bold ggt v${this.config.version}}\n\n App ${context.app.slug}\n Editor https://${context.app.slug}.gadget.app/edit\n Playground https://${context.app.slug}.gadget.app/api/graphql/playground\n Docs https://docs.gadget.dev/api/${context.app.slug}\n\n {underline Endpoints} ${\n context.app.hasSplitEnvironments\n ? `\n - https://${context.app.primaryDomain}\n - https://${context.app.slug}--development.gadget.app`\n : `\n - https://${context.app.primaryDomain}`\n }\n\n Watching for file changes... {gray Press Ctrl+C to stop}\n `)\n );\n this.log();\n\n await stopped;\n\n if (error) {\n this.notify({ subtitle: \"Uh oh!\", message: \"An error occurred while syncing files\" });\n throw error;\n } else {\n this.log(\"Goodbye!\");\n }\n }\n\n /**\n * Enqueues a function that handles file-sync events onto the {@linkcode queue}.\n *\n * @param fn The function to enqueue.\n */\n private _enqueue(fn: () => Promise<unknown>): void {\n void this.queue.add(fn).catch(this.stop);\n }\n}\n\nexport enum SyncStatus {\n STARTING,\n RUNNING,\n STOPPING,\n STOPPED,\n}\n\nexport enum Action {\n CANCEL = \"Cancel (Ctrl+C)\",\n MERGE = \"Merge local files with remote ones\",\n RESET = \"Reset local files to remote ones\",\n}\n\nexport const REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION: Query<\n RemoteFileSyncEventsSubscription,\n RemoteFileSyncEventsSubscriptionVariables\n> = /* GraphQL */ `\n subscription RemoteFileSyncEvents($localFilesVersion: String!) {\n remoteFileSyncEvents(localFilesVersion: $localFilesVersion, encoding: base64) {\n remoteFilesVersion\n changed {\n path\n mode\n content\n encoding\n }\n deleted {\n path\n }\n }\n }\n`;\n\nexport const REMOTE_FILES_VERSION_QUERY: Query<RemoteFilesVersionQuery, RemoteFilesVersionQueryVariables> = /* GraphQL */ `\n query RemoteFilesVersion {\n remoteFilesVersion\n }\n`;\n\nexport const PUBLISH_FILE_SYNC_EVENTS_MUTATION: Query<\n PublishFileSyncEventsMutation,\n PublishFileSyncEventsMutationVariables\n> = /* GraphQL */ `\n mutation PublishFileSyncEvents($input: PublishFileSyncEventsInput!) {\n publishFileSyncEvents(input: $input) {\n remoteFilesVersion\n }\n }\n`;\n"]}
|
|
@@ -8,18 +8,28 @@ import type NotifySend from "node-notifier/notifiers/notifysend";
|
|
|
8
8
|
import type WindowsToaster from "node-notifier/notifiers/toaster";
|
|
9
9
|
export type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof BaseCommand)["baseFlags"] & T["flags"]>;
|
|
10
10
|
export type Args<T extends typeof Command> = Interfaces.InferredArgs<T["args"]>;
|
|
11
|
+
/**
|
|
12
|
+
* BaseCommand is the base class for all commands in the Gadget CLI.
|
|
13
|
+
*/
|
|
11
14
|
export declare abstract class BaseCommand<T extends typeof Command> extends Command {
|
|
12
15
|
/**
|
|
13
|
-
* Determines how high the command is listed in the README. The lower the number, the higher the command is listed.
|
|
14
|
-
* sorted alphabetically.
|
|
16
|
+
* Determines how high the command is listed in the README. The lower the number, the higher the command is listed.
|
|
17
|
+
* Equal numbers are sorted alphabetically.
|
|
15
18
|
*/
|
|
16
19
|
static priority: number;
|
|
20
|
+
/**
|
|
21
|
+
* Flags that are available to all commands.
|
|
22
|
+
*
|
|
23
|
+
* Short form should be capitalized.
|
|
24
|
+
*/
|
|
17
25
|
static baseFlags: {
|
|
18
26
|
debug: Interfaces.BooleanFlag<boolean>;
|
|
19
27
|
};
|
|
20
28
|
/**
|
|
21
29
|
* Determines whether the command requires the user to be logged in or not.
|
|
22
|
-
*
|
|
30
|
+
*
|
|
31
|
+
* If true and the user is not logged in, the user will be prompted to login before the underlying command is
|
|
32
|
+
* initialized and run.
|
|
23
33
|
*/
|
|
24
34
|
readonly requireUser: boolean;
|
|
25
35
|
/**
|
|
@@ -47,12 +57,8 @@ export declare abstract class BaseCommand<T extends typeof Command> extends Comm
|
|
|
47
57
|
*/
|
|
48
58
|
login(): Promise<void>;
|
|
49
59
|
/**
|
|
50
|
-
* Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called
|
|
51
|
-
* an error is thrown during the `init` or `run` methods.
|
|
60
|
+
* Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called
|
|
61
|
+
* automatically by oclif when an error is thrown during the `init` or `run` methods.
|
|
52
62
|
*/
|
|
53
|
-
catch(cause: Error
|
|
54
|
-
oclif?: {
|
|
55
|
-
exit: number;
|
|
56
|
-
};
|
|
57
|
-
}): Promise<never>;
|
|
63
|
+
catch(cause: Error): Promise<never>;
|
|
58
64
|
}
|
|
@@ -3,7 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.BaseCommand = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const core_1 = require("@oclif/core");
|
|
6
|
-
const errors_1 = require("@oclif/
|
|
6
|
+
const errors_1 = require("@oclif/errors");
|
|
7
|
+
const errors_2 = require("@oclif/core/lib/errors");
|
|
7
8
|
const chalk_1 = tslib_1.__importDefault(require("chalk"));
|
|
8
9
|
const debug_1 = tslib_1.__importDefault(require("debug"));
|
|
9
10
|
const Sentry = tslib_1.__importStar(require("@sentry/node"));
|
|
@@ -15,13 +16,18 @@ const open_1 = tslib_1.__importDefault(require("open"));
|
|
|
15
16
|
const path_1 = tslib_1.__importDefault(require("path"));
|
|
16
17
|
const ts_dedent_1 = tslib_1.__importDefault(require("ts-dedent"));
|
|
17
18
|
const context_1 = require("./context");
|
|
18
|
-
const
|
|
19
|
+
const errors_3 = require("./errors");
|
|
20
|
+
/**
|
|
21
|
+
* BaseCommand is the base class for all commands in the Gadget CLI.
|
|
22
|
+
*/
|
|
19
23
|
class BaseCommand extends core_1.Command {
|
|
20
24
|
constructor(argv, config) {
|
|
21
25
|
super(argv, config);
|
|
22
26
|
/**
|
|
23
27
|
* Determines whether the command requires the user to be logged in or not.
|
|
24
|
-
*
|
|
28
|
+
*
|
|
29
|
+
* If true and the user is not logged in, the user will be prompted to login before the underlying command is
|
|
30
|
+
* initialized and run.
|
|
25
31
|
*/
|
|
26
32
|
Object.defineProperty(this, "requireUser", {
|
|
27
33
|
enumerable: true,
|
|
@@ -139,6 +145,7 @@ class BaseCommand extends core_1.Command {
|
|
|
139
145
|
else {
|
|
140
146
|
this.log(`Hello, ${user.email}`);
|
|
141
147
|
}
|
|
148
|
+
this.log();
|
|
142
149
|
redirectTo.searchParams.set("success", "true");
|
|
143
150
|
resolve();
|
|
144
151
|
}
|
|
@@ -169,29 +176,30 @@ class BaseCommand extends core_1.Command {
|
|
|
169
176
|
}
|
|
170
177
|
}
|
|
171
178
|
/**
|
|
172
|
-
* Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called
|
|
173
|
-
* an error is thrown during the `init` or `run` methods.
|
|
179
|
+
* Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called
|
|
180
|
+
* automatically by oclif when an error is thrown during the `init` or `run` methods.
|
|
174
181
|
*/
|
|
175
182
|
async catch(cause) {
|
|
176
|
-
if (cause.
|
|
177
|
-
//
|
|
183
|
+
if (cause instanceof errors_1.CLIError || cause instanceof errors_2.CLIError) {
|
|
184
|
+
// CLIErrors are user errors (invalid flag, arg, etc...) and already print nicely formatted error messages
|
|
178
185
|
throw cause;
|
|
179
186
|
}
|
|
180
|
-
const error = cause instanceof
|
|
187
|
+
const error = cause instanceof errors_3.BaseError ? cause : new errors_3.UnexpectedError(cause);
|
|
181
188
|
console.error(error.render());
|
|
182
189
|
await error.capture();
|
|
183
|
-
// The original implementation of `catch` re-throws the error so that it's caught and printed by oclif's `handle`
|
|
184
|
-
// to end up in oclif's `handle` method, but we don't want it to print the error again so we
|
|
185
|
-
// `handle` to not print the error, but still exit with the correct exit
|
|
190
|
+
// The original implementation of `catch` re-throws the error so that it's caught and printed by oclif's `handle`
|
|
191
|
+
// method. We still want to end up in oclif's `handle` method, but we don't want it to print the error again so we
|
|
192
|
+
// throw an ExitError instead. This will cause `handle` to not print the error, but still exit with the correct exit
|
|
193
|
+
// code.
|
|
186
194
|
//
|
|
187
195
|
// catch: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/command.ts#L261
|
|
188
196
|
// handle: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/errors/handle.ts#L15
|
|
189
|
-
throw new errors_1.ExitError(
|
|
197
|
+
throw new errors_1.ExitError(1);
|
|
190
198
|
}
|
|
191
199
|
}
|
|
192
200
|
/**
|
|
193
|
-
* Determines how high the command is listed in the README. The lower the number, the higher the command is listed.
|
|
194
|
-
* sorted alphabetically.
|
|
201
|
+
* Determines how high the command is listed in the README. The lower the number, the higher the command is listed.
|
|
202
|
+
* Equal numbers are sorted alphabetically.
|
|
195
203
|
*/
|
|
196
204
|
Object.defineProperty(BaseCommand, "priority", {
|
|
197
205
|
enumerable: true,
|
|
@@ -199,6 +207,11 @@ Object.defineProperty(BaseCommand, "priority", {
|
|
|
199
207
|
writable: true,
|
|
200
208
|
value: Infinity
|
|
201
209
|
});
|
|
210
|
+
/**
|
|
211
|
+
* Flags that are available to all commands.
|
|
212
|
+
*
|
|
213
|
+
* Short form should be capitalized.
|
|
214
|
+
*/
|
|
202
215
|
Object.defineProperty(BaseCommand, "baseFlags", {
|
|
203
216
|
enumerable: true,
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M,KAAK,CAAC;SACb;QAED,MAAM,KAAK,GAAG,KAAK,YAAY,kBAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,wBAAY,CAAC,KAAK,CAAC,CAAC;QAC3E,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;QAC9B,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QAEtB,uIAAuI;QACvI,wIAAwI;QACxI,8EAA8E;QAC9E,EAAE;QACF,0GAA0G;QAC1G,+GAA+G;QAC/G,MAAM,IAAI,kBAAS,CAAC,OAAO,CAAC,QAAQ,IAAI,KAAK,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC;IAClE,CAAC;;AA3MD;;;GAGG;AACI;;;;WAAW,QAAQ;EAAX,CAAY;AAEX;;;;WAAY;QAC1B,KAAK,EAAE,YAAK,CAAC,OAAO,CAAC;YACnB,IAAI,EAAE,GAAG;YACT,OAAO,EAAE,sCAAsC;YAC/C,SAAS,EAAE,QAAQ;YACnB,OAAO,EAAE,KAAK;SACf,CAAC;KACH;EAPwB,CAOvB;AAdkB,kCAAW","sourcesContent":["import type { Config, Interfaces } from \"@oclif/core\";\nimport { Command, Flags, settings } from \"@oclif/core\";\nimport { ExitError } from \"@oclif/core/lib/errors\";\nimport chalk from \"chalk\";\nimport Debug from \"debug\";\nimport * as Sentry from \"@sentry/node\";\nimport getPort from \"get-port\";\nimport type { Server } from \"http\";\nimport { createServer } from \"http\";\nimport { prompt } from \"inquirer\";\nimport type { Notification } from \"node-notifier\";\nimport { notify } from \"node-notifier\";\nimport type WindowsBalloon from \"node-notifier/notifiers/balloon\";\nimport type Growl from \"node-notifier/notifiers/growl\";\nimport type NotificationCenter from \"node-notifier/notifiers/notificationcenter\";\nimport type NotifySend from \"node-notifier/notifiers/notifysend\";\nimport type WindowsToaster from \"node-notifier/notifiers/toaster\";\nimport open from \"open\";\nimport path from \"path\";\nimport dedent from \"ts-dedent\";\nimport { context } from \"./context\";\nimport { BaseError, UnexpectedError as UnknownError } from \"./errors\";\n\nexport type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof BaseCommand)[\"baseFlags\"] & T[\"flags\"]>;\nexport type Args<T extends typeof Command> = Interfaces.InferredArgs<T[\"args\"]>;\n\nexport abstract class BaseCommand<T extends typeof Command> extends Command {\n /**\n * Determines how high the command is listed in the README. The lower the number, the higher the command is listed. Equal numbers are\n * sorted alphabetically.\n */\n static priority = Infinity;\n\n static override baseFlags = {\n debug: Flags.boolean({\n char: \"D\",\n summary: \"Whether to output debug information.\",\n helpGroup: \"global\",\n default: false,\n }),\n };\n\n /**\n * Determines whether the command requires the user to be logged in or not.\n * If true and the user is not logged in, the user will be prompted to login before the command is run.\n */\n readonly requireUser: boolean = false;\n\n /**\n * The parsed flags for the command.\n */\n flags!: Flags<T>;\n\n /**\n * The parsed arguments for the command.\n */\n args!: Args<T>;\n\n constructor(argv: string[], config: Config) {\n super(argv, config);\n\n // TODO: Remove this once the `@oclif/core` warnIfFlagDeprecated function checks base flags as well.\n // warnIfFlagDeprecated throws a null pointer because it assumes all parsed flags are in the flags object (which is not the case for global flags).\n // https://github.com/oclif/core/blob/11c5752cec838d08bb27cd55f0f1aa2390df3c5e/src/command.ts#L259\n this.ctor.flags = { ...this.ctor.flags, ...BaseCommand.baseFlags };\n }\n\n /**\n * Indicates whether the command is being run with the `-D/--debug` flag.\n */\n get debugEnabled(): boolean {\n return !!settings.debug;\n }\n\n override async init(): Promise<void> {\n context.config = this.config;\n\n if (context.env.productionLike) {\n Sentry.init({\n dsn: \"https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266\",\n release: context.config.version,\n });\n }\n\n await super.init();\n\n if (this.requireUser && !(await context.getUser())) {\n // we purposely log the user in before parsing flags in case one of the flags requires the user to be logged in\n // e.g. the `--app` flag verifies that the user has access to the app they are trying to use\n const { login } = await prompt<{ login: boolean }>({\n type: \"confirm\",\n name: \"login\",\n message: \"You must be logged in to use this command. Would you like to log in?\",\n });\n\n if (!login) {\n return this.exit(0);\n }\n\n await this.login();\n }\n\n const { flags, args } = await this.parse({\n flags: this.ctor.flags,\n baseFlags: (super.ctor as typeof BaseCommand).baseFlags,\n args: this.ctor.args,\n strict: this.ctor.strict,\n });\n\n this.flags = flags as Flags<T>;\n this.args = args as Args<T>;\n\n if (flags.debug) {\n settings.debug = true;\n Debug.enable(`${this.config.bin}:*`);\n }\n }\n\n /**\n * Sends a native OS notification to the user.\n *\n * @see {@link https://www.npmjs.com/package/node-notifier node-notifier}\n */\n notify(\n notification:\n | Notification\n | NotificationCenter.Notification\n | NotifySend.Notification\n | WindowsToaster.Notification\n | WindowsBalloon.Notification\n | Growl.Notification\n ): void {\n notify(\n {\n title: \"Gadget\",\n contentImage: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n icon: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n sound: true,\n timeout: false,\n ...notification,\n },\n (error) => {\n if (error) this.warn(error);\n }\n );\n }\n\n /**\n * Opens the Gadget login page in the user's default browser and waits for the user to login.\n */\n async login(): Promise<void> {\n let server: Server | undefined;\n\n try {\n const port = await getPort();\n const receiveSession = new Promise<void>((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n server = createServer(async (req, res) => {\n const redirectTo = new URL(`https://${context.domains.services}/auth/cli`);\n\n try {\n if (!req.url) throw new Error(\"missing url\");\n const incomingUrl = new URL(req.url, `http://localhost:${port}`);\n\n const value = incomingUrl.searchParams.get(\"session\");\n if (!value) throw new Error(\"missing session\");\n\n context.session = value;\n\n const user = await context.getUser();\n if (!user) throw new Error(\"missing current user\");\n\n if (user.name) {\n this.log(chalk`Hello, ${user.name} {gray (${user.email})}`);\n } else {\n this.log(`Hello, ${user.email}`);\n }\n\n redirectTo.searchParams.set(\"success\", \"true\");\n resolve();\n } catch (error) {\n context.session = undefined;\n redirectTo.searchParams.set(\"success\", \"false\");\n reject(error);\n } finally {\n res.writeHead(303, { Location: redirectTo.toString() });\n res.end();\n }\n });\n\n server.listen(port);\n });\n\n const url = new URL(`https://${context.domains.services}/auth/login`);\n url.searchParams.set(\"returnTo\", `https://${context.domains.services}/auth/cli/callback?port=${port}`);\n await open(url.toString());\n\n this.log(dedent`\n We've opened Gadget's login page using your default browser.\n\n Please log in and then return to this terminal.\\n\n `);\n\n await receiveSession;\n } finally {\n server?.close();\n }\n }\n\n /**\n * Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called automatically by oclif when\n * an error is thrown during the `init` or `run` methods.\n */\n override async catch(cause: Error & { oclif?: { exit: number } }): Promise<never> {\n if (cause.oclif?.exit === 0) {\n // we called `this.exit(0)` so we're not actually exiting with an error\n throw cause;\n }\n\n const error = cause instanceof BaseError ? cause : new UnknownError(cause);\n console.error(error.render());\n await error.capture();\n\n // The original implementation of `catch` re-throws the error so that it's caught and printed by oclif's `handle` method. We still want\n // to end up in oclif's `handle` method, but we don't want it to print the error again so we throw an ExitError instead. This will cause\n // `handle` to not print the error, but still exit with the correct exit code.\n //\n // catch: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/command.ts#L261\n // handle: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/errors/handle.ts#L15\n throw new ExitError(process.exitCode ?? cause.oclif?.exit ?? 1);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base-command.js","sourceRoot":"/","sources":["utils/base-command.ts"],"names":[],"mappings":";;;;AACA,sCAAuD;AACvD,0CAAoD;AACpD,mDAA+D;AAC/D,0DAA0B;AAC1B,0DAA0B;AAC1B,6DAAuC;AACvC,gEAA+B;AAE/B,+BAAoC;AACpC,uCAAkC;AAElC,iDAAuC;AAMvC,wDAAwB;AACxB,wDAAwB;AACxB,kEAA+B;AAC/B,uCAAoC;AACpC,qCAAsD;AAKtD;;GAEG;AACH,MAAsB,WAAsC,SAAQ,cAAO;IAuCzE,YAAY,IAAc,EAAE,M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G;QAC/G,MAAM,IAAI,kBAAS,CAAC,CAAC,CAAC,CAAC;IACzB,CAAC;;AApND;;;GAGG;AACI;;;;WAAW,QAAQ;EAAX,CAAY;AAE3B;;;;GAIG;AACa;;;;WAAY;QAC1B,KAAK,EAAE,YAAK,CAAC,OAAO,CAAC;YACnB,IAAI,EAAE,GAAG;YACT,OAAO,EAAE,sCAAsC;YAC/C,SAAS,EAAE,QAAQ;YACnB,OAAO,EAAE,KAAK;SACf,CAAC;KACH;EAPwB,CAOvB;AAnBkB,kCAAW","sourcesContent":["import type { Config, Interfaces } from \"@oclif/core\";\nimport { Command, Flags, settings } from \"@oclif/core\";\nimport { CLIError, ExitError } from \"@oclif/errors\";\nimport { CLIError as CLIError2 } from \"@oclif/core/lib/errors\";\nimport chalk from \"chalk\";\nimport Debug from \"debug\";\nimport * as Sentry from \"@sentry/node\";\nimport getPort from \"get-port\";\nimport type { Server } from \"http\";\nimport { createServer } from \"http\";\nimport { prompt } from \"inquirer\";\nimport type { Notification } from \"node-notifier\";\nimport { notify } from \"node-notifier\";\nimport type WindowsBalloon from \"node-notifier/notifiers/balloon\";\nimport type Growl from \"node-notifier/notifiers/growl\";\nimport type NotificationCenter from \"node-notifier/notifiers/notificationcenter\";\nimport type NotifySend from \"node-notifier/notifiers/notifysend\";\nimport type WindowsToaster from \"node-notifier/notifiers/toaster\";\nimport open from \"open\";\nimport path from \"path\";\nimport dedent from \"ts-dedent\";\nimport { context } from \"./context\";\nimport { BaseError, UnexpectedError } from \"./errors\";\n\nexport type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof BaseCommand)[\"baseFlags\"] & T[\"flags\"]>;\nexport type Args<T extends typeof Command> = Interfaces.InferredArgs<T[\"args\"]>;\n\n/**\n * BaseCommand is the base class for all commands in the Gadget CLI.\n */\nexport abstract class BaseCommand<T extends typeof Command> extends Command {\n /**\n * Determines how high the command is listed in the README. The lower the number, the higher the command is listed.\n * Equal numbers are sorted alphabetically.\n */\n static priority = Infinity;\n\n /**\n * Flags that are available to all commands.\n *\n * Short form should be capitalized.\n */\n static override baseFlags = {\n debug: Flags.boolean({\n char: \"D\",\n summary: \"Whether to output debug information.\",\n helpGroup: \"global\",\n default: false,\n }),\n };\n\n /**\n * Determines whether the command requires the user to be logged in or not.\n *\n * If true and the user is not logged in, the user will be prompted to login before the underlying command is\n * initialized and run.\n */\n readonly requireUser: boolean = false;\n\n /**\n * The parsed flags for the command.\n */\n flags!: Flags<T>;\n\n /**\n * The parsed arguments for the command.\n */\n args!: Args<T>;\n\n constructor(argv: string[], config: Config) {\n super(argv, config);\n\n // TODO: Remove this once the `@oclif/core` warnIfFlagDeprecated function checks base flags as well.\n // warnIfFlagDeprecated throws a null pointer because it assumes all parsed flags are in the flags object (which is not the case for global flags).\n // https://github.com/oclif/core/blob/11c5752cec838d08bb27cd55f0f1aa2390df3c5e/src/command.ts#L259\n this.ctor.flags = { ...this.ctor.flags, ...BaseCommand.baseFlags };\n }\n\n /**\n * Indicates whether the command is being run with the `-D/--debug` flag.\n */\n get debugEnabled(): boolean {\n return !!settings.debug;\n }\n\n override async init(): Promise<void> {\n context.config = this.config;\n\n if (context.env.productionLike) {\n Sentry.init({\n dsn: \"https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266\",\n release: context.config.version,\n });\n }\n\n await super.init();\n\n if (this.requireUser && !(await context.getUser())) {\n // we purposely log the user in before parsing flags in case one of the flags requires the user to be logged in\n // e.g. the `--app` flag verifies that the user has access to the app they are trying to use\n const { login } = await prompt<{ login: boolean }>({\n type: \"confirm\",\n name: \"login\",\n message: \"You must be logged in to use this command. Would you like to log in?\",\n });\n\n if (!login) {\n return this.exit(0);\n }\n\n await this.login();\n }\n\n const { flags, args } = await this.parse({\n flags: this.ctor.flags,\n baseFlags: (super.ctor as typeof BaseCommand).baseFlags,\n args: this.ctor.args,\n strict: this.ctor.strict,\n });\n\n this.flags = flags as Flags<T>;\n this.args = args as Args<T>;\n\n if (flags.debug) {\n settings.debug = true;\n Debug.enable(`${this.config.bin}:*`);\n }\n }\n\n /**\n * Sends a native OS notification to the user.\n *\n * @see {@link https://www.npmjs.com/package/node-notifier node-notifier}\n */\n notify(\n notification:\n | Notification\n | NotificationCenter.Notification\n | NotifySend.Notification\n | WindowsToaster.Notification\n | WindowsBalloon.Notification\n | Growl.Notification\n ): void {\n notify(\n {\n title: \"Gadget\",\n contentImage: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n icon: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n sound: true,\n timeout: false,\n ...notification,\n },\n (error) => {\n if (error) this.warn(error);\n }\n );\n }\n\n /**\n * Opens the Gadget login page in the user's default browser and waits for the user to login.\n */\n async login(): Promise<void> {\n let server: Server | undefined;\n\n try {\n const port = await getPort();\n const receiveSession = new Promise<void>((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n server = createServer(async (req, res) => {\n const redirectTo = new URL(`https://${context.domains.services}/auth/cli`);\n\n try {\n if (!req.url) throw new Error(\"missing url\");\n const incomingUrl = new URL(req.url, `http://localhost:${port}`);\n\n const value = incomingUrl.searchParams.get(\"session\");\n if (!value) throw new Error(\"missing session\");\n\n context.session = value;\n\n const user = await context.getUser();\n if (!user) throw new Error(\"missing current user\");\n\n if (user.name) {\n this.log(chalk`Hello, ${user.name} {gray (${user.email})}`);\n } else {\n this.log(`Hello, ${user.email}`);\n }\n this.log();\n\n redirectTo.searchParams.set(\"success\", \"true\");\n resolve();\n } catch (error) {\n context.session = undefined;\n redirectTo.searchParams.set(\"success\", \"false\");\n reject(error);\n } finally {\n res.writeHead(303, { Location: redirectTo.toString() });\n res.end();\n }\n });\n\n server.listen(port);\n });\n\n const url = new URL(`https://${context.domains.services}/auth/login`);\n url.searchParams.set(\"returnTo\", `https://${context.domains.services}/auth/cli/callback?port=${port}`);\n await open(url.toString());\n\n this.log(dedent`\n We've opened Gadget's login page using your default browser.\n\n Please log in and then return to this terminal.\\n\n `);\n\n await receiveSession;\n } finally {\n server?.close();\n }\n }\n\n /**\n * Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called\n * automatically by oclif when an error is thrown during the `init` or `run` methods.\n */\n override async catch(cause: Error): Promise<never> {\n if (cause instanceof CLIError || cause instanceof CLIError2) {\n // CLIErrors are user errors (invalid flag, arg, etc...) and already print nicely formatted error messages\n throw cause;\n }\n\n const error = cause instanceof BaseError ? cause : new UnexpectedError(cause);\n console.error(error.render());\n await error.capture();\n\n // The original implementation of `catch` re-throws the error so that it's caught and printed by oclif's `handle`\n // method. We still want to end up in oclif's `handle` method, but we don't want it to print the error again so we\n // throw an ExitError instead. This will cause `handle` to not print the error, but still exit with the correct exit\n // code.\n //\n // catch: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/command.ts#L261\n // handle: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/errors/handle.ts#L15\n throw new ExitError(1);\n }\n}\n"]}
|
package/lib/utils/client.d.ts
CHANGED
|
@@ -6,6 +6,12 @@ declare enum ConnectionStatus {
|
|
|
6
6
|
DISCONNECTED = 1,
|
|
7
7
|
RECONNECTING = 2
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Client is a GraphQL client connected to a Gadget application's /edit/api/graphql-ws endpoint.
|
|
11
|
+
*
|
|
12
|
+
* NOTE: In order to use the Client, the user must be logged in and an app must have been selected (`context.app` and
|
|
13
|
+
* `context.session` must be set).
|
|
14
|
+
*/
|
|
9
15
|
export declare class Client {
|
|
10
16
|
status: ConnectionStatus;
|
|
11
17
|
private _client;
|
package/lib/utils/client.js
CHANGED
|
@@ -16,6 +16,12 @@ var ConnectionStatus;
|
|
|
16
16
|
ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 1] = "DISCONNECTED";
|
|
17
17
|
ConnectionStatus[ConnectionStatus["RECONNECTING"] = 2] = "RECONNECTING";
|
|
18
18
|
})(ConnectionStatus || (ConnectionStatus = {}));
|
|
19
|
+
/**
|
|
20
|
+
* Client is a GraphQL client connected to a Gadget application's /edit/api/graphql-ws endpoint.
|
|
21
|
+
*
|
|
22
|
+
* NOTE: In order to use the Client, the user must be logged in and an app must have been selected (`context.app` and
|
|
23
|
+
* `context.session` must be set).
|
|
24
|
+
*/
|
|
19
25
|
class Client {
|
|
20
26
|
constructor() {
|
|
21
27
|
// assume the client is going to connect
|
package/lib/utils/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"/","sources":["utils/client.ts"],"names":[],"mappings":";;;;AAAA,4DAA4B;AAC5B,0DAA0B;AAG1B,2CAA0C;AAE1C,mCAA0C;AAG1C,oDAA2B;AAC3B,uCAAoC;AACpC,qCAAuC;AAEvC,MAAM,KAAK,GAAG,IAAA,eAAK,EAAC,YAAY,CAAC,CAAC;AAElC,IAAK,gBAIJ;AAJD,WAAK,gBAAgB;IACnB,iEAAS,CAAA;IACT,uEAAY,CAAA;IACZ,uEAAY,CAAA;AACd,CAAC,EAJI,gBAAgB,KAAhB,gBAAgB,QAIpB;AAED,MAAa,MAAM;IAMjB;QALA,wCAAwC;QACxC;;;;mBAAS,gBAAgB,CAAC,SAAS;WAAC;QAE5B;;;;;WAAyC;QAG/C,IAAA,gBAAM,EAAC,iBAAO,CAAC,GAAG,EAAE,yDAAyD,CAAC,CAAC;QAE/E,IAAI,CAAC,OAAO,GAAG,IAAA,yBAAY,EAAC;YAC1B,GAAG,EAAE,SAAS,iBAAO,CAAC,GAAG,CAAC,IAAI,IAAI,iBAAO,CAAC,OAAO,CAAC,GAAG,sBAAsB;YAC3E,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI;YACvB,aAAa,EAAE,KAAM,SAAQ,YAAS;gBACpC,YAAY,OAAqB,EAAE,SAA6B,EAAE,SAAuD;oBACvH,IAAA,gBAAM,EAAC,iBAAO,CAAC,OAAO,EAAE,6DAA6D,CAAC,CAAC;oBACvF,KAAK,CAAC,OAAO,EAAE,SA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OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,IAAI,CAAC,SAAS,CAA8B,OAAO,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;QACzF,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,WAAW,CAAwD,OAAiC;QACxG,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACzC,IAAI,MAAM,CAAC,MAAM;YAAE,MAAM,IAAI,oBAAW,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,CAAC,IAAI;YAAE,MAAM,IAAI,oBAAW,CAAC,OAAO,EAAE,qCAAqC,CAAC,CAAC;QACxF,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IAC/B,CAAC;CACF;AAvJD,wBAuJC","sourcesContent":["import assert from \"assert\";\nimport Debug from \"debug\";\nimport type { GraphQLError } from \"graphql\";\nimport type { ExecutionResult, SubscribePayload } from \"graphql-ws\";\nimport { createClient } from \"graphql-ws\";\nimport type { ClientRequestArgs } from \"http\";\nimport { isFunction, noop } from \"lodash\";\nimport type { JsonObject, SetOptional } from \"type-fest\";\nimport type { CloseEvent, ErrorEvent } from \"ws\";\nimport WebSocket from \"ws\";\nimport { context } from \"./context\";\nimport { ClientError } from \"./errors\";\n\nconst debug = Debug(\"ggt:client\");\n\nenum ConnectionStatus {\n CONNECTED,\n DISCONNECTED,\n RECONNECTING,\n}\n\nexport class Client {\n // assume the client is going to connect\n status = ConnectionStatus.CONNECTED;\n\n private _client: ReturnType<typeof createClient>;\n\n constructor() {\n assert(context.app, \"context.app must be set before instantiating the Client\");\n\n this._client = createClient({\n url: `wss://${context.app.slug}.${context.domains.app}/edit/api/graphql-ws`,\n shouldRetry: () => true,\n webSocketImpl: class extends WebSocket {\n constructor(address: string | URL, protocols?: string | string[], wsOptions?: WebSocket.ClientOptions | ClientRequestArgs) {\n assert(context.session, \"context.session must be set before instantiating the Client\");\n super(address, protocols, {\n ...wsOptions,\n headers: {\n ...wsOptions?.headers,\n \"user-agent\": context.config.userAgent,\n cookie: `session=${encodeURIComponent(context.session)};`,\n },\n });\n }\n },\n on: {\n connecting: () => {\n switch (this.status) {\n case ConnectionStatus.DISCONNECTED:\n this.status = ConnectionStatus.RECONNECTING;\n debug(\"reconnecting...\");\n break;\n case ConnectionStatus.RECONNECTING:\n debug(\"retrying...\");\n break;\n default:\n debug(\"connecting...\");\n break;\n }\n },\n connected: () => {\n if (this.status === ConnectionStatus.RECONNECTING) {\n debug(\"reconnected\");\n } else {\n debug(\"connected\");\n }\n\n // let the other on connected listeners see what status we're in\n setImmediate(() => (this.status = ConnectionStatus.CONNECTED));\n },\n closed: (e) => {\n const event = e as CloseEvent;\n if (event.wasClean) {\n debug(\"connection closed\");\n return;\n }\n\n if (this.status === ConnectionStatus.CONNECTED) {\n this.status = ConnectionStatus.DISCONNECTED;\n debug(\"disconnected\");\n }\n },\n error: (error) => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n debug(\"failed to reconnect %o\", { error });\n } else {\n debug(\"connection error %o\", { error });\n }\n },\n },\n });\n }\n\n subscribe<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>,\n sink: SetOptional<Sink<Data, Extensions>, \"complete\">\n ): () => void {\n let subscribePayload: SubscribePayload;\n let removeConnectedListener: () => void;\n\n if (isFunction(payload.variables)) {\n // the caller wants us to re-evaluate the variables every time graphql-ws re-subscribes after reconnecting\n subscribePayload = { ...payload, variables: payload.variables() };\n removeConnectedListener = this._client.on(\"connected\", () => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n // subscribePayload.variables is supposed to be readonly (it's not) and payload.variables may have been re-assigned (it won't)\n (subscribePayload as any).variables = (payload.variables as any)();\n debug(\"re-sending %s%s%O\", subscribePayload.query.split(/\\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);\n }\n });\n } else {\n subscribePayload = payload as SubscribePayload;\n }\n\n debug(\"sending %s%s%O\", subscribePayload.query.split(/\\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);\n const unsubscribe = this._client.subscribe(subscribePayload, {\n next: (result: ExecutionResult<Data, Extensions>) => sink.next(result),\n error: (error) => sink.error(new ClientError(subscribePayload, error as Error | GraphQLError[] | CloseEvent | ErrorEvent)),\n complete: () => sink.complete?.() ?? noop,\n });\n\n return () => {\n removeConnectedListener?.();\n unsubscribe();\n };\n }\n\n subscribeUnwrap<Data extends JsonObject, Variables extends JsonObject>(\n payload: Payload<Data, Variables>,\n sink: { next: (data: Data) => void; error: (error: ClientError) => void }\n ): () => void {\n const unsubscribe = this.subscribe(payload, {\n ...sink,\n next: (result) => {\n if (result.errors) {\n unsubscribe();\n sink.error(new ClientError(payload, result.errors));\n return;\n }\n\n if (!result.data) {\n sink.error(new ClientError(payload, \"We received a response without data\"));\n unsubscribe();\n return;\n }\n\n sink.next(result.data);\n },\n });\n\n return unsubscribe;\n }\n\n query<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>\n ): Promise<ExecutionResult<Data, Extensions>> {\n return new Promise((resolve, reject) => {\n this.subscribe<Data, Variables, Extensions>(payload, { next: resolve, error: reject });\n });\n }\n\n async queryUnwrap<Data extends JsonObject, Variables extends JsonObject>(payload: Payload<Data, Variables>): Promise<Data> {\n const result = await this.query(payload);\n if (result.errors) throw new ClientError(payload, result.errors);\n if (!result.data) throw new ClientError(payload, \"We received a response without data\");\n return result.data;\n }\n\n async dispose(): Promise<void> {\n await this._client.dispose();\n }\n}\n\nexport type Query<\n Data extends JsonObject,\n Variables extends JsonObject = JsonObject,\n Extensions extends JsonObject = JsonObject\n> = string & {\n __TData?: Data;\n __TVariables?: Variables;\n __TExtensions?: Extensions;\n};\n\nexport interface Payload<Data extends JsonObject, Variables extends JsonObject> {\n readonly query: Query<Data, Variables>;\n readonly variables?: Variables | (() => Variables) | null;\n}\n\nexport interface Sink<Data extends JsonObject, Extensions extends JsonObject> {\n next(value: ExecutionResult<Data, Extensions>): void;\n error(error: ClientError): void;\n complete(): void;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"/","sources":["utils/client.ts"],"names":[],"mappings":";;;;AAAA,4DAA4B;AAC5B,0DAA0B;AAG1B,2CAA0C;AAE1C,mCAA0C;AAG1C,oDAA2B;AAC3B,uCAAoC;AACpC,qCAAuC;AAEvC,MAAM,KAAK,GAAG,IAAA,eAAK,EAAC,YAAY,CAAC,CAAC;AAElC,IAAK,gBAIJ;AAJD,WAAK,gBAAgB;IACnB,iEAAS,CAAA;IACT,uEAAY,CAAA;IACZ,uEAAY,CAAA;AACd,CAAC,EAJI,gBAAgB,KAAhB,gBAAgB,QAIpB;AAED;;;;;GAKG;AACH,MAAa,MAAM;IAMjB;QALA,wCAAwC;QACxC;;;;mBAAS,gBAAgB,CAAC,SAAS;WAAC;QAE5B;;;;;WAAyC;QAG/C,IAAA,gBAAM,EAAC,iBAAO,CAAC,GAAG,EAAE,yDAAyD,CAAC,CAAC;QAE/E,IAAI,CAAC,OAAO,GAAG,IAAA,yBAAY,EAAC;YAC1B,GAAG,EAAE,SAAS,iBAAO,CAAC,GAAG,CAAC,IAAI,IAAI,iBAAO,CAAC,OAAO,CAAC,GAAG,sBAAsB;YAC3E,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI;YACvB,aAAa,EAAE,KAAM,SAAQ,YAAS;gBACpC,YAAY,OAAqB,EAAE,SAA6B,EAAE,SAAuD;oBACvH,IAAA,gBAAM,EAAC,iBAAO,CAAC,OAAO,EAAE,6DAA6D,CAAC,CAAC;oBACvF,KAAK,CAAC,OAAO,EAAE,SAAS,EAAE;wBACxB,GAAG,SAAS;wB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AAO,EAAE,MAAM,EAAE,EAAE;YACrC,IAAI,CAAC,SAAS,CAA8B,OAAO,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;QACzF,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,WAAW,CAAwD,OAAiC;QACxG,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACzC,IAAI,MAAM,CAAC,MAAM;YAAE,MAAM,IAAI,oBAAW,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,CAAC,IAAI;YAAE,MAAM,IAAI,oBAAW,CAAC,OAAO,EAAE,qCAAqC,CAAC,CAAC;QACxF,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IAC/B,CAAC;CACF;AAvJD,wBAuJC","sourcesContent":["import assert from \"assert\";\nimport Debug from \"debug\";\nimport type { GraphQLError } from \"graphql\";\nimport type { ExecutionResult, SubscribePayload } from \"graphql-ws\";\nimport { createClient } from \"graphql-ws\";\nimport type { ClientRequestArgs } from \"http\";\nimport { isFunction, noop } from \"lodash\";\nimport type { JsonObject, SetOptional } from \"type-fest\";\nimport type { CloseEvent, ErrorEvent } from \"ws\";\nimport WebSocket from \"ws\";\nimport { context } from \"./context\";\nimport { ClientError } from \"./errors\";\n\nconst debug = Debug(\"ggt:client\");\n\nenum ConnectionStatus {\n CONNECTED,\n DISCONNECTED,\n RECONNECTING,\n}\n\n/**\n * Client is a GraphQL client connected to a Gadget application's /edit/api/graphql-ws endpoint.\n *\n * NOTE: In order to use the Client, the user must be logged in and an app must have been selected (`context.app` and\n * `context.session` must be set).\n */\nexport class Client {\n // assume the client is going to connect\n status = ConnectionStatus.CONNECTED;\n\n private _client: ReturnType<typeof createClient>;\n\n constructor() {\n assert(context.app, \"context.app must be set before instantiating the Client\");\n\n this._client = createClient({\n url: `wss://${context.app.slug}.${context.domains.app}/edit/api/graphql-ws`,\n shouldRetry: () => true,\n webSocketImpl: class extends WebSocket {\n constructor(address: string | URL, protocols?: string | string[], wsOptions?: WebSocket.ClientOptions | ClientRequestArgs) {\n assert(context.session, \"context.session must be set before instantiating the Client\");\n super(address, protocols, {\n ...wsOptions,\n headers: {\n ...wsOptions?.headers,\n \"user-agent\": context.config.userAgent,\n cookie: `session=${encodeURIComponent(context.session)};`,\n },\n });\n }\n },\n on: {\n connecting: () => {\n switch (this.status) {\n case ConnectionStatus.DISCONNECTED:\n this.status = ConnectionStatus.RECONNECTING;\n debug(\"reconnecting...\");\n break;\n case ConnectionStatus.RECONNECTING:\n debug(\"retrying...\");\n break;\n default:\n debug(\"connecting...\");\n break;\n }\n },\n connected: () => {\n if (this.status === ConnectionStatus.RECONNECTING) {\n debug(\"reconnected\");\n } else {\n debug(\"connected\");\n }\n\n // let the other on connected listeners see what status we're in\n setImmediate(() => (this.status = ConnectionStatus.CONNECTED));\n },\n closed: (e) => {\n const event = e as CloseEvent;\n if (event.wasClean) {\n debug(\"connection closed\");\n return;\n }\n\n if (this.status === ConnectionStatus.CONNECTED) {\n this.status = ConnectionStatus.DISCONNECTED;\n debug(\"disconnected\");\n }\n },\n error: (error) => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n debug(\"failed to reconnect %o\", { error });\n } else {\n debug(\"connection error %o\", { error });\n }\n },\n },\n });\n }\n\n subscribe<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>,\n sink: SetOptional<Sink<Data, Extensions>, \"complete\">\n ): () => void {\n let subscribePayload: SubscribePayload;\n let removeConnectedListener: () => void;\n\n if (isFunction(payload.variables)) {\n // the caller wants us to re-evaluate the variables every time graphql-ws re-subscribes after reconnecting\n subscribePayload = { ...payload, variables: payload.variables() };\n removeConnectedListener = this._client.on(\"connected\", () => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n // subscribePayload.variables is supposed to be readonly (it's not) and payload.variables may have been re-assigned (it won't)\n (subscribePayload as any).variables = (payload.variables as any)();\n debug(\"re-sending %s%s%O\", subscribePayload.query.split(/\\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);\n }\n });\n } else {\n subscribePayload = payload as SubscribePayload;\n }\n\n debug(\"sending %s%s%O\", subscribePayload.query.split(/\\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);\n const unsubscribe = this._client.subscribe(subscribePayload, {\n next: (result: ExecutionResult<Data, Extensions>) => sink.next(result),\n error: (error) => sink.error(new ClientError(subscribePayload, error as Error | GraphQLError[] | CloseEvent | ErrorEvent)),\n complete: () => sink.complete?.() ?? noop,\n });\n\n return () => {\n removeConnectedListener?.();\n unsubscribe();\n };\n }\n\n subscribeUnwrap<Data extends JsonObject, Variables extends JsonObject>(\n payload: Payload<Data, Variables>,\n sink: { next: (data: Data) => void; error: (error: ClientError) => void }\n ): () => void {\n const unsubscribe = this.subscribe(payload, {\n ...sink,\n next: (result) => {\n if (result.errors) {\n unsubscribe();\n sink.error(new ClientError(payload, result.errors));\n return;\n }\n\n if (!result.data) {\n sink.error(new ClientError(payload, \"We received a response without data\"));\n unsubscribe();\n return;\n }\n\n sink.next(result.data);\n },\n });\n\n return unsubscribe;\n }\n\n query<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>\n ): Promise<ExecutionResult<Data, Extensions>> {\n return new Promise((resolve, reject) => {\n this.subscribe<Data, Variables, Extensions>(payload, { next: resolve, error: reject });\n });\n }\n\n async queryUnwrap<Data extends JsonObject, Variables extends JsonObject>(payload: Payload<Data, Variables>): Promise<Data> {\n const result = await this.query(payload);\n if (result.errors) throw new ClientError(payload, result.errors);\n if (!result.data) throw new ClientError(payload, \"We received a response without data\");\n return result.data;\n }\n\n async dispose(): Promise<void> {\n await this._client.dispose();\n }\n}\n\nexport type Query<\n Data extends JsonObject,\n Variables extends JsonObject = JsonObject,\n Extensions extends JsonObject = JsonObject\n> = string & {\n __TData?: Data;\n __TVariables?: Variables;\n __TExtensions?: Extensions;\n};\n\nexport interface Payload<Data extends JsonObject, Variables extends JsonObject> {\n readonly query: Query<Data, Variables>;\n readonly variables?: Variables | (() => Variables) | null;\n}\n\nexport interface Sink<Data extends JsonObject, Extensions extends JsonObject> {\n next(value: ExecutionResult<Data, Extensions>): void;\n error(error: ClientError): void;\n complete(): void;\n}\n"]}
|
package/lib/utils/context.d.ts
CHANGED
|
@@ -3,8 +3,9 @@ export declare class Context {
|
|
|
3
3
|
/**
|
|
4
4
|
* A reference to oclif's {@linkcode Config}.
|
|
5
5
|
*
|
|
6
|
-
* By default, oclif's {@linkcode Config} is only available as an instance property on a Command, but we want to be
|
|
7
|
-
* anywhere. To do this, we created this global variable that references the Config. It is set
|
|
6
|
+
* By default, oclif's {@linkcode Config} is only available as an instance property on a Command, but we want to be
|
|
7
|
+
* able to access it from anywhere. To do this, we created this global variable that references the Config. It is set
|
|
8
|
+
* by the init function in the BaseCommand.
|
|
8
9
|
*/
|
|
9
10
|
config: Config;
|
|
10
11
|
env: Env;
|
package/lib/utils/context.js
CHANGED
|
@@ -13,8 +13,9 @@ class Context {
|
|
|
13
13
|
/**
|
|
14
14
|
* A reference to oclif's {@linkcode Config}.
|
|
15
15
|
*
|
|
16
|
-
* By default, oclif's {@linkcode Config} is only available as an instance property on a Command, but we want to be
|
|
17
|
-
* anywhere. To do this, we created this global variable that references the Config. It is set
|
|
16
|
+
* By default, oclif's {@linkcode Config} is only available as an instance property on a Command, but we want to be
|
|
17
|
+
* able to access it from anywhere. To do this, we created this global variable that references the Config. It is set
|
|
18
|
+
* by the init function in the BaseCommand.
|
|
18
19
|
*/
|
|
19
20
|
Object.defineProperty(this, "config", {
|
|
20
21
|
enumerable: true,
|
package/lib/utils/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"/","sources":["utils/context.ts"],"names":[],"mappings":";;;;AACA,4DAA4B;AAC5B,gEAA0B;AAC1B,mDAAqC;AACrC,mCAAkC;AAClC,wDAAwB;AACxB,yCAA0C;AAE1C,MAAa,OAAO;
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"/","sources":["utils/context.ts"],"names":[],"mappings":";;;;AACA,4DAA4B;AAC5B,gEAA0B;AAC1B,mDAAqC;AACrC,mCAAkC;AAClC,wDAAwB;AACxB,yCAA0C;AAE1C,MAAa,OAAO;IAsClB;QArCA;;;;;;WAMG;QACH;;;;;WAAgB;QAEhB;;;;mBAAM,IAAI,GAAG,EAAE;WAAC;QAEhB;;;;;WAAU;QAEV;;;;;WAGE;QAEM;;;;;WAAkB;QAElB;;;;;WAAa;QAEb;;;;mBAAwB,EAAE;WAAC;QAE3B;;;;mBAAW,aAAG,CAAC,MAAM,CAAC;gBAC5B,KAAK,EAAE;oBACL,aAAa,EAAE;wBACb,CAAC,OAAO,EAAE,EAAE;4BACV,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC;4BACtD,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,OAAO,EAAE;gCAC9D,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,WAAW,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC;6BAC5E;wBACH,CAAC;qBACF;iBACF;aACF,CAAC;WAAC;QAGD,IAAI,CAAC,OAAO,GAAG;YACb,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC;YACjG,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,IAA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S,CAAC;QACvB,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;IAC3B,CAAC;CACF;AAjHD,0BAiHC;AAED;;GAEG;AACH,MAAM,GAAG;IACP,IAAI,KAAK;QACP,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,YAAY,CAAC;IAChD,CAAC;IAED,IAAI,cAAc;QAChB,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;IAC9C,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,eAAe,IAAI,IAAI,CAAC,QAAQ,CAAC;IAC/C,CAAC;CACF;AAeY,QAAA,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC","sourcesContent":["import type { Config } from \"@oclif/core\";\nimport assert from \"assert\";\nimport fs from \"fs-extra\";\nimport got, { HTTPError } from \"got\";\nimport { isString } from \"lodash\";\nimport path from \"path\";\nimport { ignoreEnoent } from \"./fs-utils\";\n\nexport class Context {\n /**\n * A reference to oclif's {@linkcode Config}.\n *\n * By default, oclif's {@linkcode Config} is only available as an instance property on a Command, but we want to be\n * able to access it from anywhere. To do this, we created this global variable that references the Config. It is set\n * by the init function in the BaseCommand.\n */\n config!: Config;\n\n env = new Env();\n\n app?: App;\n\n domains: {\n app: string;\n services: string;\n };\n\n private _session?: string;\n\n private _user?: User;\n\n private _availableApps: App[] = [];\n\n private _request = got.extend({\n hooks: {\n beforeRequest: [\n (options) => {\n options.headers[\"user-agent\"] = this.config.userAgent;\n if (options.url.host === this.domains.services && this.session) {\n options.headers[\"cookie\"] = `session=${encodeURIComponent(this.session)};`;\n }\n },\n ],\n },\n });\n\n constructor() {\n this.domains = {\n app: process.env[\"GGT_GADGET_APP_DOMAIN\"] || (this.env.productionLike ? \"gadget.app\" : \"ggt.pub\"),\n services: process.env[\"GGT_GADGET_SERVICES_DOMAIN\"] || (this.env.productionLike ? \"app.gadget.dev\" : \"app.ggt.dev\"),\n };\n }\n\n get session(): string | undefined {\n if (this._session) return this._session;\n\n try {\n this._session = fs.readFileSync(path.join(this.config.configDir, \"session.txt\"), \"utf-8\");\n return this._session;\n } catch (error) {\n ignoreEnoent(error);\n return undefined;\n }\n }\n\n set session(value: string | undefined) {\n this.clear();\n this._session = value;\n if (this._session) {\n fs.outputFileSync(path.join(this.config.configDir, \"session.txt\"), this._session);\n } else {\n fs.removeSync(path.join(this.config.configDir, \"session.txt\"));\n }\n }\n\n /**\n * @returns The current user, or undefined if the user is not logged in.\n */\n async getUser(): Promise<User | undefined> {\n if (!this.session) return undefined;\n if (this._user) return this._user;\n\n try {\n this._user = await this._request(`https://${this.domains.services}/auth/api/current-user`).json<User>();\n return this._user;\n } catch (error) {\n if (error instanceof HTTPError && error.response.statusCode === 401) {\n this.session = undefined;\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * @returns The list of Gadget applications the current user has access to.\n */\n async getAvailableApps(): Promise<App[]> {\n if (!this.session) return [];\n if (this._availableApps.length > 0) return this._availableApps;\n\n this._availableApps = await this._request(`https://${this.domains.services}/auth/api/apps`).json<App[]>();\n return this._availableApps;\n }\n\n async setApp(appOrSlug?: App | string): Promise<void> {\n if (isString(appOrSlug)) {\n const app = await this.getAvailableApps().then((apps) => apps.find((app) => app.slug == appOrSlug));\n assert(app, `attempted to set app to \"${appOrSlug}\" but no app with that name or slug was found`);\n this.app = app;\n } else {\n this.app = appOrSlug;\n }\n }\n\n clear(): void {\n this._session = undefined;\n this._user = undefined;\n this.app = undefined;\n this._availableApps = [];\n }\n}\n\n/**\n * Captures the name and nature of the environment\n */\nclass Env {\n get value(): string {\n return process.env[\"GGT_ENV\"] || \"production\";\n }\n\n get productionLike(): boolean {\n return this.value.startsWith(\"production\");\n }\n\n get developmentLike(): boolean {\n return this.value.startsWith(\"development\");\n }\n\n get testLike(): boolean {\n return this.value.startsWith(\"test\");\n }\n\n get developmentOrTestLike(): boolean {\n return this.developmentLike || this.testLike;\n }\n}\n\nexport interface User {\n id: string | number;\n email: string;\n name?: string;\n}\n\nexport interface App {\n id: string | number;\n slug: string;\n primaryDomain: string;\n hasSplitEnvironments: boolean;\n}\n\nexport const context = new Context();\n"]}
|
package/lib/utils/fs-utils.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare class
|
|
1
|
+
export declare class FSIgnorer {
|
|
2
2
|
private readonly _rootDir;
|
|
3
3
|
private readonly _alwaysIgnore;
|
|
4
4
|
readonly filepath: string;
|
|
@@ -8,7 +8,7 @@ export declare class Ignorer {
|
|
|
8
8
|
reload(): void;
|
|
9
9
|
}
|
|
10
10
|
export interface WalkDirOptions {
|
|
11
|
-
ignorer?:
|
|
11
|
+
ignorer?: FSIgnorer;
|
|
12
12
|
}
|
|
13
13
|
export declare function walkDir(dir: string, options?: WalkDirOptions): AsyncGenerator<string>;
|
|
14
14
|
export declare function walkDirSync(dir: string, options?: WalkDirOptions): Generator<string>;
|