@gadgetinc/ggt 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -94,6 +94,7 @@ DESCRIPTION
94
94
  - .gadget
95
95
  - .git
96
96
  - node_modules
97
+ - .DS_Store
97
98
 
98
99
  Note:
99
100
  - If you have separate development and production environments, ggt sync will only sync with your development environment
@@ -129,7 +130,7 @@ EXAMPLES
129
130
  Goodbye!
130
131
  ```
131
132
 
132
- _See code: [src/commands/sync.ts](https://github.com/gadget-inc/ggt/blob/v0.2.3/src/commands/sync.ts)_
133
+ _See code: [src/commands/sync.ts](https://github.com/gadget-inc/ggt/blob/v0.2.4/src/commands/sync.ts)_
133
134
 
134
135
  ### `ggt help [COMMAND]`
135
136
 
@@ -143,7 +144,7 @@ ARGUMENTS
143
144
  COMMAND The command to show help for.
144
145
  ```
145
146
 
146
- _See code: [src/commands/help.ts](https://github.com/gadget-inc/ggt/blob/v0.2.3/src/commands/help.ts)_
147
+ _See code: [src/commands/help.ts](https://github.com/gadget-inc/ggt/blob/v0.2.4/src/commands/help.ts)_
147
148
 
148
149
  ### `ggt list`
149
150
 
@@ -170,7 +171,7 @@ EXAMPLES
170
171
  $ ggt list --sort=slug
171
172
  ```
172
173
 
173
- _See code: [src/commands/list.ts](https://github.com/gadget-inc/ggt/blob/v0.2.3/src/commands/list.ts)_
174
+ _See code: [src/commands/list.ts](https://github.com/gadget-inc/ggt/blob/v0.2.4/src/commands/list.ts)_
174
175
 
175
176
  ### `ggt login`
176
177
 
@@ -189,7 +190,7 @@ EXAMPLES
189
190
  Hello, Jane Doe (jane@example.com)
190
191
  ```
191
192
 
192
- _See code: [src/commands/login.ts](https://github.com/gadget-inc/ggt/blob/v0.2.3/src/commands/login.ts)_
193
+ _See code: [src/commands/login.ts](https://github.com/gadget-inc/ggt/blob/v0.2.4/src/commands/login.ts)_
193
194
 
194
195
  ### `ggt logout`
195
196
 
@@ -204,7 +205,7 @@ EXAMPLES
204
205
  Goodbye
205
206
  ```
206
207
 
207
- _See code: [src/commands/logout.ts](https://github.com/gadget-inc/ggt/blob/v0.2.3/src/commands/logout.ts)_
208
+ _See code: [src/commands/logout.ts](https://github.com/gadget-inc/ggt/blob/v0.2.4/src/commands/logout.ts)_
208
209
 
209
210
  ### `ggt whoami`
210
211
 
@@ -219,7 +220,7 @@ EXAMPLES
219
220
  You are logged in as Jane Doe (jane@example.com)
220
221
  ```
221
222
 
222
- _See code: [src/commands/whoami.ts](https://github.com/gadget-inc/ggt/blob/v0.2.3/src/commands/whoami.ts)_
223
+ _See code: [src/commands/whoami.ts](https://github.com/gadget-inc/ggt/blob/v0.2.4/src/commands/whoami.ts)_
223
224
 
224
225
  <!-- commandsstop -->
225
226
 
@@ -137,7 +137,8 @@ class Sync extends BaseCommand {
137
137
  this.ignorer = new FSIgnorer(this.dir, [
138
138
  "node_modules",
139
139
  ".gadget",
140
- ".git"
140
+ ".git",
141
+ ".DS_Store"
141
142
  ]);
142
143
  if (!which.sync("yarn", {
143
144
  nothrow: true
@@ -511,7 +512,7 @@ class Sync extends BaseCommand {
511
512
  }, this.flags["file-push-delay"]);
512
513
  this.watcher = new FSWatcher(this.dir, {
513
514
  // paths that we never want to publish
514
- ignore: /(\.gadget|\.git|node_modules)/,
515
+ ignore: /(\.gadget|\.git|node_modules|\.DS_Store)/,
515
516
  // don't emit an event for every watched file on boot
516
517
  ignoreInitial: true,
517
518
  renameDetection: true,
@@ -681,6 +682,7 @@ _define_property(Sync, "description", dedent(chalkTemplate`
681
682
  - .gadget
682
683
  - .git
683
684
  - node_modules
685
+ - .DS_Store
684
686
 
685
687
  Note:
686
688
  - If you have separate development and production environments, {gray ggt sync} will only sync with your development environment
@@ -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 { 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 if (BigInt(publishFileSyncEvents.remoteFilesVersion) > this.state.filesVersion) {\n this.state.filesVersion = publishFileSyncEvents.remoteFilesVersion;\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 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 = dedent(/* 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`) as Query<RemoteFileSyncEventsSubscription, RemoteFileSyncEventsSubscriptionVariables>;\n\nexport const REMOTE_FILES_VERSION_QUERY = dedent(/* GraphQL */ `\n query RemoteFilesVersion {\n remoteFilesVersion\n }\n`) as Query<RemoteFilesVersionQuery, RemoteFilesVersionQueryVariables>;\n\nexport const PUBLISH_FILE_SYNC_EVENTS_MUTATION = dedent(/* GraphQL */ `\n mutation PublishFileSyncEvents($input: PublishFileSyncEventsInput!) {\n publishFileSyncEvents(input: $input) {\n remoteFilesVersion\n }\n }\n`) as Query<PublishFileSyncEventsMutation, PublishFileSyncEventsMutationVariables>;\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","toJSON","_rootDir","inner","outputJSONSync","spaces"],"mappings":";;;;AAAA,SAASA,IAAI,EAAEC,KAAK,QAAQ,cAAc;AAC1C,OAAOC,YAAY,SAAS;AAC5B,OAAOC,mBAAmB,iBAAiB;AAC3C,SAASC,MAAM,QAAQ,WAAW;AAClC,SAASC,KAAK,QAAQ,QAAQ;AAE9B,OAAOC,QAAQ,WAAW;AAC1B,OAAOC,cAAc,WAAW;AAChC,OAAOC,OAAO,SAAS;AACvB,OAAOC,mBAAmB,iBAAiB;AAC3C,OAAOC,UAAU,QAAQ;AACzB,OAAOC,YAAY,UAAU;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,eAAe,YAAY;AAClC,SAASC,MAAM,QAAQ,YAAY;AACnC,OAAOC,eAAe,UAAU;AAChC,OAAOC,WAAW,QAAQ;AAW1B,SAASC,gBAAgB,QAAQ,8BAA8B;AAC/D,SAASC,WAAW,QAAQ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,YAAS;IADCD,OAEVE,WAAQ;IAFEF,OAGVG,WAAQ;GAHEH,WAAAA;AAMZ,OAAO,MAAM2C,uCAAuCnJ,OAAO,WAAW,GAAG,CAAC;;;;;;;;;;;;;;;AAe1E,CAAC,EAAwF;AAEzF,OAAO,MAAMgF,6BAA6BhF,OAAO,WAAW,GAAG,CAAC;;;;AAIhE,CAAC,EAAsE;AAEvE,OAAO,MAAM4G,oCAAoC5G,OAAO,WAAW,GAAG,CAAC;;;;;;AAMvE,CAAC,EAAkF"}
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 - .DS_Store\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\", \".DS_Store\"]);\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 if (BigInt(publishFileSyncEvents.remoteFilesVersion) > this.state.filesVersion) {\n this.state.filesVersion = publishFileSyncEvents.remoteFilesVersion;\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 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|\\.DS_Store)/,\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 = dedent(/* 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`) as Query<RemoteFileSyncEventsSubscription, RemoteFileSyncEventsSubscriptionVariables>;\n\nexport const REMOTE_FILES_VERSION_QUERY = dedent(/* GraphQL */ `\n query RemoteFilesVersion {\n remoteFilesVersion\n }\n`) as Query<RemoteFilesVersionQuery, RemoteFilesVersionQueryVariables>;\n\nexport const PUBLISH_FILE_SYNC_EVENTS_MUTATION = dedent(/* GraphQL */ `\n mutation PublishFileSyncEvents($input: PublishFileSyncEventsInput!) {\n publishFileSyncEvents(input: $input) {\n remoteFilesVersion\n }\n }\n`) as Query<PublishFileSyncEventsMutation, PublishFileSyncEventsMutationVariables>;\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","toJSON","_rootDir","inner","outputJSONSync","spaces"],"mappings":";;;;AAAA,SAASA,IAAI,EAAEC,KAAK,QAAQ,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