@gadgetinc/ggt 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +6 -6
  2. package/bin/dev.js +2 -2
  3. package/bin/run.js +1 -1
  4. package/lib/__generated__/graphql.js.map +1 -1
  5. package/lib/commands/help.js +3 -3
  6. package/lib/commands/help.js.map +1 -1
  7. package/lib/commands/list.js +4 -4
  8. package/lib/commands/list.js.map +1 -1
  9. package/lib/commands/login.js +2 -2
  10. package/lib/commands/login.js.map +1 -1
  11. package/lib/commands/logout.js +2 -2
  12. package/lib/commands/logout.js.map +1 -1
  13. package/lib/commands/sync.js +239 -83
  14. package/lib/commands/sync.js.map +1 -1
  15. package/lib/commands/whoami.js +2 -2
  16. package/lib/commands/whoami.js.map +1 -1
  17. package/lib/{utils → services}/base-command.js +25 -10
  18. package/lib/services/base-command.js.map +1 -0
  19. package/lib/{utils → services}/client.js +70 -21
  20. package/lib/services/client.js.map +1 -0
  21. package/lib/{utils → services}/context.js +42 -27
  22. package/lib/services/context.js.map +1 -0
  23. package/lib/{utils → services}/errors.js +8 -8
  24. package/lib/services/errors.js.map +1 -0
  25. package/lib/{utils → services}/flags.js +4 -3
  26. package/lib/services/flags.js.map +1 -0
  27. package/lib/{utils → services}/fs-utils.js +6 -2
  28. package/lib/services/fs-utils.js.map +1 -0
  29. package/lib/{utils → services}/help.js +1 -1
  30. package/lib/services/help.js.map +1 -0
  31. package/lib/services/promise.js.map +1 -0
  32. package/lib/{utils → services}/sleep.js +6 -2
  33. package/lib/services/sleep.js.map +1 -0
  34. package/npm-shrinkwrap.json +2378 -2704
  35. package/oclif.manifest.json +35 -15
  36. package/package.json +35 -34
  37. package/lib/utils/base-command.js.map +0 -1
  38. package/lib/utils/client.js.map +0 -1
  39. package/lib/utils/context.js.map +0 -1
  40. package/lib/utils/errors.js.map +0 -1
  41. package/lib/utils/flags.js.map +0 -1
  42. package/lib/utils/fs-utils.js.map +0 -1
  43. package/lib/utils/help.js.map +0 -1
  44. package/lib/utils/promise.js.map +0 -1
  45. package/lib/utils/sleep.js.map +0 -1
  46. /package/lib/{utils → services}/promise.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/sync.ts"],"sourcesContent":["import { Args, Flags } from \"@oclif/core\";\nimport assert from \"assert\";\nimport chalkTemplate from \"chalk-template\";\nimport { FSWatcher } from \"chokidar\";\nimport { format } from \"date-fns\";\nimport { execa } from \"execa\";\nimport type { Stats } from \"fs-extra\";\nimport fs from \"fs-extra\";\nimport inquirer from \"inquirer\";\nimport _ 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 type {\n FileSyncChangedEventInput,\n FileSyncDeletedEventInput,\n PublishFileSyncEventsMutation,\n PublishFileSyncEventsMutationVariables,\n RemoteFileSyncEventsSubscription,\n RemoteFileSyncEventsSubscriptionVariables,\n RemoteFilesVersionQuery,\n RemoteFilesVersionQueryVariables,\n} from \"../__generated__/graphql.js\";\nimport { FileSyncEncoding } from \"../__generated__/graphql.js\";\nimport { BaseCommand } from \"../utils/base-command.js\";\nimport type { Query } from \"../utils/client.js\";\nimport { Client } from \"../utils/client.js\";\nimport { context } from \"../utils/context.js\";\nimport { InvalidSyncAppFlagError, InvalidSyncFileError, YarnNotFoundError } from \"../utils/errors.js\";\nimport { app } from \"../utils/flags.js\";\nimport { FSIgnorer, ignoreEnoent, isEmptyDir, walkDir } from \"../utils/fs-utils.js\";\nimport { PromiseSignal } from \"../utils/promise.js\";\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(chalkTemplate`\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(chalkTemplate`\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 * The state of the local filesystem.\n */\n state!: SyncState;\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 * Instead of deleting files, we move them to .gadget/backup so that users can recover them if something goes wrong.\n */\n async softDelete(normalizedPath: string): Promise<void> {\n try {\n await fs.move(this.absolute(normalizedPath), this.absolute(\".gadget/backup\", normalizedPath), {\n overwrite: true,\n });\n } catch (error) {\n // replicate the behavior of `rm -rf` and ignore ENOENT\n ignoreEnoent(error);\n }\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) => chalkTemplate`{green ${prefix}} ${normalizedPath} {gray (changed)}`),\n ...deleted.map((normalizedPath) => chalkTemplate`{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(chalkTemplate`{gray … ${lines.length - logged} more}`);\n }\n\n this.log(\n chalkTemplate`{gray ${pluralize(\"file\", lines.length, true)} in total. ${changed.length} changed, ${deleted.length} deleted.}`\n );\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 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.state?.app) return this.state.app;\n const selected = await inquirer.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 const app = await getApp();\n this.state = SyncState.create(this.dir, { app });\n } else {\n try {\n this.state = SyncState.load(this.dir);\n } catch (error) {\n if (!this.flags.force) {\n throw new InvalidSyncFileError(error, this, this.flags.app);\n }\n const app = await getApp();\n this.state = SyncState.create(this.dir, { app });\n }\n }\n\n if (this.flags.app && this.flags.app !== this.state.app && !this.flags.force) {\n throw new InvalidSyncAppFlagError(this);\n }\n\n await context.setApp(this.state.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.state.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.state.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.state, remoteFilesVersion, hasRemoteChanges, hasLocalChanges });\n\n let action: Action | undefined;\n if (hasLocalChanges) {\n ({ action } = await inquirer.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.state.mtime) {\n this.state.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) => this.softDelete(normalizedPath));\n this.state.filesVersion = 0n;\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 this.state.flush();\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(chalkTemplate` 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: String(this.state.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) > this.state.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.state.filesVersion, remoteFilesVersion);\n this.state.filesVersion = remoteFilesVersion;\n }\n return;\n }\n\n this.log(chalkTemplate`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 will be deleted as well\n await pMap(deleted, async (file) => {\n this.recentRemoteChanges.add(file.path);\n await this.softDelete(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.state.filesVersion, remoteFilesVersion);\n this.state.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: String(this.state.filesVersion), changed, deleted } },\n });\n\n this.log(chalkTemplate`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) > this.state.filesVersion) {\n this.debug(\"updated local files version from %s to %s\", this.state.filesVersion, remoteFilesVersion);\n this.state.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.state.mtime) {\n this.state.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(chalkTemplate`\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\n/**\n * Holds information about the state of the local filesystem. It's persisted to `.gadget/sync.json`.\n */\nexport class SyncState {\n private _inner: {\n app: string;\n filesVersion: string;\n mtime: number;\n };\n\n /**\n * Saves the current state of the filesystem to `.gadget/sync.json`.\n */\n #save = _.debounce(() => {\n fs.outputJSONSync(path.join(this._rootDir, \".gadget/sync.json\"), this._inner, { spaces: 2 });\n }, 100);\n\n private constructor(private _rootDir: string, inner: { app: string; filesVersion: string; mtime: number }) {\n this._inner = inner;\n }\n\n /**\n * The app this filesystem is synced to.\n */\n get app(): string {\n return this._inner.app;\n }\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 get filesVersion(): bigint {\n return BigInt(this._inner.filesVersion);\n }\n\n set filesVersion(value: bigint | string) {\n this._inner.filesVersion = String(value);\n this.#save();\n }\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 // eslint-disable-next-line @typescript-eslint/member-ordering\n get mtime(): number {\n return this._inner.mtime;\n }\n\n set mtime(value: number) {\n this._inner.mtime = value;\n this.#save();\n }\n\n /**\n * Creates a new SyncFile instance and saves it to the filesystem.\n *\n * @param rootDir The root directory of the app.\n * @param app The app slug.\n * @returns A new SyncFile instance.\n */\n static create(rootDir: string, opts: { app: string; filesVersion?: string; mtime?: number }): SyncState {\n const state = new SyncState(rootDir, { filesVersion: \"0\", mtime: 0, ...opts });\n state.#save();\n state.flush();\n return state;\n }\n\n /**\n * Loads a SyncFile instance from the filesystem.\n *\n * @param rootDir The root directory of the app.\n * @returns The SyncFile instance.\n */\n static load(rootDir: string): SyncState {\n const state = fs.readJsonSync(path.join(rootDir, \".gadget/sync.json\"));\n\n assert(_.isString(state.app), \"missing or invalid app\");\n assert(_.isString(state.filesVersion), \"missing or invalid filesVersion\");\n assert(_.isNumber(state.mtime), \"missing or invalid mtime\");\n\n return new SyncState(rootDir, {\n app: state.app,\n filesVersion: state.filesVersion,\n mtime: state.mtime,\n });\n }\n\n /**\n * Flushes any pending writes to the filesystem.\n */\n flush(): void {\n this.#save.flush();\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"],"names":["Args","Flags","assert","chalkTemplate","FSWatcher","format","execa","fs","inquirer","_","normalizePath","pMap","PQueue","path","pluralize","dedent","which","FileSyncEncoding","BaseCommand","Client","context","InvalidSyncAppFlagError","InvalidSyncFileError","YarnNotFoundError","app","FSIgnorer","ignoreEnoent","isEmptyDir","walkDir","PromiseSignal","Sync","relative","to","dir","absolute","pathSegments","resolve","normalize","filepath","isDirectory","isAbsolute","softDelete","normalizedPath","move","overwrite","error","logPaths","prefix","changed","deleted","limit","lines","sortBy","map","line","slice","indexOf","logged","log","debugEnabled","length","init","isString","args","config","windows","startsWith","join","home","getApp","flags","state","selected","prompt","type","name","message","choices","getAvailableApps","then","apps","slug","SyncState","create","load","force","setApp","client","ignorer","watcher","ignored","ignores","ignoreInitial","alwaysStat","awaitWriteFinish","pollInterval","stabilityThreshold","debug","sync","nothrow","ensureDir","remoteFilesVersion","queryUnwrap","query","REMOTE_FILES_VERSION_QUERY","hasRemoteChanges","BigInt","filesVersion","getChangedFiles","files","Map","absolutePath","stats","stat","mtime","getTime","set","delete","changedFiles","hasLocalChanges","size","Array","from","keys","metadata","action","Action","CANCEL","MERGE","RESET","PUBLISH_FILE_SYNC_EVENTS_MUTATION","variables","input","expectedRemoteFilesVersion","mode","content","readFile","encoding","Base64","process","exit","run","stopped","stop","e","status","SyncStatus","RUNNING","STOPPING","unsubscribe","removeAllListeners","publish","flush","queue","onIdle","Promise","allSettled","close","dispose","STOPPED","signal","on","setTimeout","once","unref","subscribeUnwrap","REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION","localFilesVersion","String","next","remoteFileSyncEvents","filter","event","_enqueue","Date","x","file","recentRemoteChanges","add","endsWith","dirname","writeFile","Buffer","cwd","catch","err","reload","localFilesBuffer","debounce","localFiles","entries","clear","push","data","publishFileSyncEvents","isSymbolicLink","isDeleted","version","hasSplitEnvironments","primaryDomain","notify","subtitle","fn","requireUser","STARTING","Set","concurrency","priority","summary","usage","description","directory","string","default","boolean","integer","helpGroup","helpValue","hidden","examples","_inner","value","save","rootDir","opts","readJsonSync","isNumber","_rootDir","inner","outputJSONSync","spaces"],"mappings":";;;;AAAA,SAASA,IAAI,EAAEC,KAAK,QAAQ,cAAc;AAC1C,OAAOC,YAAY,SAAS;AAC5B,OAAOC,mBAAmB,iBAAiB;AAC3C,SAASC,SAAS,QAAQ,WAAW;AACrC,SAASC,MAAM,QAAQ,WAAW;AAClC,SAASC,KAAK,QAAQ,QAAQ;AAE9B,OAAOC,QAAQ,WAAW;AAC1B,OAAOC,cAAc,WAA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U1D,WAAAA,WAEVC,aAAAA,KAAAA;IAFUD,WAAAA,WAGVE,cAAAA,KAAAA;IAHUF,WAAAA,WAIVa,aAAAA,KAAAA;GAJUb,eAAAA;WAOL;UAAKpB,MAAM;IAANA,OACVC,YAAS;IADCD,OAEVE,WAAQ;IAFEF,OAGVG,WAAQ;GAHEH,WAAAA;AAMZ,OAAO,MAAMwC,uCAGT,WAAW,GAAG,CAAC;;;;;;;;;;;;;;;AAenB,CAAC,CAAC;AAEF,OAAO,MAAM9D,6BAA+F,WAAW,GAAG,CAAC;;;;AAI3H,CAAC,CAAC;AAEF,OAAO,MAAM0B,oCAGT,WAAW,GAAG,CAAC;;;;;;AAMnB,CAAC,CAAC"}
1
+ {"version":3,"sources":["../../src/commands/sync.ts"],"sourcesContent":["import { Args, Flags } from \"@oclif/core\";\nimport assert from \"assert\";\nimport chalkTemplate from \"chalk-template\";\nimport { format } from \"date-fns\";\nimport { execa } from \"execa\";\nimport type { Stats } from \"fs-extra\";\nimport fs from \"fs-extra\";\nimport inquirer from \"inquirer\";\nimport _ 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 FSWatcher from \"watcher\";\nimport which from \"which\";\nimport type {\n FileSyncChangedEventInput,\n FileSyncDeletedEventInput,\n PublishFileSyncEventsMutation,\n PublishFileSyncEventsMutationVariables,\n RemoteFileSyncEventsSubscription,\n RemoteFileSyncEventsSubscriptionVariables,\n RemoteFilesVersionQuery,\n RemoteFilesVersionQueryVariables,\n} from \"../__generated__/graphql.js\";\nimport { FileSyncEncoding } from \"../__generated__/graphql.js\";\nimport { BaseCommand } from \"../services/base-command.js\";\nimport type { Query } from \"../services/client.js\";\nimport { Client } from \"../services/client.js\";\nimport { context } from \"../services/context.js\";\nimport { InvalidSyncAppFlagError, InvalidSyncFileError, YarnNotFoundError } from \"../services/errors.js\";\nimport { app } from \"../services/flags.js\";\nimport { FSIgnorer, ignoreEnoent, isEmptyDir, walkDir } from \"../services/fs-utils.js\";\nimport { PromiseSignal } from \"../services/promise.js\";\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(chalkTemplate`\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 // The following flags are passed to FSWatcher (https://github.com/fabiospampinato/watcher)\n \"file-watch-debounce\": Flags.integer({\n summary: \"Amount of milliseconds to debounce file changed events\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 300,\n hidden: true,\n }),\n \"file-watch-poll-interval\": Flags.integer({\n summary:\n \"Polling is used as a last resort measure when watching non-existent paths inside non-existent directories, this controls how often polling is performed, in milliseconds. You can set it to a lower value to make the app detect events much more quickly, but don't set it too low if you are watching many paths that require polling as polling is expensive.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 3_000,\n hidden: true,\n }),\n \"file-watch-poll-timeout\": Flags.integer({\n summary:\n \"Sometimes polling will fail, for example if there are too many file descriptors currently open, usually eventually polling will succeed after a few tries though, this controls the amount of milliseconds the library should keep retrying for.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 20_000,\n hidden: true,\n }),\n \"file-watch-rename-timeout\": Flags.integer({\n summary:\n \"Amount of milliseconds to wait for a potential rename/renameDir event to be detected. The higher this value is the more reliably renames will be detected, but don't set this too high, or the emission of some events could be delayed by that amount. The higher this value is the longer the library will take to emit add/addDir/unlink/unlinkDir events.\",\n helpGroup: \"file\",\n helpValue: \"ms\",\n default: 1_250,\n hidden: true,\n }),\n };\n\n static override examples = [\n dedent(chalkTemplate`\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 * The state of the local filesystem.\n */\n state!: SyncState;\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 * Instead of deleting files, we move them to .gadget/backup so that users can recover them if something goes wrong.\n */\n async softDelete(normalizedPath: string): Promise<void> {\n try {\n await fs.move(this.absolute(normalizedPath), this.absolute(\".gadget/backup\", normalizedPath), {\n overwrite: true,\n });\n } catch (error) {\n // replicate the behavior of `rm -rf` and ignore ENOENT\n ignoreEnoent(error);\n }\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 ..._.map(changed, (normalizedPath) => chalkTemplate`{green ${prefix}} ${normalizedPath} {gray (changed)}`),\n ..._.map(deleted, (normalizedPath) => chalkTemplate`{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(chalkTemplate`{gray … ${lines.length - logged} more}`);\n }\n\n this.log(\n chalkTemplate`{gray ${pluralize(\"file\", lines.length, true)} in total. ${changed.length} changed, ${deleted.length} deleted.}`,\n );\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 && _.startsWith(this.args.directory, \"~/\")\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) {\n return this.flags.app;\n }\n\n // this.state can be undefined if the user is running `ggt sync` for the first time\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.state?.app) {\n return this.state.app;\n }\n\n const selected = await inquirer.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) => _.map(apps, \"slug\")),\n });\n\n return selected.app;\n };\n\n if (await isEmptyDir(this.dir)) {\n const app = await getApp();\n this.state = SyncState.create(this.dir, { app });\n } else {\n try {\n this.state = SyncState.load(this.dir);\n } catch (error) {\n if (!this.flags.force) {\n throw new InvalidSyncFileError(error, this, this.flags.app);\n }\n const app = await getApp();\n this.state = SyncState.create(this.dir, { app });\n }\n }\n\n if (this.flags.app && this.flags.app !== this.state.app && !this.flags.force) {\n throw new InvalidSyncAppFlagError(this);\n }\n\n await context.setApp(this.state.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 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.state.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.state.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 let 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 context.addBreadcrumb({\n category: \"sync\",\n message: \"Initializing\",\n data: {\n state: this.state,\n remoteFilesVersion,\n hasRemoteChanges,\n hasLocalChanges,\n changed: Array.from(changedFiles.keys()),\n },\n });\n\n let action: Action | undefined;\n if (hasLocalChanges) {\n ({ action } = await inquirer.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 // get all the changed files again in case more changed\n changedFiles = await getChangedFiles();\n\n switch (action) {\n case Action.MERGE: {\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Merging local changes\",\n data: {\n state: this.state,\n remoteFilesVersion,\n changed: Array.from(changedFiles.keys()),\n },\n });\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(changedFiles, async ([normalizedPath, stats]) => {\n if (stats.mtime.getTime() > this.state.mtime) {\n this.state.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 context.addBreadcrumb({\n category: \"sync\",\n message: \"Resetting local changes\",\n data: {\n state: this.state,\n remoteFilesVersion,\n changed: Array.from(changedFiles.keys()),\n },\n });\n\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) => this.softDelete(normalizedPath));\n this.state.filesVersion = 0n;\n break;\n }\n case Action.CANCEL: {\n process.exit(0);\n }\n }\n\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Initialized\",\n data: {\n state: this.state,\n },\n });\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 this.status = SyncStatus.STOPPING;\n error = e;\n\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Stopping\",\n level: error ? \"error\" : undefined,\n data: {\n state: this.state,\n error,\n },\n });\n\n try {\n unsubscribe();\n this.watcher.removeAllListeners();\n this.publish.flush();\n await this.queue.onIdle();\n } finally {\n this.state.flush();\n await Promise.allSettled([this.watcher.close(), this.client.dispose()]);\n\n this.status = SyncStatus.STOPPED;\n stopped.resolve();\n\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Stopped\",\n data: {\n state: this.state,\n },\n });\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(chalkTemplate` 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: String(this.state.filesVersion) }),\n },\n {\n error: (error) => void this.stop(error),\n next: ({ remoteFileSyncEvents }) => {\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Received file sync events\",\n data: {\n state: this.state,\n remoteFilesVersion: remoteFileSyncEvents.remoteFilesVersion,\n changed: _.map(remoteFileSyncEvents.changed, \"path\"),\n deleted: _.map(remoteFileSyncEvents.deleted, \"path\"),\n },\n });\n\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 }) => _.startsWith(event.path, \".gadget/\") || !this.ignorer.ignores(event.path);\n const changed = _.filter(remoteFileSyncEvents.changed, filter);\n const deleted = _.filter(remoteFileSyncEvents.deleted, filter);\n\n this._enqueue(async () => {\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Processing received file sync events\",\n data: {\n state: this.state,\n remoteFilesVersion: remoteFileSyncEvents.remoteFilesVersion,\n changed: _.map(remoteFileSyncEvents.changed, \"path\"),\n deleted: _.map(remoteFileSyncEvents.deleted, \"path\"),\n },\n });\n\n if (!changed.length && !deleted.length) {\n if (BigInt(remoteFilesVersion) > this.state.filesVersion) {\n // we still need to update filesVersion, otherwise our expectedFilesVersion will be behind the next time we publish\n this.state.filesVersion = remoteFilesVersion;\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Received empty file sync events\",\n data: {\n state: this.state,\n remoteFilesVersion: remoteFileSyncEvents.remoteFilesVersion,\n },\n });\n }\n return;\n }\n\n this.log(chalkTemplate`Received {gray ${format(new Date(), \"pp\")}}`);\n this.logPaths(\"←\", _.map(changed, \"path\"), _.map(deleted, \"path\"));\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 will be deleted as well\n await pMap(deleted, async (file) => {\n this.recentRemoteChanges.add(file.path);\n await this.softDelete(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 (_.endsWith(file.path, \"/\")) {\n await fs.ensureDir(absolutePath, { mode: 0o755 });\n return;\n }\n\n // we need to add all parent directories to recentRemoteChanges so that we don't re-publish them\n for (const dir of _.split(path.dirname(file.path), \"/\")) {\n this.recentRemoteChanges.add(dir + \"/\");\n }\n\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((error) => {\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Yarn install failed\",\n level: \"error\",\n data: {\n state: this.state,\n error,\n },\n });\n });\n }\n\n if (absolutePath == this.ignorer.filepath) {\n this.ignorer.reload();\n }\n });\n\n this.state.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 context.addBreadcrumb({\n category: \"sync\",\n message: \"Processed received file sync events\",\n data: {\n state: this.state,\n remoteFilesVersion: remoteFileSyncEvents.remoteFilesVersion,\n changed: _.map(remoteFileSyncEvents.changed, \"path\"),\n deleted: _.map(remoteFileSyncEvents.deleted, \"path\"),\n recentRemoteChanges: Array.from(this.recentRemoteChanges.keys()),\n },\n });\n });\n },\n },\n );\n\n const localFilesBuffer = new Map<\n string,\n | { mode: number; isDirectory: boolean }\n | { isDeleted: true; isDirectory: boolean }\n | { mode: number; oldPath: string; newPath: string; isDirectory: boolean }\n >();\n\n this.publish = _.debounce(() => {\n const localFiles = new Map(localFilesBuffer.entries());\n localFilesBuffer.clear();\n\n this._enqueue(async () => {\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Publishing file sync events\",\n data: {\n state: this.state,\n localFiles: Array.from(localFiles.keys()),\n },\n });\n\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 oldPath: \"oldPath\" in file ? file.oldPath : undefined,\n mode: file.mode,\n content: file.isDirectory ? \"\" : await fs.readFile(this.absolute(normalizedPath), FileSyncEncoding.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 { publishFileSyncEvents } = await this.client.queryUnwrap({\n query: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: { input: { expectedRemoteFilesVersion: String(this.state.filesVersion), changed, deleted } },\n });\n\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Published file sync events\",\n data: {\n state: this.state,\n remoteFilesVersion: publishFileSyncEvents.remoteFilesVersion,\n changed: _.map(changed, \"path\"),\n deleted: _.map(deleted, \"path\"),\n },\n });\n\n if (BigInt(publishFileSyncEvents.remoteFilesVersion) > this.state.filesVersion) {\n this.state.filesVersion = publishFileSyncEvents.remoteFilesVersion;\n }\n\n this.log(chalkTemplate`Sent {gray ${format(new Date(), \"pp\")}}`);\n this.logPaths(\"→\", _.map(changed, \"path\"), _.map(deleted, \"path\"));\n });\n }, this.flags[\"file-push-delay\"]);\n\n this.watcher = new FSWatcher(this.dir, {\n // paths that we never want to publish\n ignore: /(\\.gadget|\\.git|node_modules)/,\n // don't emit an event for every watched file on boot\n ignoreInitial: true,\n renameDetection: true,\n recursive: true,\n debounce: this.flags[\"file-watch-debounce\"],\n pollingInterval: this.flags[\"file-watch-poll-interval\"],\n pollingTimeout: this.flags[\"file-watch-poll-timeout\"],\n renameTimeout: this.flags[\"file-watch-rename-timeout\"],\n });\n\n this.watcher.once(\"error\", (error) => void this.stop(error));\n\n this.watcher.on(\"all\", (event: string, absolutePath: string, renamedPath: string) => {\n const filepath = event === \"rename\" || event === \"renameDir\" ? renamedPath : absolutePath;\n const isDirectory = event === \"renameDir\" || event === \"addDir\" || event === \"unlinkDir\";\n const normalizedPath = this.normalize(filepath, isDirectory);\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\", normalizedPath);\n return;\n }\n\n let stats: Stats | undefined;\n try {\n stats = fs.statSync(filepath);\n } catch (error) {\n ignoreEnoent(error);\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.state.mtime) {\n this.state.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(\"%s %s\", event, normalizedPath);\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 case \"rename\":\n case \"renameDir\":\n assert(stats, \"missing stats on rename/renameDir event\");\n localFilesBuffer.set(normalizedPath, {\n oldPath: this.normalize(absolutePath, isDirectory),\n newPath: normalizedPath,\n isDirectory: event === \"renameDir\",\n mode: stats.mode,\n });\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(chalkTemplate`\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 as 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\n/**\n * Holds information about the state of the local filesystem. It's persisted to `.gadget/sync.json`.\n */\nexport class SyncState {\n private _inner: {\n app: string;\n filesVersion: string;\n mtime: number;\n };\n\n /**\n * Saves the current state of the filesystem to `.gadget/sync.json`.\n */\n #save = _.debounce(() => {\n fs.outputJSONSync(path.join(this._rootDir, \".gadget/sync.json\"), this._inner, { spaces: 2 });\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Saved sync state\",\n data: { state: this._inner },\n });\n }, 100);\n\n private constructor(\n private _rootDir: string,\n inner: { app: string; filesVersion: string; mtime: number },\n ) {\n this._inner = inner;\n }\n\n /**\n * The app this filesystem is synced to.\n */\n get app(): string {\n return this._inner.app;\n }\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 get filesVersion(): bigint {\n return BigInt(this._inner.filesVersion);\n }\n\n set filesVersion(value: bigint | string) {\n this._inner.filesVersion = String(value);\n this.#save();\n }\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 // eslint-disable-next-line @typescript-eslint/member-ordering\n get mtime(): number {\n return this._inner.mtime;\n }\n\n set mtime(value: number) {\n this._inner.mtime = value;\n this.#save();\n }\n\n /**\n * Creates a new SyncFile instance and saves it to the filesystem.\n *\n * @param rootDir The root directory of the app.\n * @param app The app slug.\n * @returns A new SyncFile instance.\n */\n static create(rootDir: string, opts: { app: string; filesVersion?: string; mtime?: number }): SyncState {\n const state = new SyncState(rootDir, { filesVersion: \"0\", mtime: 0, ...opts });\n state.#save();\n state.flush();\n return state;\n }\n\n /**\n * Loads a SyncFile instance from the filesystem.\n *\n * @param rootDir The root directory of the app.\n * @returns The SyncFile instance.\n */\n static load(rootDir: string): SyncState {\n const state = fs.readJsonSync(path.join(rootDir, \".gadget/sync.json\"));\n\n context.addBreadcrumb({\n category: \"sync\",\n message: \"Loaded sync state\",\n data: { state },\n });\n\n assert(_.isString(state.app), \"missing or invalid app\");\n assert(_.isString(state.filesVersion), \"missing or invalid filesVersion\");\n assert(_.isNumber(state.mtime), \"missing or invalid mtime\");\n\n return new SyncState(rootDir, {\n app: state.app,\n filesVersion: state.filesVersion,\n mtime: state.mtime,\n });\n }\n\n /**\n * Flushes any pending writes to the filesystem.\n */\n flush(): void {\n this.#save.flush();\n }\n\n /**\n * @returns The JSON representation of this instance.\n */\n toJSON() {\n return this._inner;\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"],"names":["Args","Flags","assert","chalkTemplate","format","execa","fs","inquirer","_","normalizePath","pMap","PQueue","path","pluralize","dedent","FSWatcher","which","FileSyncEncoding","BaseCommand","Client","context","InvalidSyncAppFlagError","InvalidSyncFileError","YarnNotFoundError","app","FSIgnorer","ignoreEnoent","isEmptyDir","walkDir","PromiseSignal","Sync","relative","to","dir","absolute","pathSegments","resolve","normalize","filepath","isDirectory","isAbsolute","softDelete","normalizedPath","move","overwrite","error","logPaths","prefix","changed","deleted","limit","lines","sortBy","map","line","slice","indexOf","logged","log","debugEnabled","length","init","config","windows","startsWith","args","directory","join","home","getApp","flags","state","selected","prompt","type","name","message","choices","getAvailableApps","then","apps","SyncState","create","load","force","setApp","client","ignorer","sync","nothrow","ensureDir","remoteFilesVersion","queryUnwrap","query","REMOTE_FILES_VERSION_QUERY","hasRemoteChanges","BigInt","filesVersion","getChangedFiles","files","Map","absolutePath","stats","stat","mtime","getTime","set","delete","changedFiles","hasLocalChanges","size","Array","from","keys","addBreadcrumb","category","data","action","Action","CANCEL","MERGE","RESET","PUBLISH_FILE_SYNC_EVENTS_MUTATION","variables","input","expectedRemoteFilesVersion","mode","content","readFile","encoding","Base64","process","exit","run","stopped","stop","e","status","SyncStatus","RUNNING","STOPPING","level","undefined","unsubscribe","watcher","removeAllListeners","publish","flush","queue","onIdle","Promise","allSettled","close","dispose","STOPPED","signal","on","setTimeout","once","unref","subscribeUnwrap","REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION","localFilesVersion","String","next","remoteFileSyncEvents","filter","event","ignores","_enqueue","Date","file","recentRemoteChanges","add","endsWith","split","dirname","writeFile","Buffer","cwd","catch","reload","localFilesBuffer","debounce","localFiles","entries","clear","push","oldPath","publishFileSyncEvents","ignore","ignoreInitial","renameDetection","recursive","pollingInterval","pollingTimeout","renameTimeout","renamedPath","debug","statSync","isDeleted","newPath","version","slug","hasSplitEnvironments","primaryDomain","notify","subtitle","fn","requireUser","STARTING","Set","concurrency","priority","summary","usage","description","string","default","boolean","integer","helpGroup","helpValue","hidden","examples","_inner","value","save","rootDir","opts","readJsonSync","isString","isNumber","toJ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UUS;uCAVTP,OAAO3N,EAAE+K,QAAQ,CAAC;YACjBjL,GAAGsO,cAAc,CAAChO,KAAKuD,IAAI,CAAC,IAAI,CAACuK,QAAQ,EAAE,sBAAsB,IAAI,CAACT,MAAM,EAAE;gBAAEY,QAAQ;YAAE;YAC1FzN,QAAQ8F,aAAa,CAAC;gBACpBC,UAAU;gBACVvC,SAAS;gBACTwC,MAAM;oBAAE7C,OAAO,IAAI,CAAC0J,MAAM;gBAAC;YAC7B;QACF,GAAG;QAMD,IAAI,CAACA,MAAM,GAAGU;IAChB;AA2FF;WAEO;UAAKjG,UAAU;IAAVA,WAAAA,WACVwE,cAAAA,KAAAA;IADUxE,WAAAA,WAEVC,aAAAA,KAAAA;IAFUD,WAAAA,WAGVE,cAAAA,KAAAA;IAHUF,WAAAA,WAIVgB,aAAAA,KAAAA;GAJUhB,eAAAA;WAOL;UAAKpB,MAAM;IAANA,OACVC,YAAS;IADCD,OAEVE,WAAQ;IAFEF,OAGVG,WAAQ;GAHEH,WAAAA;AAMZ,OAAO,MAAM2C,uCAGT,WAAW,GAAG,CAAC;;;;;;;;;;;;;;;AAenB,CAAC,CAAC;AAEF,OAAO,MAAMnE,6BAA+F,WAAW,GAAG,CAAC;;;;AAI3H,CAAC,CAAC;AAEF,OAAO,MAAM4B,oCAGT,WAAW,GAAG,CAAC;;;;;;AAMnB,CAAC,CAAC"}
@@ -1,8 +1,8 @@
1
1
  import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
2
  import chalkTemplate from "chalk-template";
3
3
  import { dedent } from "ts-dedent";
4
- import { BaseCommand } from "../utils/base-command.js";
5
- import { context } from "../utils/context.js";
4
+ import { BaseCommand } from "../services/base-command.js";
5
+ import { context } from "../services/context.js";
6
6
  class Whoami extends BaseCommand {
7
7
  async run() {
8
8
  const user = await context.getUser();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/whoami.ts"],"sourcesContent":["import chalkTemplate from \"chalk-template\";\nimport { dedent } from \"ts-dedent\";\nimport { BaseCommand } from \"../utils/base-command.js\";\nimport { context } from \"../utils/context.js\";\n\nexport default class Whoami extends BaseCommand<typeof Whoami> {\n static override summary = \"Show the name and email address of the currently logged in user.\";\n\n static override usage = \"whoami\";\n\n static override examples = [\n dedent(chalkTemplate`\n {gray $ ggt whoami}\n You are logged in as Jane Doe {gray (jane@example.com)}\n `),\n ];\n\n async run(): Promise<void> {\n const user = await context.getUser();\n if (!user) {\n this.log(\"You are not logged in\");\n return;\n }\n\n if (user.name) {\n this.log(chalkTemplate`You are logged in as ${user.name} {gray (${user.email})}`);\n } else {\n this.log(`You are logged in as ${user.email}`);\n }\n }\n}\n"],"names":["chalkTemplate","dedent","BaseCommand","context","Whoami","run","user","getUser","log","name","email","summary","usage","examples"],"mappings":";AAAA,OAAOA,mBAAmB,iBAAiB;AAC3C,SAASC,MAAM,QAAQ,YAAY;AACnC,SAASC,WAAW,QAAQ,2BAA2B;AACvD,SAASC,OAAO,QAAQ,sBAAsB;AAE/B,MAAMC,eAAeF;IAYlC,MAAMG,MAAqB;QACzB,MAAMC,OAAO,MAAMH,QAAQI;QAC3B,IAAI,CAACD,MAAM;YACT,IAAI,CAACE,IAAI;YACT;QACF;QAEA,IAAIF,KAAKG,MAAM;YACb,IAAI,CAACD,IAAIR,aAAa,CAAC,qBAAqB,EAAEM,KAAKG,KAAK,QAAQ,EAAEH,KAAKI,MAAM,EAAE,CAAC;QAClF,OAAO;YACL,IAAI,CAACF,IAAI,CAAC,qBAAqB,EAAEF,KAAKI,MAAM,CAAC;QAC/C;IACF;AACF;AAxBE,iBADmBN,QACHO,WAAU;AAE1B,iBAHmBP,QAGHQ,SAAQ;AAExB,iBALmBR,QAKHS,YAAW;IACzBZ,OAAOD,aAAa,CAAC;;;IAGrB,CAAC;CACF;AAVH,SAAqBI,oBAyBpB"}
1
+ {"version":3,"sources":["../../src/commands/whoami.ts"],"sourcesContent":["import chalkTemplate from \"chalk-template\";\nimport { dedent } from \"ts-dedent\";\nimport { BaseCommand } from \"../services/base-command.js\";\nimport { context } from \"../services/context.js\";\n\nexport default class Whoami extends BaseCommand<typeof Whoami> {\n static override summary = \"Show the name and email address of the currently logged in user.\";\n\n static override usage = \"whoami\";\n\n static override examples = [\n dedent(chalkTemplate`\n {gray $ ggt whoami}\n You are logged in as Jane Doe {gray (jane@example.com)}\n `),\n ];\n\n async run(): Promise<void> {\n const user = await context.getUser();\n if (!user) {\n this.log(\"You are not logged in\");\n return;\n }\n\n if (user.name) {\n this.log(chalkTemplate`You are logged in as ${user.name} {gray (${user.email})}`);\n } else {\n this.log(`You are logged in as ${user.email}`);\n }\n }\n}\n"],"names":["chalkTemplate","dedent","BaseCommand","context","Whoami","run","user","getUser","log","name","email","summary","usage","examples"],"mappings":";AAAA,OAAOA,mBAAmB,iBAAiB;AAC3C,SAASC,MAAM,QAAQ,YAAY;AACnC,SAASC,WAAW,QAAQ,8BAA8B;AAC1D,SAASC,OAAO,QAAQ,yBAAyB;AAElC,MAAMC,eAAeF;IAYlC,MAAMG,MAAqB;QACzB,MAAMC,OAAO,MAAMH,QAAQI,OAAO;QAClC,IAAI,CAACD,MAAM;YACT,IAAI,CAACE,GAAG,CAAC;YACT;QACF;QAEA,IAAIF,KAAKG,IAAI,EAAE;YACb,IAAI,CAACD,GAAG,CAACR,aAAa,CAAC,qBAAqB,EAAEM,KAAKG,IAAI,CAAC,QAAQ,EAAEH,KAAKI,KAAK,CAAC,EAAE,CAAC;QAClF,OAAO;YACL,IAAI,CAACF,GAAG,CAAC,CAAC,qBAAqB,EAAEF,KAAKI,KAAK,CAAC,CAAC;QAC/C;IACF;AACF;AAxBE,iBADmBN,QACHO,WAAU;AAE1B,iBAHmBP,QAGHQ,SAAQ;AAExB,iBALmBR,QAKHS,YAAW;IACzBZ,OAAOD,aAAa,CAAC;;;IAGrB,CAAC;CACF;AAVH,SAAqBI,oBAyBpB"}
@@ -2,11 +2,12 @@ import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
2
  import { Command, Flags, settings } from "@oclif/core";
3
3
  import { CLIError as CLIError2 } from "@oclif/core/lib/errors/index.js";
4
4
  import { CLIError, ExitError } from "@oclif/errors";
5
- import * as Sentry from "@sentry/node";
5
+ import { init as initSentry } from "@sentry/node";
6
6
  import chalkTemplate from "chalk-template";
7
7
  import Debug from "debug";
8
8
  import getPort from "get-port";
9
9
  import inquirer from "inquirer";
10
+ import _ from "lodash";
10
11
  import notifier from "node-notifier";
11
12
  import http from "node:http";
12
13
  import path from "node:path";
@@ -24,27 +25,32 @@ import { BaseError, UnexpectedError } from "./errors.js";
24
25
  }
25
26
  async init() {
26
27
  context.config = this.config;
27
- if (context.env.productionLike) {
28
- Sentry.init({
29
- dsn: "https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266",
30
- release: context.config.version
31
- });
32
- }
28
+ initSentry({
29
+ dsn: "https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266",
30
+ release: context.config.version,
31
+ enabled: context.env.productionLike && !_.includes([
32
+ "0",
33
+ "false",
34
+ "no",
35
+ "off"
36
+ ], _.toLower(_.trim(process.env["GGT_SENTRY_ENABLED"])))
37
+ });
33
38
  await super.init();
34
39
  if (this.requireUser && !await context.getUser()) {
35
40
  // we purposely log the user in before parsing flags in case one of the flags requires the user to be logged in
36
41
  // e.g. the `--app` flag verifies that the user has access to the app they are trying to use
37
- const { login } = await inquirer.prompt({
42
+ const { login } = await inquirer.prompt({
38
43
  type: "confirm",
39
44
  name: "login",
40
45
  message: "You must be logged in to use this command. Would you like to log in?"
41
46
  });
42
47
  if (!login) {
43
- return this.exit(0);
48
+ this.exit(0);
49
+ return;
44
50
  }
45
51
  await this.login();
46
52
  }
47
- const { flags , args } = await this.parse({
53
+ const { flags, args } = await this.parse({
48
54
  flags: this.ctor.flags,
49
55
  baseFlags: super.ctor.baseFlags,
50
56
  args: this.ctor.args,
@@ -56,6 +62,15 @@ import { BaseError, UnexpectedError } from "./errors.js";
56
62
  settings.debug = true;
57
63
  Debug.enable(`${this.config.bin}:*`);
58
64
  }
65
+ context.addBreadcrumb({
66
+ category: "command",
67
+ message: "Initialized",
68
+ data: {
69
+ command: this.id,
70
+ flags: this.flags,
71
+ args: this.args
72
+ }
73
+ });
59
74
  }
60
75
  /**
61
76
  * Sends a native OS notification to the user.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/services/base-command.ts"],"sourcesContent":["import type { Config, Interfaces } from \"@oclif/core\";\nimport { Command, Flags, settings } from \"@oclif/core\";\nimport { CLIError as CLIError2 } from \"@oclif/core/lib/errors/index.js\";\nimport { CLIError, ExitError } from \"@oclif/errors\";\nimport { init as initSentry } from \"@sentry/node\";\nimport chalkTemplate from \"chalk-template\";\nimport Debug from \"debug\";\nimport getPort from \"get-port\";\nimport inquirer from \"inquirer\";\nimport _ from \"lodash\";\nimport type { Notification } from \"node-notifier\";\nimport notifier from \"node-notifier\";\nimport type WindowsBalloon from \"node-notifier/notifiers/balloon.js\";\nimport type Growl from \"node-notifier/notifiers/growl.js\";\nimport type NotificationCenter from \"node-notifier/notifiers/notificationcenter.js\";\nimport type NotifySend from \"node-notifier/notifiers/notifysend.js\";\nimport type WindowsToaster from \"node-notifier/notifiers/toaster.js\";\nimport type { Server } from \"node:http\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport open from \"open\";\nimport { dedent } from \"ts-dedent\";\nimport { context } from \"./context.js\";\nimport { BaseError, UnexpectedError } from \"./errors.js\";\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 initSentry({\n dsn: \"https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266\",\n release: context.config.version,\n enabled: context.env.productionLike && !_.includes([\"0\", \"false\", \"no\", \"off\"], _.toLower(_.trim(process.env[\"GGT_SENTRY_ENABLED\"]))),\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 inquirer.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 this.exit(0);\n return;\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 context.addBreadcrumb({\n category: \"command\",\n message: \"Initialized\",\n data: {\n command: this.id,\n flags: this.flags,\n args: this.args,\n },\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 notifier.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 = http.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(chalkTemplate`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"],"names":["Command","Flags","settings","CLIError","CLIError2","ExitError","init","initSentry","chalkTemplate","Debug","getPort","inquirer","_","notifier","http","path","open","dedent","context","BaseError","UnexpectedError","BaseCommand","debugEnabled","debug","config","dsn","release","version","enabled","env","productionLike","includes","toLower","trim","process","requireUser","getUser","login","prompt","type","name","message","exit","flags","args","parse","ctor","baseFlags","strict","enable","bin","addBreadcrumb","category","data","command","id","notify","notification","title","contentImage","join","root","icon","sound","timeout","error","warn","server","port","receiveSession","Promise","resolve","reject","createServer","req","res","redirectTo","URL","domains","services","url","Error","incomingUrl","value","searchParams","get","session","user","log","email","set","undefined","writeHead","Location","toString","end","listen","close","catch","cause","console","render","capture","constructor","argv","priority","Infinity","boolean","char","summary","helpGroup","default"],"mappings":";AACA,SAASA,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;QACnBC,MAAM;QACNC,SAAS;QACTC,WAAW;QACXC,SAAS;IACX;AACF"}
@@ -1,12 +1,10 @@
1
1
  import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
2
  import assert from "assert";
3
- import Debug from "debug";
4
3
  import { createClient } from "graphql-ws";
5
4
  import _ from "lodash";
6
5
  import WebSocket from "ws";
7
6
  import { context } from "./context.js";
8
7
  import { ClientError } from "./errors.js";
9
- const debug = Debug("ggt:client");
10
8
  var ConnectionStatus;
11
9
  (function(ConnectionStatus) {
12
10
  ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED";
@@ -21,7 +19,7 @@ var ConnectionStatus;
21
19
  */ export class Client {
22
20
  subscribe(payload, sink) {
23
21
  let subscribePayload;
24
- let removeConnectedListener;
22
+ let removeConnectedListener = _.noop.bind(_);
25
23
  if (_.isFunction(payload.variables)) {
26
24
  // the caller wants us to re-evaluate the variables every time graphql-ws re-subscribes after reconnecting
27
25
  subscribePayload = {
@@ -32,20 +30,40 @@ var ConnectionStatus;
32
30
  if (this.status == ConnectionStatus.RECONNECTING) {
33
31
  // subscribePayload.variables is supposed to be readonly (it's not) and payload.variables may have been re-assigned (it won't)
34
32
  subscribePayload.variables = payload.variables();
35
- debug("re-sending %s%s%O", subscribePayload.query.split(/\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);
33
+ context.addBreadcrumb({
34
+ category: "client",
35
+ message: "Re-sending GraphQL query",
36
+ data: {
37
+ type: _.split(subscribePayload.query, /\s+/g, 1)[0],
38
+ query: subscribePayload.query
39
+ }
40
+ });
36
41
  }
37
42
  });
38
43
  } else {
39
44
  subscribePayload = payload;
40
45
  }
41
- debug("sending %s%s%O", subscribePayload.query.split(/\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);
46
+ context.addBreadcrumb({
47
+ category: "client",
48
+ message: "Sending GraphQL query",
49
+ data: {
50
+ type: _.split(subscribePayload.query, /\s+/g, 1)[0],
51
+ query: subscribePayload.query
52
+ }
53
+ });
42
54
  const unsubscribe = this._client.subscribe(subscribePayload, {
43
- next: (result)=>sink.next(result),
44
- error: (error)=>sink.error(new ClientError(subscribePayload, error)),
45
- complete: ()=>sink.complete?.()
55
+ next: (result)=>{
56
+ sink.next(result);
57
+ },
58
+ error: (error)=>{
59
+ sink.error(new ClientError(subscribePayload, error));
60
+ },
61
+ complete: ()=>{
62
+ sink.complete?.();
63
+ }
46
64
  });
47
65
  return ()=>{
48
- removeConnectedListener?.();
66
+ removeConnectedListener();
49
67
  unsubscribe();
50
68
  };
51
69
  }
@@ -92,7 +110,7 @@ var ConnectionStatus;
92
110
  assert(context.app, "context.app must be set before instantiating the Client");
93
111
  this._client = createClient({
94
112
  url: `wss://${context.app.slug}.${context.domains.app}/edit/api/graphql-ws`,
95
- shouldRetry: ()=>true,
113
+ shouldRetry: _.constant(true),
96
114
  webSocketImpl: class extends WebSocket {
97
115
  constructor(address, protocols, wsOptions){
98
116
  assert(context.session, "context.session must be set before instantiating the Client");
@@ -111,21 +129,36 @@ var ConnectionStatus;
111
129
  switch(this.status){
112
130
  case ConnectionStatus.DISCONNECTED:
113
131
  this.status = ConnectionStatus.RECONNECTING;
114
- debug("reconnecting...");
132
+ context.addBreadcrumb({
133
+ category: "client",
134
+ message: "Reconnecting"
135
+ });
115
136
  break;
116
137
  case ConnectionStatus.RECONNECTING:
117
- debug("retrying...");
138
+ context.addBreadcrumb({
139
+ category: "client",
140
+ message: "Retrying"
141
+ });
118
142
  break;
119
143
  default:
120
- debug("connecting...");
144
+ context.addBreadcrumb({
145
+ category: "client",
146
+ message: "Connecting"
147
+ });
121
148
  break;
122
149
  }
123
150
  },
124
151
  connected: ()=>{
125
152
  if (this.status === ConnectionStatus.RECONNECTING) {
126
- debug("reconnected");
153
+ context.addBreadcrumb({
154
+ category: "client",
155
+ message: "Reconnected"
156
+ });
127
157
  } else {
128
- debug("connected");
158
+ context.addBreadcrumb({
159
+ category: "client",
160
+ message: "Connected"
161
+ });
129
162
  }
130
163
  // let the other on connected listeners see what status we're in
131
164
  setImmediate(()=>this.status = ConnectionStatus.CONNECTED);
@@ -133,22 +166,38 @@ var ConnectionStatus;
133
166
  closed: (e)=>{
134
167
  const event = e;
135
168
  if (event.wasClean) {
136
- debug("connection closed");
169
+ context.addBreadcrumb({
170
+ category: "client",
171
+ message: "Connection Closed"
172
+ });
137
173
  return;
138
174
  }
139
175
  if (this.status === ConnectionStatus.CONNECTED) {
140
176
  this.status = ConnectionStatus.DISCONNECTED;
141
- debug("disconnected");
177
+ context.addBreadcrumb({
178
+ category: "client",
179
+ message: "Disconnected"
180
+ });
142
181
  }
143
182
  },
144
183
  error: (error)=>{
145
184
  if (this.status == ConnectionStatus.RECONNECTING) {
146
- debug("failed to reconnect %o", {
147
- error
185
+ context.addBreadcrumb({
186
+ category: "client",
187
+ message: "Failed to reconnect",
188
+ level: "error",
189
+ data: {
190
+ error
191
+ }
148
192
  });
149
193
  } else {
150
- debug("connection error %o", {
151
- error
194
+ context.addBreadcrumb({
195
+ category: "client",
196
+ message: "Connection error",
197
+ level: "error",
198
+ data: {
199
+ error
200
+ }
152
201
  });
153
202
  }
154
203
  }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/services/client.ts"],"sourcesContent":["import assert from \"assert\";\nimport type { GraphQLError } from \"graphql\";\nimport type { ExecutionResult, SubscribePayload } from \"graphql-ws\";\nimport { createClient } from \"graphql-ws\";\nimport type { ClientRequestArgs } from \"http\";\nimport _ from \"lodash\";\nimport type { JsonObject, SetOptional } from \"type-fest\";\nimport type { CloseEvent, ErrorEvent } from \"ws\";\nimport WebSocket from \"ws\";\nimport { context } from \"./context.js\";\nimport { ClientError } from \"./errors.js\";\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: _.constant(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 context.addBreadcrumb({ category: \"client\", message: \"Reconnecting\" });\n break;\n case ConnectionStatus.RECONNECTING:\n context.addBreadcrumb({ category: \"client\", message: \"Retrying\" });\n break;\n default:\n context.addBreadcrumb({ category: \"client\", message: \"Connecting\" });\n break;\n }\n },\n connected: () => {\n if (this.status === ConnectionStatus.RECONNECTING) {\n context.addBreadcrumb({ category: \"client\", message: \"Reconnected\" });\n } else {\n context.addBreadcrumb({ category: \"client\", message: \"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 context.addBreadcrumb({ category: \"client\", message: \"Connection Closed\" });\n return;\n }\n\n if (this.status === ConnectionStatus.CONNECTED) {\n this.status = ConnectionStatus.DISCONNECTED;\n context.addBreadcrumb({ category: \"client\", message: \"Disconnected\" });\n }\n },\n error: (error) => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n context.addBreadcrumb({ category: \"client\", message: \"Failed to reconnect\", level: \"error\", data: { error } });\n } else {\n context.addBreadcrumb({ category: \"client\", message: \"Connection error\", level: \"error\", data: { 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 = _.noop.bind(_);\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 context.addBreadcrumb({\n category: \"client\",\n message: \"Re-sending GraphQL query\",\n data: {\n type: _.split(subscribePayload.query, /\\s+/g, 1)[0],\n query: subscribePayload.query,\n },\n });\n }\n });\n } else {\n subscribePayload = payload as SubscribePayload;\n }\n\n context.addBreadcrumb({\n category: \"client\",\n message: \"Sending GraphQL query\",\n data: {\n type: _.split(subscribePayload.query, /\\s+/g, 1)[0],\n query: subscribePayload.query,\n },\n });\n\n const unsubscribe = this._client.subscribe(subscribePayload, {\n next: (result: ExecutionResult<Data, Extensions>) => {\n sink.next(result);\n },\n error: (error) => {\n sink.error(new ClientError(subscribePayload, error as Error | GraphQLError[] | CloseEvent | ErrorEvent));\n },\n complete: () => {\n sink.complete?.();\n },\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"],"names":["assert","createClient","_","WebSocket","context","ClientError","ConnectionStatus","CONNECTED","DISCONNECTED","RECONNECTING","Client","subscribe","payload","sink","subscribePayload","removeConnectedListener","noop","bind","isFunction","variables","_client","on","status","addBreadcrumb","category","message","data","type","split","query","unsubscribe","next","result","error","complete","subscribeUnwrap","errors","Promise","resolve","reject","queryUnwrap","dispose","constructor","app","url","slug","domains","shouldRetry","constant","webSocketImpl","address","protocols","wsOptions","session","headers","config","userAgent","cookie","encodeURIComponent","connecting","connected","setImmediate","closed","e","event","wasClean","level"],"mappings":";AAAA,OAAOA,YAAY,SAAS;AAG5B,SAASC,YAAY,QAAQ,aAAa;AAE1C,OAAOC,OAAO,SAAS;AAGvB,OAAOC,eAAe,KAAK;AAC3B,SAASC,OAAO,QAAQ,eAAe;AACvC,SAASC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