@gadgetinc/ggt 0.4.4 → 0.4.5
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 +1 -1
- package/lib/commands/deploy.js +2 -4
- package/lib/commands/deploy.js.map +1 -1
- package/lib/services/filesync/filesync.js +35 -33
- package/lib/services/filesync/filesync.js.map +1 -1
- package/lib/services/filesync/hashes.js +2 -2
- package/lib/services/filesync/hashes.js.map +1 -1
- package/lib/services/output/log/format/pretty.js +4 -1
- package/lib/services/output/log/format/pretty.js.map +1 -1
- package/npm-shrinkwrap.json +946 -205
- package/package.json +5 -5
package/README.md
CHANGED
package/lib/commands/deploy.js
CHANGED
|
@@ -3,7 +3,6 @@ import ora from "ora";
|
|
|
3
3
|
import { AppArg } from "../services/app/arg.js";
|
|
4
4
|
import { REMOTE_SERVER_CONTRACT_STATUS_SUBSCRIPTION } from "../services/app/edit-graphql.js";
|
|
5
5
|
import { FileSync } from "../services/filesync/filesync.js";
|
|
6
|
-
import { isEqualHashes } from "../services/filesync/hashes.js";
|
|
7
6
|
import { select } from "../services/output/prompt.js";
|
|
8
7
|
import { sprint } from "../services/output/sprint.js";
|
|
9
8
|
import { getUserOrLogin } from "../services/user/user.js";
|
|
@@ -120,9 +119,8 @@ var AppDeploymentSteps;
|
|
|
120
119
|
if (firstRun) {
|
|
121
120
|
log.printlns`App: ${filesync.app.slug}`;
|
|
122
121
|
}
|
|
123
|
-
const {
|
|
124
|
-
|
|
125
|
-
if (!upToDate) {
|
|
122
|
+
const { inSync } = await filesync.hashes();
|
|
123
|
+
if (!inSync) {
|
|
126
124
|
log.printlns`
|
|
127
125
|
Local files have diverged from remote. Run a sync once to converge your files or keep {italic ggt sync} running in the background.
|
|
128
126
|
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/deploy.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { AppArg } from \"../services/app/arg.js\";\nimport { REMOTE_SERVER_CONTRACT_STATUS_SUBSCRIPTION } from \"../services/app/edit-graphql.js\";\nimport type { ArgsSpec } from \"../services/command/arg.js\";\nimport { type Command, type Usage } from \"../services/command/command.js\";\nimport { FileSync } from \"../services/filesync/filesync.js\";\nimport { isEqualHashes } from \"../services/filesync/hashes.js\";\nimport { select } from \"../services/output/prompt.js\";\nimport { sprint } from \"../services/output/sprint.js\";\nimport { getUserOrLogin } from \"../services/user/user.js\";\nimport { isCloseEvent, isGraphQLErrors } from \"../services/util/is.js\";\n\nexport const usage: Usage = () => sprint`\n Deploy your Gadget application's development source code to production.\n\n {bold USAGE}\n ggt deploy [DIRECTORY] [--app=<name>]\n\n {bold ARGUMENTS}\n DIRECTORY The directory to sync files to and deploy (default: \".\")\n\n {bold FLAGS}\n -a, --app=<name> The Gadget application to deploy\n --force Deploy the Gadget application regardless of any issues it may have\n\n {bold DESCRIPTION}\n Deploy allows you to deploy your current Gadget application in development to production.\n \n It detects if local files are up to date with remote and if the Gadget application \n is in a deployable state. If there are any issues, it will display them and ask if \n you would like to deploy anyways. \n \n Note:\n • If local files are not up to date or have not recently been synced with remote ones,\n you will be prompted to run a one-time sync to ensure the files remain consistent with \n what is on the remote. \n • You may wish to keep ggt sync running in the background before trying to run ggt deploy\n \n {bold EXAMPLE} \n $ ggt deploy ~/gadget/example --app example\n \n App example\n Editor https://example.gadget.app/edit\n Playground https://example.gadget.app/api/graphql/playground\n Docs https://docs.gadget.dev/api/example\n\n Endpoints\n • https://example.gadget.app\n • https://example--development.gadget.app\n \n \n Building frontend assets ...\n ✔ DONE\n \n Setting up database ...\n ✔ DONE\n \n Copying development ...\n ✔ DONE\n \n Restarting app ...\n ✔ DONE\n \n Deploy completed. Good bye!\n`;\n\nexport const args = {\n \"--app\": {\n type: AppArg,\n alias: \"-a\",\n },\n \"--force\": Boolean,\n} satisfies ArgsSpec;\n\nexport enum Action {\n DEPLOY_ANYWAYS = \"Deploy anyways\",\n SYNC_ONCE = \"Sync once\",\n CANCEL = \"Cancel (Ctrl+C)\",\n}\n\nconst AppDeploymentStepsToAppDeployState = (step: string | undefined): string => {\n switch (step) {\n case \"NOT_STARTED\":\n return \"Deploy not started\";\n case \"STARTING\":\n case \"BUILDING_ASSETS\":\n case \"UPLOADING_ASSETS\":\n return \"Building frontend assets\";\n case \"CONVERGING_STORAGE\":\n return \"Setting up database\";\n case \"PUBLISHING_TREE\":\n return \"Copying development\";\n case \"RELOADING_SANDBOX\":\n return \"Restarting app\";\n case \"COMPLETED\":\n return \"Deploy completed\";\n default:\n return \"Unknown step\";\n }\n};\n\nenum AppDeploymentSteps {\n NOT_STARTED = \"NOT_STARTED\",\n STARTING = \"STARTING\",\n BUILDING_ASSETS = \"BUILDING_ASSETS\",\n UPLOADING_ASSETS = \"UPLOADING_ASSETS\",\n CONVERGING_STORAGE = \"CONVERGING_STORAGE\",\n PUBLISHING_TREE = \"PUBLISHING_TREE\",\n RELOADING_SANDBOX = \"RELOADING_SANDBOX\",\n COMPLETED = \"COMPLETED\",\n}\n\n/**\n * Runs the deploy process.\n */\n\nexport const command = (async (ctx, firstRun = true) => {\n const spinner = ora();\n let prevProgress: string | undefined = AppDeploymentStepsToAppDeployState(\"NOT_STARTED\");\n let action: Action;\n\n const filesync = await FileSync.init({\n user: await getUserOrLogin(),\n dir: ctx.args._[0],\n app: ctx.args[\"--app\"],\n });\n\n const log = filesync.log.extend(\"deploy\");\n\n if (firstRun) {\n log.printlns`App: ${filesync.app.slug}`;\n }\n\n const { localHashes, gadgetHashes } = await filesync._getHashes();\n\n const upToDate = isEqualHashes(localHashes, gadgetHashes);\n\n if (!upToDate) {\n log.printlns`\n Local files have diverged from remote. Run a sync once to converge your files or keep {italic ggt sync} running in the background.\n `;\n\n action = await select({\n message: \"How would you like to proceed?\",\n choices: [Action.CANCEL, Action.SYNC_ONCE],\n });\n\n switch (action) {\n case Action.SYNC_ONCE: {\n await filesync.sync();\n\n break;\n }\n case Action.CANCEL: {\n process.exit(0);\n }\n }\n }\n\n // subscribes to the graphql subscription that will listen and send back the server contract status\n const unsubscribe = filesync.editGraphQL.subscribe({\n query: REMOTE_SERVER_CONTRACT_STATUS_SUBSCRIPTION,\n variables: () => ({ localFilesVersion: String(filesync.filesVersion), force: ctx.args[\"--force\"] }),\n onError: (error) => {\n if (isCloseEvent(error.cause)) {\n spinner.fail(\"Failed\");\n log.printlns(error.message);\n } else if (isGraphQLErrors(error.cause)) {\n const message = error.cause[0]?.message;\n if (message && message.includes(\"GGT_PAYMENT_REQUIRED\")) {\n log.println(\"Production environment limit reached. Upgrade your plan to deploy\");\n } else {\n log.println(`${message}`);\n }\n }\n log.error(\"failed to deploy\", { error });\n unsubscribe();\n return;\n },\n onData: async ({ publishStatus }): Promise<void> => {\n const { progress, issues } = publishStatus ?? {};\n\n const hasIssues = issues?.length;\n\n if (firstRun && hasIssues) {\n log.printlns`{underline Issues detected}`;\n\n for (const issue of issues) {\n const message = issue.message.replace(/\"/g, \"\");\n const nodeType = issue.node?.type;\n const nodeName = issue.node?.name;\n const nodeParent = issue.node?.parentApiIdentifier;\n\n log.printlns(\n `\n • ${message} \n ${nodeType ? `${nodeType}: ${chalk.cyan(nodeName)}` : \"\"} ${\n nodeParent ? `ParentResource: ${chalk.cyan(nodeParent)}` : \"\"\n }\n `.trim(),\n );\n }\n\n if (!ctx.args[\"--force\"]) {\n unsubscribe();\n\n action = await select({\n message: \"Detected some issues with your app. How would you like to proceed?\",\n choices: [Action.CANCEL, Action.DEPLOY_ANYWAYS],\n });\n\n switch (action) {\n case Action.DEPLOY_ANYWAYS: {\n ctx.args[\"--force\"] = true;\n await command(ctx, false);\n break;\n }\n case Action.CANCEL: {\n process.exit(0);\n }\n }\n }\n\n firstRun = false;\n } else {\n if (progress === AppDeploymentSteps.COMPLETED) {\n spinner.succeed(\"DONE\");\n log.printlns(\"Deploy completed. Good bye!\");\n unsubscribe();\n return;\n }\n\n const currentProgress = AppDeploymentStepsToAppDeployState(progress);\n\n if (progress && currentProgress !== prevProgress) {\n if ((progress as AppDeploymentSteps) !== AppDeploymentSteps.STARTING) {\n spinner.succeed(\"DONE\");\n }\n\n prevProgress = currentProgress;\n log.printlns(`${currentProgress} ...`);\n spinner.start(\"Working ...\");\n }\n }\n },\n });\n}) satisfies Command<typeof args>;\n"],"names":["chalk","ora","AppArg","REMOTE_SERVER_CONTRACT_STATUS_SUBSCRIPTION","FileSync","isEqualHashes","select","sprint","getUserOrLogin","isCloseEvent","isGraphQLErrors","usage","args","type","alias","Boolean","Action","AppDeploymentStepsToAppDeployState","step","AppDeploymentSteps","command","ctx","firstRun","spinner","prevProgress","action","filesync","init","user","dir","_","app","log","extend","printlns","slug","localHashes","gadgetHashes","_getHashes","upToDate","message","choices","sync","process","exit","unsubscribe","editGraphQL","subscribe","query","variables","localFilesVersion","String","filesVersion","force","onError","error","cause","fail","includes","println","onData","publishStatus","progress","issues","hasIssues","length","issue","replace","nodeType","node","nodeName","name","nodeParent","parentApiIdentifier","cyan","trim","succeed","currentProgress","start"],"mappings":"AAAA,OAAOA,WAAW,QAAQ;AAC1B,OAAOC,SAAS,MAAM;AACtB,SAASC,MAAM,QAAQ,yBAAyB;AAChD,SAASC,0CAA0C,QAAQ,kCAAkC;AAG7F,SAASC,QAAQ,QAAQ,mCAAmC;AAC5D,SAASC,aAAa,QAAQ,iCAAiC;AAC/D,SAASC,MAAM,QAAQ,+BAA+B;AACtD,SAASC,MAAM,QAAQ,+BAA+B;AACtD,SAASC,cAAc,QAAQ,2BAA2B;AAC1D,SAASC,YAAY,EAAEC,eAAe,QAAQ,yBAAyB;AAEvE,OAAO,MAAMC,QAAe,IAAMJ,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDzC,CAAC,CAAC;AAEF,OAAO,MAAMK,OAAO;IAClB,SAAS;QACPC,MAAMX;QACNY,OAAO;IACT;IACA,WAAWC;AACb,EAAqB;;UAETC;;;;GAAAA,WAAAA;AAMZ,MA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V;gBAEA,IAAI,CAACtD,IAAIT,IAAI,CAAC,UAAU,EAAE;oBACxBiC;oBAEApB,SAAS,MAAMnB,OAAO;wBACpBkC,SAAS;wBACTC,SAAS;;;yBAAsC;oBACjD;oBAEA,OAAQhB;wBACN;4BAA4B;gCAC1BJ,IAAIT,IAAI,CAAC,UAAU,GAAG;gCACtB,MAAMQ,QAAQC,KAAK;gCACnB;4BACF;wBACA;4BAAoB;gCAClBsB,QAAQC,IAAI,CAAC;4BACf;oBACF;gBACF;gBAEAtB,WAAW;YACb,OAAO;gBACL,IAAIwC,0BAA2C;oBAC7CvC,QAAQqD,OAAO,CAAC;oBAChB5C,IAAIE,QAAQ,CAAC;oBACbW;oBACA;gBACF;gBAEA,MAAMgC,kBAAkB5D,mCAAmC6C;gBAE3D,IAAIA,YAAYe,oBAAoBrD,cAAc;oBAChD,IAAI,AAACsC,yBAAiE;wBACpEvC,QAAQqD,OAAO,CAAC;oBAClB;oBAEApD,eAAeqD;oBACf7C,IAAIE,QAAQ,CAAC,CAAC,EAAE2C,gBAAgB,IAAI,CAAC;oBACrCtD,QAAQuD,KAAK,CAAC;gBAChB;YACF;QACF;IACF;AACF,EAAkC"}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/deploy.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { AppArg } from \"../services/app/arg.js\";\nimport { REMOTE_SERVER_CONTRACT_STATUS_SUBSCRIPTION } from \"../services/app/edit-graphql.js\";\nimport type { ArgsSpec } from \"../services/command/arg.js\";\nimport { type Command, type Usage } from \"../services/command/command.js\";\nimport { FileSync } from \"../services/filesync/filesync.js\";\nimport { select } from \"../services/output/prompt.js\";\nimport { sprint } from \"../services/output/sprint.js\";\nimport { getUserOrLogin } from \"../services/user/user.js\";\nimport { isCloseEvent, isGraphQLErrors } from \"../services/util/is.js\";\n\nexport const usage: Usage = () => sprint`\n Deploy your Gadget application's development source code to production.\n\n {bold USAGE}\n ggt deploy [DIRECTORY] [--app=<name>]\n\n {bold ARGUMENTS}\n DIRECTORY The directory to sync files to and deploy (default: \".\")\n\n {bold FLAGS}\n -a, --app=<name> The Gadget application to deploy\n --force Deploy the Gadget application regardless of any issues it may have\n\n {bold DESCRIPTION}\n Deploy allows you to deploy your current Gadget application in development to production.\n \n It detects if local files are up to date with remote and if the Gadget application \n is in a deployable state. If there are any issues, it will display them and ask if \n you would like to deploy anyways. \n \n Note:\n • If local files are not up to date or have not recently been synced with remote ones,\n you will be prompted to run a one-time sync to ensure the files remain consistent with \n what is on the remote. \n • You may wish to keep ggt sync running in the background before trying to run ggt deploy\n \n {bold EXAMPLE} \n $ ggt deploy ~/gadget/example --app example\n \n App example\n Editor https://example.gadget.app/edit\n Playground https://example.gadget.app/api/graphql/playground\n Docs https://docs.gadget.dev/api/example\n\n Endpoints\n • https://example.gadget.app\n • https://example--development.gadget.app\n \n \n Building frontend assets ...\n ✔ DONE\n \n Setting up database ...\n ✔ DONE\n \n Copying development ...\n ✔ DONE\n \n Restarting app ...\n ✔ DONE\n \n Deploy completed. Good bye!\n`;\n\nexport const args = {\n \"--app\": {\n type: AppArg,\n alias: \"-a\",\n },\n \"--force\": Boolean,\n} satisfies ArgsSpec;\n\nexport enum Action {\n DEPLOY_ANYWAYS = \"Deploy anyways\",\n SYNC_ONCE = \"Sync once\",\n CANCEL = \"Cancel (Ctrl+C)\",\n}\n\nconst AppDeploymentStepsToAppDeployState = (step: string | undefined): string => {\n switch (step) {\n case \"NOT_STARTED\":\n return \"Deploy not started\";\n case \"STARTING\":\n case \"BUILDING_ASSETS\":\n case \"UPLOADING_ASSETS\":\n return \"Building frontend assets\";\n case \"CONVERGING_STORAGE\":\n return \"Setting up database\";\n case \"PUBLISHING_TREE\":\n return \"Copying development\";\n case \"RELOADING_SANDBOX\":\n return \"Restarting app\";\n case \"COMPLETED\":\n return \"Deploy completed\";\n default:\n return \"Unknown step\";\n }\n};\n\nenum AppDeploymentSteps {\n NOT_STARTED = \"NOT_STARTED\",\n STARTING = \"STARTING\",\n BUILDING_ASSETS = \"BUILDING_ASSETS\",\n UPLOADING_ASSETS = \"UPLOADING_ASSETS\",\n CONVERGING_STORAGE = \"CONVERGING_STORAGE\",\n PUBLISHING_TREE = \"PUBLISHING_TREE\",\n RELOADING_SANDBOX = \"RELOADING_SANDBOX\",\n COMPLETED = \"COMPLETED\",\n}\n\n/**\n * Runs the deploy process.\n */\n\nexport const command = (async (ctx, firstRun = true) => {\n const spinner = ora();\n let prevProgress: string | undefined = AppDeploymentStepsToAppDeployState(\"NOT_STARTED\");\n let action: Action;\n\n const filesync = await FileSync.init({\n user: await getUserOrLogin(),\n dir: ctx.args._[0],\n app: ctx.args[\"--app\"],\n });\n\n const log = filesync.log.extend(\"deploy\");\n\n if (firstRun) {\n log.printlns`App: ${filesync.app.slug}`;\n }\n\n const { inSync } = await filesync.hashes();\n if (!inSync) {\n log.printlns`\n Local files have diverged from remote. Run a sync once to converge your files or keep {italic ggt sync} running in the background.\n `;\n\n action = await select({\n message: \"How would you like to proceed?\",\n choices: [Action.CANCEL, Action.SYNC_ONCE],\n });\n\n switch (action) {\n case Action.SYNC_ONCE: {\n await filesync.sync();\n\n break;\n }\n case Action.CANCEL: {\n process.exit(0);\n }\n }\n }\n\n // subscribes to the graphql subscription that will listen and send back the server contract status\n const unsubscribe = filesync.editGraphQL.subscribe({\n query: REMOTE_SERVER_CONTRACT_STATUS_SUBSCRIPTION,\n variables: () => ({ localFilesVersion: String(filesync.filesVersion), force: ctx.args[\"--force\"] }),\n onError: (error) => {\n if (isCloseEvent(error.cause)) {\n spinner.fail(\"Failed\");\n log.printlns(error.message);\n } else if (isGraphQLErrors(error.cause)) {\n const message = error.cause[0]?.message;\n if (message && message.includes(\"GGT_PAYMENT_REQUIRED\")) {\n log.println(\"Production environment limit reached. Upgrade your plan to deploy\");\n } else {\n log.println(`${message}`);\n }\n }\n log.error(\"failed to deploy\", { error });\n unsubscribe();\n return;\n },\n onData: async ({ publishStatus }): Promise<void> => {\n const { progress, issues } = publishStatus ?? {};\n\n const hasIssues = issues?.length;\n\n if (firstRun && hasIssues) {\n log.printlns`{underline Issues detected}`;\n\n for (const issue of issues) {\n const message = issue.message.replace(/\"/g, \"\");\n const nodeType = issue.node?.type;\n const nodeName = issue.node?.name;\n const nodeParent = issue.node?.parentApiIdentifier;\n\n log.printlns(\n `\n • ${message} \n ${nodeType ? `${nodeType}: ${chalk.cyan(nodeName)}` : \"\"} ${\n nodeParent ? `ParentResource: ${chalk.cyan(nodeParent)}` : \"\"\n }\n `.trim(),\n );\n }\n\n if (!ctx.args[\"--force\"]) {\n unsubscribe();\n\n action = await select({\n message: \"Detected some issues with your app. How would you like to proceed?\",\n choices: [Action.CANCEL, Action.DEPLOY_ANYWAYS],\n });\n\n switch (action) {\n case Action.DEPLOY_ANYWAYS: {\n ctx.args[\"--force\"] = true;\n await command(ctx, false);\n break;\n }\n case Action.CANCEL: {\n process.exit(0);\n }\n }\n }\n\n firstRun = false;\n } else {\n if (progress === AppDeploymentSteps.COMPLETED) {\n spinner.succeed(\"DONE\");\n log.printlns(\"Deploy completed. Good bye!\");\n unsubscribe();\n return;\n }\n\n const currentProgress = AppDeploymentStepsToAppDeployState(progress);\n\n if (progress && currentProgress !== prevProgress) {\n if ((progress as AppDeploymentSteps) !== AppDeploymentSteps.STARTING) {\n spinner.succeed(\"DONE\");\n }\n\n prevProgress = currentProgress;\n log.printlns(`${currentProgress} ...`);\n spinner.start(\"Working ...\");\n }\n }\n },\n });\n}) satisfies Command<typeof args>;\n"],"names":["chalk","ora","AppArg","REMOTE_SERVER_CONTRACT_STATUS_SUBSCRIPTION","FileSync","select","sprint","getUserOrLogin","isCloseEvent","isGraphQLErrors","usage","args","type","alias","Boolean","Action","AppDeploymentStepsToAppDeployState","step","AppDeploymentSteps","command","ctx","firstRun","spinner","prevProgress","action","filesync","init","user","dir","_","app","log","extend","printlns","slug","inSync","hashes","message","choices","sync","process","exit","unsubscribe","editGraphQL","subscribe","query","variables","localFilesVersion","String","filesVersion","force","onError","error","cause","fail","includes","println","onData","publishStatus","progress","issues","hasIssues","length","issue","replace","nodeType","node","nodeName","name","nodeParent","parentApiIdentifier","cyan","trim","succeed","currentProgress","start"],"mappings":"AAAA,OAAOA,WAAW,QAAQ;AAC1B,OAAOC,SAAS,MAAM;AACtB,SAASC,MAAM,QAAQ,yBAAyB;AAChD,SAASC,0CAA0C,QAAQ,kCAAkC;AAG7F,SAASC,QAAQ,QAAQ,mCAAmC;AAC5D,SAASC,MAAM,QAAQ,+BAA+B;AACtD,SAASC,MAAM,QAAQ,+BAA+B;AACtD,SAASC,cAAc,QAAQ,2BAA2B;AAC1D,SAASC,YAAY,EAAEC,eAAe,QAAQ,yBAAyB;AAEvE,OAAO,MAAMC,QAAe,IAAMJ,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDzC,CAAC,CAAC;AAEF,OAAO,MAAMK,OAAO;IAClB,SAAS;QACPC,MAAMV;QACNW,OAAO;IACT;IACA,WAAWC;AACb,EAAqB;;UAETC;;;;GAAAA,WAAAA;AAMZ,MAAMC,qCAAqC,CAACC;IAC1C,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF;;UAEKC;;;;;;;;;GAAAA,uBAAAA;AAWL;;CAEC,GAED,OAAO,MAAMC,UAAW,OAAOC,KAAKC,WAAW,IAAI;IACjD,MAAMC,UAAUrB;IAChB,IAAIsB,eAAmCP,mCAAmC;IAC1E,IAAIQ;IAEJ,MAAMC,WAAW,MAAMrB,SAASsB,IAAI,CAAC;QACnCC,MAAM,MAAMpB;QACZqB,KAAKR,IAAIT,IAAI,CAACkB,CAAC,CAAC,EAAE;QAClBC,KAAKV,IAAIT,IAAI,CAAC,QA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AEAlD,eAAemD;oBACf3C,IAAIE,QAAQ,CAAC,CAAC,EAAEyC,gBAAgB,IAAI,CAAC;oBACrCpD,QAAQqD,KAAK,CAAC;gBAChB;YACF;QACF;IACF;AACF,EAAkC"}
|
|
@@ -25,6 +25,9 @@ import { getConflicts, printConflicts, withoutConflictingChanges } from "./confl
|
|
|
25
25
|
import { Directory, supportsPermissions, swallowEnoent } from "./directory.js";
|
|
26
26
|
import { InvalidSyncFileError, TooManySyncAttemptsError } from "./error.js";
|
|
27
27
|
import { getChanges, isEqualHashes } from "./hashes.js";
|
|
28
|
+
const log = createLogger({
|
|
29
|
+
name: "filesync"
|
|
30
|
+
});
|
|
28
31
|
export class FileSync {
|
|
29
32
|
/**
|
|
30
33
|
* The last filesVersion that was written to the filesystem.
|
|
@@ -157,7 +160,7 @@ export class FileSync {
|
|
|
157
160
|
/**
|
|
158
161
|
* Waits for all pending and ongoing filesync operations to complete.
|
|
159
162
|
*/ async idle() {
|
|
160
|
-
await this.
|
|
163
|
+
await this._syncOperations.onIdle();
|
|
161
164
|
}
|
|
162
165
|
/**
|
|
163
166
|
* Sends file changes to the Gadget.
|
|
@@ -165,7 +168,7 @@ export class FileSync {
|
|
|
165
168
|
* @param changes - The changes to send.
|
|
166
169
|
* @returns A promise that resolves when the changes have been sent.
|
|
167
170
|
*/ async sendChangesToGadget({ changes }) {
|
|
168
|
-
await this.
|
|
171
|
+
await this._syncOperations.add(()=>this._sendChangesToGadget({
|
|
169
172
|
changes
|
|
170
173
|
}));
|
|
171
174
|
}
|
|
@@ -187,7 +190,7 @@ export class FileSync {
|
|
|
187
190
|
}),
|
|
188
191
|
onError,
|
|
189
192
|
onData: ({ remoteFileSyncEvents: { changed, deleted, remoteFilesVersion } })=>{
|
|
190
|
-
this.
|
|
193
|
+
this._syncOperations.add(async ()=>{
|
|
191
194
|
if (BigInt(remoteFilesVersion) < this.filesVersion) {
|
|
192
195
|
this.log.warn("skipping received changes because files version is outdated", {
|
|
193
196
|
filesVersion: remoteFilesVersion
|
|
@@ -244,22 +247,33 @@ export class FileSync {
|
|
|
244
247
|
* - Conflicts are resolved by prompting the user to either keep their
|
|
245
248
|
* local changes or keep Gadget's changes.
|
|
246
249
|
* - This function will not return until the filesystem is in sync.
|
|
247
|
-
*/ async sync({
|
|
248
|
-
|
|
249
|
-
|
|
250
|
+
*/ async sync({ preference, maxAttempts = 10 } = {}) {
|
|
251
|
+
this._syncOperations.pause();
|
|
252
|
+
try {
|
|
253
|
+
for(let attempt = 0; attempt < maxAttempts; attempt++){
|
|
254
|
+
const { inSync, ...hashes } = await this.hashes();
|
|
255
|
+
if (inSync) {
|
|
256
|
+
this.log.info("filesystem is in sync");
|
|
257
|
+
await this._save(hashes.gadgetFilesVersion);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
await this._sync({
|
|
261
|
+
preference,
|
|
262
|
+
...hashes
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
} finally{
|
|
266
|
+
this._syncOperations.start();
|
|
250
267
|
}
|
|
251
|
-
|
|
268
|
+
throw new TooManySyncAttemptsError(maxAttempts);
|
|
269
|
+
}
|
|
270
|
+
async _sync({ preference, filesVersionHashes, localHashes, gadgetHashes, gadgetFilesVersion }) {
|
|
252
271
|
this.log.debug("syncing", {
|
|
253
272
|
filesVersionHashes,
|
|
254
273
|
localHashes,
|
|
255
274
|
gadgetHashes,
|
|
256
275
|
gadgetFilesVersion
|
|
257
276
|
});
|
|
258
|
-
if (isEqualHashes(localHashes, gadgetHashes)) {
|
|
259
|
-
this.log.info("filesystem is in sync");
|
|
260
|
-
await this._save(gadgetFilesVersion);
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
277
|
let localChanges = getChanges({
|
|
264
278
|
from: filesVersionHashes,
|
|
265
279
|
to: localHashes,
|
|
@@ -283,6 +297,7 @@ export class FileSync {
|
|
|
283
297
|
gadgetChanges
|
|
284
298
|
});
|
|
285
299
|
}
|
|
300
|
+
assert(localChanges.size > 0 || gadgetChanges.size > 0, "there must be changes if hashes don't match");
|
|
286
301
|
const conflicts = getConflicts({
|
|
287
302
|
localChanges,
|
|
288
303
|
gadgetChanges
|
|
@@ -325,7 +340,6 @@ export class FileSync {
|
|
|
325
340
|
}
|
|
326
341
|
}
|
|
327
342
|
}
|
|
328
|
-
assert(localChanges.size > 0 || gadgetChanges.size > 0, "there must be changes if hashes don't match");
|
|
329
343
|
if (gadgetChanges.size > 0) {
|
|
330
344
|
await this._getChangesFromGadget({
|
|
331
345
|
changes: gadgetChanges,
|
|
@@ -338,13 +352,8 @@ export class FileSync {
|
|
|
338
352
|
expectedFilesVersion: gadgetFilesVersion
|
|
339
353
|
});
|
|
340
354
|
}
|
|
341
|
-
// recursively call this function until we're in sync
|
|
342
|
-
return this.sync({
|
|
343
|
-
attempt: ++attempt,
|
|
344
|
-
preference
|
|
345
|
-
});
|
|
346
355
|
}
|
|
347
|
-
async
|
|
356
|
+
async hashes() {
|
|
348
357
|
const [localHashes, { filesVersionHashes, gadgetHashes, gadgetFilesVersion }] = await Promise.all([
|
|
349
358
|
// get the hashes of our local files
|
|
350
359
|
this.directory.hashes(),
|
|
@@ -387,7 +396,8 @@ export class FileSync {
|
|
|
387
396
|
filesVersionHashes,
|
|
388
397
|
localHashes,
|
|
389
398
|
gadgetHashes,
|
|
390
|
-
gadgetFilesVersion
|
|
399
|
+
gadgetFilesVersion,
|
|
400
|
+
inSync: isEqualHashes(localHashes, gadgetHashes)
|
|
391
401
|
};
|
|
392
402
|
}
|
|
393
403
|
async _getChangesFromGadget({ filesVersion, changes }) {
|
|
@@ -584,11 +594,6 @@ export class FileSync {
|
|
|
584
594
|
spaces: 2
|
|
585
595
|
});
|
|
586
596
|
}
|
|
587
|
-
/**
|
|
588
|
-
* Enqueues a function that handles filesync events onto the {@linkcode _queue}.
|
|
589
|
-
*/ _enqueue(fn) {
|
|
590
|
-
return this._queue.add(fn);
|
|
591
|
-
}
|
|
592
597
|
constructor(/**
|
|
593
598
|
* The directory that is being synced to.
|
|
594
599
|
*/ directory, /**
|
|
@@ -609,18 +614,15 @@ export class FileSync {
|
|
|
609
614
|
/**
|
|
610
615
|
* A FIFO async callback queue that ensures we process filesync events
|
|
611
616
|
* in the order we receive them.
|
|
612
|
-
*/ _define_property(this, "
|
|
617
|
+
*/ _define_property(this, "_syncOperations", void 0);
|
|
613
618
|
this.directory = directory;
|
|
614
619
|
this.wasEmptyOrNonExistent = wasEmptyOrNonExistent;
|
|
615
620
|
this.app = app;
|
|
616
621
|
this._state = _state;
|
|
617
|
-
this.log =
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
})
|
|
622
|
-
});
|
|
623
|
-
this._queue = new PQueue({
|
|
622
|
+
this.log = log.extend("filesync", ()=>({
|
|
623
|
+
state: this._state
|
|
624
|
+
}));
|
|
625
|
+
this._syncOperations = new PQueue({
|
|
624
626
|
concurrency: 1
|
|
625
627
|
});
|
|
626
628
|
this.editGraphQL = new EditGraphQL(this.app);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/filesync/filesync.ts"],"sourcesContent":["import dayjs from \"dayjs\";\nimport { findUp } from \"find-up\";\nimport fs from \"fs-extra\";\nimport ms from \"ms\";\nimport assert from \"node:assert\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport pMap from \"p-map\";\nimport PQueue from \"p-queue\";\nimport pRetry from \"p-retry\";\nimport type { Promisable } from \"type-fest\";\nimport { z } from \"zod\";\nimport { FileSyncEncoding, type FileSyncChangedEventInput, type FileSyncDeletedEventInput } from \"../../__generated__/graphql.js\";\nimport type { App } from \"../app/app.js\";\nimport { getApps } from \"../app/app.js\";\nimport {\n EditGraphQL,\n FILE_SYNC_COMPARISON_HASHES_QUERY,\n FILE_SYNC_FILES_QUERY,\n FILE_SYNC_HASHES_QUERY,\n PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n} from \"../app/edit-graphql.js\";\nimport { ArgError } from \"../command/arg.js\";\nimport { config, homePath } from \"../config/config.js\";\nimport { createLogger } from \"../output/log/logger.js\";\nimport { select } from \"../output/prompt.js\";\nimport { sprint } from \"../output/sprint.js\";\nimport type { User } from \"../user/user.js\";\nimport { sortBySimilar } from \"../util/collection.js\";\nimport { noop } from \"../util/function.js\";\nimport { Changes, printChanges } from \"./changes.js\";\nimport { getConflicts, printConflicts, withoutConflictingChanges } from \"./conflicts.js\";\nimport { Directory, supportsPermissions, swallowEnoent, type Hashes } from \"./directory.js\";\nimport { InvalidSyncFileError, TooManySyncAttemptsError } from \"./error.js\";\nimport type { File } from \"./file.js\";\nimport { getChanges, isEqualHashes, type ChangesWithHash } from \"./hashes.js\";\n\nexport class FileSync {\n readonly editGraphQL: EditGraphQL;\n\n readonly log = createLogger({ name: \"filesync\", fields: () => ({ state: this._state }) });\n\n /**\n * A FIFO async callback queue that ensures we process filesync events\n * in the order we receive them.\n */\n private _queue = new PQueue({ concurrency: 1 });\n\n private constructor(\n /**\n * The directory that is being synced to.\n */\n readonly directory: Directory,\n\n /**\n * Whether the directory was empty or non-existent when we started.\n */\n readonly wasEmptyOrNonExistent: boolean,\n\n /**\n * The Gadget application that is being synced to.\n */\n readonly app: App,\n\n /**\n * The state of the filesystem.\n *\n * This is persisted to `.gadget/sync.json` within the {@linkcode directory}.\n */\n private _state: { app: string; filesVersion: string; mtime: number },\n ) {\n this.editGraphQL = new EditGraphQL(this.app);\n }\n\n /**\n * The last filesVersion that was written to the filesystem.\n *\n * This determines if the filesystem in Gadget is ahead of the\n * filesystem on the local machine.\n */\n get filesVersion(): bigint {\n return BigInt(this._state.filesVersion);\n }\n\n /**\n * The largest mtime that was seen on the filesystem.\n *\n * This is used to determine if any files have changed since the last\n * sync. This does not include the mtime of files that are ignored.\n */\n get mtime(): number {\n return this._state.mtime;\n }\n\n /**\n * Initializes a {@linkcode FileSync} instance.\n * - Ensures the directory exists.\n * - Ensures the directory is empty or contains a `.gadget/sync.json` file (unless `options.force` is `true`)\n * - Ensures an app is specified (either via `options.app` or by prompting the user)\n * - Ensures the specified app matches the app the directory was previously synced to (unless `options.force` is `true`)\n */\n static async init(options: { user: User; dir?: string; app?: string; force?: boolean }): Promise<FileSync> {\n const apps = await getApps(options.user);\n if (apps.length === 0) {\n throw new ArgError(\n sprint`\n You (${options.user.email}) don't have have any Gadget applications.\n\n Visit https://gadget.new to create one!\n `,\n );\n }\n\n let dir = options.dir;\n if (!dir) {\n // the user didn't specify a directory\n const filepath = await findUp(\".gadget/sync.json\");\n if (filepath) {\n // we found a .gadget/sync.json file, use its parent directory\n dir = path.join(filepath, \"../..\");\n } else {\n // we didn't find a .gadget/sync.json file, use the current directory\n dir = process.cwd();\n }\n }\n\n if (config.windows && dir.startsWith(\"~/\")) {\n // `~` doesn't expand to the home directory on Windows\n dir = homePath(dir.slice(2));\n }\n\n // ensure the root directory is an absolute path and exists\n const wasEmptyOrNonExistent = await isEmptyOrNonExistentDir(dir);\n await fs.ensureDir((dir = path.resolve(dir)));\n\n // try to load the .gadget/sync.json file\n const state = await fs\n .readJson(path.join(dir, \".gadget/sync.json\"))\n .then((json) =>\n z\n .object({\n app: z.string(),\n filesVersion: z.string(),\n mtime: z.number(),\n })\n .parse(json),\n )\n .catch(noop);\n\n let appSlug = options.app || state?.app;\n if (!appSlug) {\n // the user didn't specify an app, suggest some apps that they can sync to\n appSlug = await select({\n message: \"Select the app to sync to\",\n choices: apps.map((x) => x.slug),\n });\n }\n\n // try to find the appSlug in their list of apps\n const app = apps.find((app) => app.slug === appSlug);\n if (!app) {\n // the specified appSlug doesn't exist in their list of apps,\n // either they misspelled it or they don't have access to it\n // anymore, suggest some apps that are similar to the one they\n // specified\n const similarAppSlugs = sortBySimilar(\n appSlug,\n apps.map((app) => app.slug),\n ).slice(0, 5);\n\n throw new ArgError(\n sprint`\n Unknown application:\n\n ${appSlug}\n\n Did you mean one of these?\n\n\n `.concat(` • ${similarAppSlugs.join(\"\\n • \")}`),\n );\n }\n\n const directory = await Directory.init(dir);\n\n if (!state) {\n // the .gadget/sync.json file didn't exist or contained invalid json\n if (wasEmptyOrNonExistent || options.force) {\n // the directory was empty or the user passed --force\n // either way, create a fresh .gadget/sync.json file\n return new FileSync(directory, wasEmptyOrNonExistent, app, { app: app.slug, filesVersion: \"0\", mtime: 0 });\n }\n\n // the directory isn't empty and the user didn't pass --force\n throw new InvalidSyncFileError(dir, app.slug);\n }\n\n // the .gadget/sync.json file exists\n if (state.app === app.slug) {\n // the .gadget/sync.json file is for the same app that the user specified\n return new FileSync(directory, wasEmptyOrNonExistent, app, state);\n }\n\n // the .gadget/sync.json file is for a different app\n if (options.force) {\n // the user passed --force, so use the app they specified and overwrite everything\n return new FileSync(directory, wasEmptyOrNonExistent, app, { app: app.slug, filesVersion: \"0\", mtime: 0 });\n }\n\n // the user didn't pass --force, so throw an error\n throw new ArgError(sprint`\n You were about to sync the following app to the following directory:\n\n {dim ${app.slug}} → {dim ${dir}}\n\n However, that directory has already been synced with this app:\n\n {dim ${state.app}}\n\n If you're sure that you want to sync:\n\n {dim ${app.slug}} → {dim ${dir}}\n\n Then run {dim ggt sync} again with the {dim --force} flag.\n `);\n }\n\n /**\n * Waits for all pending and ongoing filesync operations to complete.\n */\n async idle(): Promise<void> {\n await this._queue.onIdle();\n }\n\n /**\n * Sends file changes to the Gadget.\n *\n * @param changes - The changes to send.\n * @returns A promise that resolves when the changes have been sent.\n */\n async sendChangesToGadget({ changes }: { changes: Changes }): Promise<void> {\n await this._enqueue(() => this._sendChangesToGadget({ changes }));\n }\n\n /**\n * Subscribes to file changes on Gadget and executes the provided\n * callbacks before and after the changes occur.\n *\n * @returns A function that unsubscribes from changes on Gadget.\n */\n subscribeToGadgetChanges({\n beforeChanges,\n afterChanges,\n onError,\n }: {\n beforeChanges: (data: { changed: string[]; deleted: string[] }) => Promisable<void>;\n afterChanges: (data: { changes: Changes }) => Promisable<void>;\n onError: (error: unknown) => void;\n }): () => void {\n return this.editGraphQL.subscribe({\n query: REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n // the reason this is a function rather than a static value is\n // so that it will be re-evaluated if the connection is lost and\n // then re-established. this ensures that we send our current\n // filesVersion rather than the one that was sent when we first\n // subscribed\n variables: () => ({ localFilesVersion: String(this.filesVersion) }),\n onError,\n onData: ({ remoteFileSyncEvents: { changed, deleted, remoteFilesVersion } }) => {\n this._enqueue(async () => {\n if (BigInt(remoteFilesVersion) < this.filesVersion) {\n this.log.warn(\"skipping received changes because files version is outdated\", { filesVersion: remoteFilesVersion });\n return;\n }\n\n this.log.debug(\"received files\", {\n remoteFilesVersion: remoteFilesVersion,\n changed: changed.map((change) => change.path),\n deleted: deleted.map((change) => change.path),\n });\n\n const filterIgnoredFiles = (file: { path: string }): boolean => {\n const ignored = this.directory.ignores(file.path);\n if (ignored) {\n this.log.warn(\"skipping received change because file is ignored\", { path: file.path });\n }\n return !ignored;\n };\n\n changed = changed.filter(filterIgnoredFiles);\n deleted = deleted.filter(filterIgnoredFiles);\n\n if (changed.length === 0 && deleted.length === 0) {\n await this._save(remoteFilesVersion);\n return;\n }\n\n await beforeChanges({\n changed: changed.map((file) => file.path),\n deleted: deleted.map((file) => file.path),\n });\n\n const changes = await this._writeToLocalFilesystem({\n filesVersion: remoteFilesVersion,\n files: changed,\n delete: deleted.map((file) => file.path),\n });\n\n if (changes.size > 0) {\n printChanges({\n message: sprint`← Received {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n changes,\n tense: \"past\",\n limit: 10,\n });\n }\n\n await afterChanges({ changes });\n }).catch(onError);\n },\n });\n }\n\n /**\n * Ensures the local filesystem is in sync with Gadget's filesystem.\n * - All non-conflicting changes are automatically merged.\n * - Conflicts are resolved by prompting the user to either keep their\n * local changes or keep Gadget's changes.\n * - This function will not return until the filesystem is in sync.\n */\n async sync({ attempt = 0, preference }: { attempt?: number; preference?: ConflictPreference } = {}): Promise<void> {\n if (attempt > 10) {\n throw new TooManySyncAttemptsError(attempt);\n }\n\n const { filesVersionHashes, localHashes, gadgetHashes, gadgetFilesVersion } = await this._getHashes();\n this.log.debug(\"syncing\", { filesVersionHashes, localHashes, gadgetHashes, gadgetFilesVersion });\n\n if (isEqualHashes(localHashes, gadgetHashes)) {\n this.log.info(\"filesystem is in sync\");\n await this._save(gadgetFilesVersion);\n return;\n }\n\n let localChanges = getChanges({ from: filesVersionHashes, to: localHashes, existing: gadgetHashes, ignore: [\".gadget/\"] });\n let gadgetChanges = getChanges({ from: filesVersionHashes, to: gadgetHashes, existing: localHashes });\n\n if (localChanges.size === 0 && gadgetChanges.size === 0) {\n // the local filesystem is missing .gadget/ files\n gadgetChanges = getChanges({ from: localHashes, to: gadgetHashes });\n assertAllGadgetFiles({ gadgetChanges });\n }\n\n const conflicts = getConflicts({ localChanges, gadgetChanges });\n if (conflicts.size > 0) {\n this.log.debug(\"conflicts detected\", { conflicts });\n\n if (!preference) {\n printConflicts({\n message: sprint`{bold You have conflicting changes with Gadget}`,\n conflicts,\n });\n\n preference = await select({\n message: \"How would you like to resolve these conflicts?\",\n choices: Object.values(ConflictPreference),\n });\n }\n\n switch (preference) {\n case ConflictPreference.CANCEL: {\n process.exit(0);\n break;\n }\n case ConflictPreference.LOCAL: {\n gadgetChanges = withoutConflictingChanges({ conflicts, changes: gadgetChanges });\n break;\n }\n case ConflictPreference.GADGET: {\n localChanges = withoutConflictingChanges({ conflicts, changes: localChanges });\n break;\n }\n }\n }\n\n assert(localChanges.size > 0 || gadgetChanges.size > 0, \"there must be changes if hashes don't match\");\n\n if (gadgetChanges.size > 0) {\n await this._getChangesFromGadget({ changes: gadgetChanges, filesVersion: gadgetFilesVersion });\n }\n\n if (localChanges.size > 0) {\n await this._sendChangesToGadget({ changes: localChanges, expectedFilesVersion: gadgetFilesVersion });\n }\n\n // recursively call this function until we're in sync\n return this.sync({ attempt: ++attempt, preference });\n }\n\n async _getHashes(): Promise<{\n gadgetFilesVersion: bigint;\n filesVersionHashes: Hashes;\n localHashes: Hashes;\n gadgetHashes: Hashes;\n }> {\n const [localHashes, { filesVersionHashes, gadgetHashes, gadgetFilesVersion }] = await Promise.all([\n // get the hashes of our local files\n this.directory.hashes(),\n // get the hashes of our local filesVersion and the latest filesVersion\n (async () => {\n let gadgetFilesVersion: bigint;\n let gadgetHashes: Hashes;\n let filesVersionHashes: Hashes;\n\n if (this.filesVersion === 0n) {\n // this is the first time we're syncing, so just get the\n // hashes of the latest filesVersion\n const { fileSyncHashes } = await this.editGraphQL.query({ query: FILE_SYNC_HASHES_QUERY });\n gadgetFilesVersion = BigInt(fileSyncHashes.filesVersion);\n gadgetHashes = fileSyncHashes.hashes;\n filesVersionHashes = {};\n } else {\n // this isn't the first time we're syncing, so get the hashes\n // of the files at our local filesVersion and the latest\n // filesVersion\n const { fileSyncComparisonHashes } = await this.editGraphQL.query({\n query: FILE_SYNC_COMPARISON_HASHES_QUERY,\n variables: { filesVersion: String(this.filesVersion) },\n });\n gadgetFilesVersion = BigInt(fileSyncComparisonHashes.latestFilesVersionHashes.filesVersion);\n gadgetHashes = fileSyncComparisonHashes.latestFilesVersionHashes.hashes;\n filesVersionHashes = fileSyncComparisonHashes.filesVersionHashes.hashes;\n }\n\n return { filesVersionHashes, gadgetHashes, gadgetFilesVersion };\n })(),\n ]);\n\n return { filesVersionHashes, localHashes, gadgetHashes, gadgetFilesVersion };\n }\n\n private async _getChangesFromGadget({\n filesVersion,\n changes,\n }: {\n filesVersion: bigint;\n changes: Changes | ChangesWithHash;\n }): Promise<void> {\n this.log.debug(\"getting changes from gadget\", { filesVersion, changes });\n const created = changes.created();\n const updated = changes.updated();\n\n let files: File[] = [];\n if (created.length > 0 || updated.length > 0) {\n const { fileSyncFiles } = await this.editGraphQL.query({\n query: FILE_SYNC_FILES_QUERY,\n variables: {\n paths: [...created, ...updated],\n filesVersion: String(filesVersion),\n encoding: FileSyncEncoding.Base64,\n },\n });\n\n files = fileSyncFiles.files;\n }\n\n await this._writeToLocalFilesystem({\n filesVersion,\n files,\n delete: changes.deleted(),\n });\n\n printChanges({\n changes,\n tense: \"past\",\n message: sprint`← Received {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n });\n }\n\n private async _sendChangesToGadget({\n expectedFilesVersion = this.filesVersion,\n changes,\n printLimit,\n }: {\n expectedFilesVersion?: bigint;\n changes: Changes;\n printLimit?: number;\n }): Promise<void> {\n this.log.debug(\"sending changes to gadget\", { expectedFilesVersion, changes });\n const changed: FileSyncChangedEventInput[] = [];\n const deleted: FileSyncDeletedEventInput[] = [];\n\n await pMap(changes, async ([normalizedPath, change]) => {\n if (change.type === \"delete\") {\n deleted.push({ path: normalizedPath });\n return;\n }\n\n const absolutePath = this.directory.absolute(normalizedPath);\n\n let stats;\n try {\n stats = await fs.stat(absolutePath);\n } catch (error) {\n swallowEnoent(error);\n this.log.debug(\"skipping change because file doesn't exist\", { path: normalizedPath });\n return;\n }\n\n let content = \"\";\n if (stats.isFile()) {\n content = await fs.readFile(absolutePath, FileSyncEncoding.Base64);\n }\n\n let oldPath;\n if (change.type === \"create\" && change.oldPath) {\n oldPath = change.oldPath;\n }\n\n changed.push({\n content,\n oldPath,\n path: normalizedPath,\n mode: stats.mode,\n encoding: FileSyncEncoding.Base64,\n });\n });\n\n if (changed.length === 0 && deleted.length === 0) {\n this.log.debug(\"skipping send because there are no changes\");\n return;\n }\n\n const {\n publishFileSyncEvents: { remoteFilesVersion },\n } = await this.editGraphQL.query({\n query: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: {\n input: {\n expectedRemoteFilesVersion: String(expectedFilesVersion),\n changed,\n deleted,\n },\n },\n });\n\n await this._save(remoteFilesVersion);\n\n printChanges({\n changes,\n tense: \"past\",\n message: sprint`→ Sent {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n limit: printLimit,\n });\n }\n\n private async _writeToLocalFilesystem(options: { filesVersion: bigint | string; files: File[]; delete: string[] }): Promise<Changes> {\n const filesVersion = BigInt(options.filesVersion);\n assert(filesVersion >= this.filesVersion, \"filesVersion must be greater than or equal to current filesVersion\");\n\n this.log.debug(\"writing to local filesystem\", {\n filesVersion,\n files: options.files.map((file) => file.path),\n delete: options.delete,\n });\n\n const created: string[] = [];\n const updated: string[] = [];\n\n await pMap(options.delete, async (filepath) => {\n const currentPath = this.directory.absolute(filepath);\n const backupPath = this.directory.absolute(\".gadget/backup\", this.directory.relative(filepath));\n\n // rather than `rm -rf`ing files, we move them to\n // `.gadget/backup/` so that users can recover them if something\n // goes wrong. We've seen a lot of EBUSY/EINVAL errors when moving\n // files so we retry a few times.\n await pRetry(\n async () => {\n try {\n // remove the current backup file in case it exists and is a\n // different type (file vs directory)\n await fs.remove(backupPath);\n await fs.move(currentPath, backupPath);\n } catch (error) {\n // replicate the behavior of `rm -rf` and ignore ENOENT\n swallowEnoent(error);\n }\n },\n {\n retries: 2,\n minTimeout: ms(\"100ms\"),\n onFailedAttempt: (error) => {\n this.log.warn(\"failed to move file to backup\", { error, currentPath, backupPath });\n },\n },\n );\n });\n\n await pMap(options.files, async (file) => {\n const absolutePath = this.directory.absolute(file.path);\n if (await fs.pathExists(absolutePath)) {\n updated.push(file.path);\n } else {\n created.push(file.path);\n }\n\n if (file.path.endsWith(\"/\")) {\n await fs.ensureDir(absolutePath);\n } else {\n await fs.outputFile(absolutePath, Buffer.from(file.content, file.encoding));\n }\n\n if (supportsPermissions) {\n // the os's default umask makes setting the mode during creation\n // not work, so an additional fs.chmod call is necessary to\n // ensure the file has the correct mode\n await fs.chmod(absolutePath, file.mode & 0o777);\n }\n\n if (absolutePath === this.directory.absolute(\".ignore\")) {\n await this.directory.loadIgnoreFile();\n }\n });\n\n await this._save(String(filesVersion));\n\n return new Changes([\n ...created.map((path) => [path, { type: \"create\" }] as const),\n ...updated.map((path) => [path, { type: \"update\" }] as const),\n ...options.delete.map((path) => [path, { type: \"delete\" }] as const),\n ]);\n }\n\n /**\n * Updates {@linkcode _state} and saves it to `.gadget/sync.json`.\n */\n private async _save(filesVersion: string | bigint): Promise<void> {\n this._state = { ...this._state, mtime: Date.now() + 1, filesVersion: String(filesVersion) };\n this.log.debug(\"saving state\", { state: this._state });\n await fs.outputJSON(this.directory.absolute(\".gadget/sync.json\"), this._state, { spaces: 2 });\n }\n\n /**\n * Enqueues a function that handles filesync events onto the {@linkcode _queue}.\n */\n private _enqueue<T>(fn: () => Promise<T>): Promise<T> {\n return this._queue.add(fn) as Promise<T>;\n }\n}\n\n/**\n * Checks if a directory is empty or non-existent.\n *\n * @param dir - The directory path to check.\n * @returns A Promise that resolves to a boolean indicating whether the directory is empty or non-existent.\n */\nexport const isEmptyOrNonExistentDir = async (dir: string): Promise<boolean> => {\n try {\n for await (const _ of await fs.opendir(dir, { bufferSize: 1 })) {\n return false;\n }\n return true;\n } catch (error) {\n swallowEnoent(error);\n return true;\n }\n};\n\nexport const assertAllGadgetFiles = ({ gadgetChanges }: { gadgetChanges: Changes }): void => {\n assert(\n gadgetChanges.created().length > 0 || gadgetChanges.deleted().length > 0 || gadgetChanges.updated().length > 0,\n \"expected gadgetChanges to have changes\",\n );\n\n const allGadgetFiles = Array.from(gadgetChanges.keys()).every((path) => path.startsWith(\".gadget/\"));\n assert(allGadgetFiles, \"expected all gadgetChanges to be .gadget/ files\");\n};\n\nexport const ConflictPreference = Object.freeze({\n CANCEL: \"Cancel (Ctrl+C)\",\n LOCAL: \"Keep my conflicting changes\",\n GADGET: \"Keep Gadget's conflicting changes\",\n});\n\nexport type ConflictPreference = (typeof ConflictPreference)[keyof typeof ConflictPreference];\n\nexport const ConflictPreferenceArg = (value: string, name: string): ConflictPreference => {\n if ([\"local\", \"gadget\"].includes(value)) {\n return ConflictPreference[value.toUpperCase() as keyof typeof ConflictPreference];\n }\n\n throw new ArgError(sprint`\n ${name} must be {bold local} or {bold gadget}\n\n {bold EXAMPLES:}\n ${name} local\n ${name} gadget\n `);\n};\n"],"names":["dayjs","findUp","fs","ms","assert","path","process","pMap","PQueue","pRetry","z","FileSyncEncoding","getApps","EditGraphQL","FILE_SYNC_COMPARISON_HASHES_QUERY","FILE_SYNC_FILES_QUERY","FILE_SYNC_HASHES_QUERY","PUBLISH_FILE_SYNC_EVENTS_MUTATION","REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION","ArgError","config","homePath","createLogger","select","sprint","sortBySimilar","noop","Changes","printChanges","getConflicts","printConflicts","withoutConflictingChanges","Directory","supportsPermissions","swallowEnoent","InvalidSyncFileError","TooManySyncAttemptsError","getChanges","isEqualHashes","FileSync","filesVersion","BigInt","_state","mtime","init","options","apps","user","length","email","dir","filepath","join","cwd","windows","startsWith","slice","wasEmptyOrNonExistent","isEmptyOrNonExistentDir","ensureDir","resolve","state","readJson","then","json","object","app","string","number","parse","catch","appSlug","message","choices","map","x","slug","find","similarAppSlugs","concat","directory","force","idle","_queue","onIdle","sendChangesToGadget","changes","_enqueue","_sendChangesToGadget","subscribeToGadgetChanges","beforeChanges","afterChanges","onError","editGraphQL","subscribe","query","variables","localFilesVersion","String","onData","remoteFileSyncEvents","changed","deleted","remoteFilesVersion","log","warn","debug","change","filterIgnoredFiles","file","ignored","ignores","filter","_save","_writeToLocalFilesystem","files","delete","size","format","tense","limit","sync","attempt","preference","filesVersionHashes","localHashes","gadgetHashes","gadgetFilesVersion","_getHashes","info","localChanges","from","to","existing","ignore","gadgetChanges","assertAllGadgetFiles","conflicts","Object","values","ConflictPreference","CANCEL","exit","LOCAL","GADGET","_getChangesFromGadget","expectedFilesVersion","Promise","all","hashes","fileSyncHashes","fileSyncComparisonHashes","latestFilesVersionHashes","created","updated","fileSyncFiles","paths","encoding","Base64","printLimit","normalizedPath","type","push","absolutePath","absolute","stats","stat","error","content","isFile","readFile","oldPath","mode","publishFileSyncEvents","input","expectedRemoteFilesVersion","currentPath","backupPath","relative","remove","move","retries","minTimeout","onFailedAttempt","pathExists","endsWith","outputFile","Buffer","chmod","loadIgnoreFile","Date","now","outputJSON","spaces","fn","add","name","fields","concurrency","_","opendir","bufferSize","allGadgetFiles","Array","keys","every","freeze","ConflictPreferenceArg","value","includes","toUpperCase"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AC,EAAED,aAAa,EAA8B;IAChFnI,OACEmI,cAAckB,OAAO,GAAGzG,MAAM,GAAG,KAAKuF,cAAcjC,OAAO,GAAGtD,MAAM,GAAG,KAAKuF,cAAcmB,OAAO,GAAG1G,MAAM,GAAG,GAC7G;IAGF,MAAM0J,iBAAiBC,MAAMxE,IAAI,CAACI,cAAcqE,IAAI,IAAIC,KAAK,CAAC,CAACxM,OAASA,KAAKkD,UAAU,CAAC;IACxFnD,OAAOsM,gBAAgB;AACzB,EAAE;AAEF,OAAO,MAAM9D,qBAAqBF,OAAOoE,MAAM,CAAC;IAC9CjE,QAAQ;IACRE,OAAO;IACPC,QAAQ;AACV,GAAG;AAIH,OAAO,MAAM+D,wBAAwB,CAACC,OAAeZ;IACnD,IAAI;QAAC;QAAS;KAAS,CAACa,QAAQ,CAACD,QAAQ;QACvC,OAAOpE,kBAAkB,CAACoE,MAAME,WAAW,GAAsC;IACnF;IAEA,MAAM,IAAI/L,SAASK,MAAM,CAAC;MACtB,EAAE4K,KAAK;;;QAGL,EAAEA,KAAK;QACP,EAAEA,KAAK;IACX,CAAC;AACL,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/filesync/filesync.ts"],"sourcesContent":["import dayjs from \"dayjs\";\nimport { findUp } from \"find-up\";\nimport fs from \"fs-extra\";\nimport ms from \"ms\";\nimport assert from \"node:assert\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport pMap from \"p-map\";\nimport PQueue from \"p-queue\";\nimport pRetry from \"p-retry\";\nimport type { Promisable } from \"type-fest\";\nimport { z } from \"zod\";\nimport { FileSyncEncoding, type FileSyncChangedEventInput, type FileSyncDeletedEventInput } from \"../../__generated__/graphql.js\";\nimport type { App } from \"../app/app.js\";\nimport { getApps } from \"../app/app.js\";\nimport {\n EditGraphQL,\n FILE_SYNC_COMPARISON_HASHES_QUERY,\n FILE_SYNC_FILES_QUERY,\n FILE_SYNC_HASHES_QUERY,\n PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n} from \"../app/edit-graphql.js\";\nimport { ArgError } from \"../command/arg.js\";\nimport { config, homePath } from \"../config/config.js\";\nimport { createLogger } from \"../output/log/logger.js\";\nimport { select } from \"../output/prompt.js\";\nimport { sprint } from \"../output/sprint.js\";\nimport type { User } from \"../user/user.js\";\nimport { sortBySimilar } from \"../util/collection.js\";\nimport { noop } from \"../util/function.js\";\nimport { Changes, printChanges } from \"./changes.js\";\nimport { getConflicts, printConflicts, withoutConflictingChanges } from \"./conflicts.js\";\nimport { Directory, supportsPermissions, swallowEnoent, type Hashes } from \"./directory.js\";\nimport { InvalidSyncFileError, TooManySyncAttemptsError } from \"./error.js\";\nimport type { File } from \"./file.js\";\nimport { getChanges, isEqualHashes, type ChangesWithHash } from \"./hashes.js\";\n\nconst log = createLogger({ name: \"filesync\" });\n\nexport type FileSyncHashes = {\n inSync: boolean;\n filesVersionHashes: Hashes;\n localHashes: Hashes;\n gadgetHashes: Hashes;\n gadgetFilesVersion: bigint;\n};\n\nexport class FileSync {\n readonly editGraphQL: EditGraphQL;\n\n readonly log = log.extend(\"filesync\", () => ({ state: this._state }));\n\n /**\n * A FIFO async callback queue that ensures we process filesync events\n * in the order we receive them.\n */\n private _syncOperations = new PQueue({ concurrency: 1 });\n\n private constructor(\n /**\n * The directory that is being synced to.\n */\n readonly directory: Directory,\n\n /**\n * Whether the directory was empty or non-existent when we started.\n */\n readonly wasEmptyOrNonExistent: boolean,\n\n /**\n * The Gadget application that is being synced to.\n */\n readonly app: App,\n\n /**\n * The state of the filesystem.\n *\n * This is persisted to `.gadget/sync.json` within the {@linkcode directory}.\n */\n private _state: { app: string; filesVersion: string; mtime: number },\n ) {\n this.editGraphQL = new EditGraphQL(this.app);\n }\n\n /**\n * The last filesVersion that was written to the filesystem.\n *\n * This determines if the filesystem in Gadget is ahead of the\n * filesystem on the local machine.\n */\n get filesVersion(): bigint {\n return BigInt(this._state.filesVersion);\n }\n\n /**\n * The largest mtime that was seen on the filesystem.\n *\n * This is used to determine if any files have changed since the last\n * sync. This does not include the mtime of files that are ignored.\n */\n get mtime(): number {\n return this._state.mtime;\n }\n\n /**\n * Initializes a {@linkcode FileSync} instance.\n * - Ensures the directory exists.\n * - Ensures the directory is empty or contains a `.gadget/sync.json` file (unless `options.force` is `true`)\n * - Ensures an app is specified (either via `options.app` or by prompting the user)\n * - Ensures the specified app matches the app the directory was previously synced to (unless `options.force` is `true`)\n */\n static async init(options: { user: User; dir?: string; app?: string; force?: boolean }): Promise<FileSync> {\n const apps = await getApps(options.user);\n if (apps.length === 0) {\n throw new ArgError(\n sprint`\n You (${options.user.email}) don't have have any Gadget applications.\n\n Visit https://gadget.new to create one!\n `,\n );\n }\n\n let dir = options.dir;\n if (!dir) {\n // the user didn't specify a directory\n const filepath = await findUp(\".gadget/sync.json\");\n if (filepath) {\n // we found a .gadget/sync.json file, use its parent directory\n dir = path.join(filepath, \"../..\");\n } else {\n // we didn't find a .gadget/sync.json file, use the current directory\n dir = process.cwd();\n }\n }\n\n if (config.windows && dir.startsWith(\"~/\")) {\n // `~` doesn't expand to the home directory on Windows\n dir = homePath(dir.slice(2));\n }\n\n // ensure the root directory is an absolute path and exists\n const wasEmptyOrNonExistent = await isEmptyOrNonExistentDir(dir);\n await fs.ensureDir((dir = path.resolve(dir)));\n\n // try to load the .gadget/sync.json file\n const state = await fs\n .readJson(path.join(dir, \".gadget/sync.json\"))\n .then((json) =>\n z\n .object({\n app: z.string(),\n filesVersion: z.string(),\n mtime: z.number(),\n })\n .parse(json),\n )\n .catch(noop);\n\n let appSlug = options.app || state?.app;\n if (!appSlug) {\n // the user didn't specify an app, suggest some apps that they can sync to\n appSlug = await select({\n message: \"Select the app to sync to\",\n choices: apps.map((x) => x.slug),\n });\n }\n\n // try to find the appSlug in their list of apps\n const app = apps.find((app) => app.slug === appSlug);\n if (!app) {\n // the specified appSlug doesn't exist in their list of apps,\n // either they misspelled it or they don't have access to it\n // anymore, suggest some apps that are similar to the one they\n // specified\n const similarAppSlugs = sortBySimilar(\n appSlug,\n apps.map((app) => app.slug),\n ).slice(0, 5);\n\n throw new ArgError(\n sprint`\n Unknown application:\n\n ${appSlug}\n\n Did you mean one of these?\n\n\n `.concat(` • ${similarAppSlugs.join(\"\\n • \")}`),\n );\n }\n\n const directory = await Directory.init(dir);\n\n if (!state) {\n // the .gadget/sync.json file didn't exist or contained invalid json\n if (wasEmptyOrNonExistent || options.force) {\n // the directory was empty or the user passed --force\n // either way, create a fresh .gadget/sync.json file\n return new FileSync(directory, wasEmptyOrNonExistent, app, { app: app.slug, filesVersion: \"0\", mtime: 0 });\n }\n\n // the directory isn't empty and the user didn't pass --force\n throw new InvalidSyncFileError(dir, app.slug);\n }\n\n // the .gadget/sync.json file exists\n if (state.app === app.slug) {\n // the .gadget/sync.json file is for the same app that the user specified\n return new FileSync(directory, wasEmptyOrNonExistent, app, state);\n }\n\n // the .gadget/sync.json file is for a different app\n if (options.force) {\n // the user passed --force, so use the app they specified and overwrite everything\n return new FileSync(directory, wasEmptyOrNonExistent, app, { app: app.slug, filesVersion: \"0\", mtime: 0 });\n }\n\n // the user didn't pass --force, so throw an error\n throw new ArgError(sprint`\n You were about to sync the following app to the following directory:\n\n {dim ${app.slug}} → {dim ${dir}}\n\n However, that directory has already been synced with this app:\n\n {dim ${state.app}}\n\n If you're sure that you want to sync:\n\n {dim ${app.slug}} → {dim ${dir}}\n\n Then run {dim ggt sync} again with the {dim --force} flag.\n `);\n }\n\n /**\n * Waits for all pending and ongoing filesync operations to complete.\n */\n async idle(): Promise<void> {\n await this._syncOperations.onIdle();\n }\n\n /**\n * Sends file changes to the Gadget.\n *\n * @param changes - The changes to send.\n * @returns A promise that resolves when the changes have been sent.\n */\n async sendChangesToGadget({ changes }: { changes: Changes }): Promise<void> {\n await this._syncOperations.add(() => this._sendChangesToGadget({ changes }));\n }\n\n /**\n * Subscribes to file changes on Gadget and executes the provided\n * callbacks before and after the changes occur.\n *\n * @returns A function that unsubscribes from changes on Gadget.\n */\n subscribeToGadgetChanges({\n beforeChanges,\n afterChanges,\n onError,\n }: {\n beforeChanges: (data: { changed: string[]; deleted: string[] }) => Promisable<void>;\n afterChanges: (data: { changes: Changes }) => Promisable<void>;\n onError: (error: unknown) => void;\n }): () => void {\n return this.editGraphQL.subscribe({\n query: REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION,\n // the reason this is a function rather than a static value is\n // so that it will be re-evaluated if the connection is lost and\n // then re-established. this ensures that we send our current\n // filesVersion rather than the one that was sent when we first\n // subscribed\n variables: () => ({ localFilesVersion: String(this.filesVersion) }),\n onError,\n onData: ({ remoteFileSyncEvents: { changed, deleted, remoteFilesVersion } }) => {\n this._syncOperations\n .add(async () => {\n if (BigInt(remoteFilesVersion) < this.filesVersion) {\n this.log.warn(\"skipping received changes because files version is outdated\", { filesVersion: remoteFilesVersion });\n return;\n }\n\n this.log.debug(\"received files\", {\n remoteFilesVersion: remoteFilesVersion,\n changed: changed.map((change) => change.path),\n deleted: deleted.map((change) => change.path),\n });\n\n const filterIgnoredFiles = (file: { path: string }): boolean => {\n const ignored = this.directory.ignores(file.path);\n if (ignored) {\n this.log.warn(\"skipping received change because file is ignored\", { path: file.path });\n }\n return !ignored;\n };\n\n changed = changed.filter(filterIgnoredFiles);\n deleted = deleted.filter(filterIgnoredFiles);\n\n if (changed.length === 0 && deleted.length === 0) {\n await this._save(remoteFilesVersion);\n return;\n }\n\n await beforeChanges({\n changed: changed.map((file) => file.path),\n deleted: deleted.map((file) => file.path),\n });\n\n const changes = await this._writeToLocalFilesystem({\n filesVersion: remoteFilesVersion,\n files: changed,\n delete: deleted.map((file) => file.path),\n });\n\n if (changes.size > 0) {\n printChanges({\n message: sprint`← Received {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n changes,\n tense: \"past\",\n limit: 10,\n });\n }\n\n await afterChanges({ changes });\n })\n .catch(onError);\n },\n });\n }\n\n /**\n * Ensures the local filesystem is in sync with Gadget's filesystem.\n * - All non-conflicting changes are automatically merged.\n * - Conflicts are resolved by prompting the user to either keep their\n * local changes or keep Gadget's changes.\n * - This function will not return until the filesystem is in sync.\n */\n async sync({ preference, maxAttempts = 10 }: { preference?: ConflictPreference; maxAttempts?: number } = {}): Promise<void> {\n this._syncOperations.pause();\n\n try {\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const { inSync, ...hashes } = await this.hashes();\n\n if (inSync) {\n this.log.info(\"filesystem is in sync\");\n await this._save(hashes.gadgetFilesVersion);\n return;\n }\n\n await this._sync({ preference, ...hashes });\n }\n } finally {\n this._syncOperations.start();\n }\n\n throw new TooManySyncAttemptsError(maxAttempts);\n }\n\n async _sync({\n preference,\n filesVersionHashes,\n localHashes,\n gadgetHashes,\n gadgetFilesVersion,\n }: { preference?: ConflictPreference } & Omit<FileSyncHashes, \"inSync\">): Promise<void> {\n this.log.debug(\"syncing\", { filesVersionHashes, localHashes, gadgetHashes, gadgetFilesVersion });\n let localChanges = getChanges({ from: filesVersionHashes, to: localHashes, existing: gadgetHashes, ignore: [\".gadget/\"] });\n let gadgetChanges = getChanges({ from: filesVersionHashes, to: gadgetHashes, existing: localHashes });\n\n if (localChanges.size === 0 && gadgetChanges.size === 0) {\n // the local filesystem is missing .gadget/ files\n gadgetChanges = getChanges({ from: localHashes, to: gadgetHashes });\n assertAllGadgetFiles({ gadgetChanges });\n }\n\n assert(localChanges.size > 0 || gadgetChanges.size > 0, \"there must be changes if hashes don't match\");\n\n const conflicts = getConflicts({ localChanges, gadgetChanges });\n if (conflicts.size > 0) {\n this.log.debug(\"conflicts detected\", { conflicts });\n\n if (!preference) {\n printConflicts({\n message: sprint`{bold You have conflicting changes with Gadget}`,\n conflicts,\n });\n\n preference = await select({\n message: \"How would you like to resolve these conflicts?\",\n choices: Object.values(ConflictPreference),\n });\n }\n\n switch (preference) {\n case ConflictPreference.CANCEL: {\n process.exit(0);\n break;\n }\n case ConflictPreference.LOCAL: {\n gadgetChanges = withoutConflictingChanges({ conflicts, changes: gadgetChanges });\n break;\n }\n case ConflictPreference.GADGET: {\n localChanges = withoutConflictingChanges({ conflicts, changes: localChanges });\n break;\n }\n }\n }\n\n if (gadgetChanges.size > 0) {\n await this._getChangesFromGadget({ changes: gadgetChanges, filesVersion: gadgetFilesVersion });\n }\n\n if (localChanges.size > 0) {\n await this._sendChangesToGadget({ changes: localChanges, expectedFilesVersion: gadgetFilesVersion });\n }\n }\n\n async hashes(): Promise<FileSyncHashes> {\n const [localHashes, { filesVersionHashes, gadgetHashes, gadgetFilesVersion }] = await Promise.all([\n // get the hashes of our local files\n this.directory.hashes(),\n // get the hashes of our local filesVersion and the latest filesVersion\n (async () => {\n let gadgetFilesVersion: bigint;\n let gadgetHashes: Hashes;\n let filesVersionHashes: Hashes;\n\n if (this.filesVersion === 0n) {\n // this is the first time we're syncing, so just get the\n // hashes of the latest filesVersion\n const { fileSyncHashes } = await this.editGraphQL.query({ query: FILE_SYNC_HASHES_QUERY });\n gadgetFilesVersion = BigInt(fileSyncHashes.filesVersion);\n gadgetHashes = fileSyncHashes.hashes;\n filesVersionHashes = {};\n } else {\n // this isn't the first time we're syncing, so get the hashes\n // of the files at our local filesVersion and the latest\n // filesVersion\n const { fileSyncComparisonHashes } = await this.editGraphQL.query({\n query: FILE_SYNC_COMPARISON_HASHES_QUERY,\n variables: { filesVersion: String(this.filesVersion) },\n });\n gadgetFilesVersion = BigInt(fileSyncComparisonHashes.latestFilesVersionHashes.filesVersion);\n gadgetHashes = fileSyncComparisonHashes.latestFilesVersionHashes.hashes;\n filesVersionHashes = fileSyncComparisonHashes.filesVersionHashes.hashes;\n }\n\n return { filesVersionHashes, gadgetHashes, gadgetFilesVersion };\n })(),\n ]);\n\n return { filesVersionHashes, localHashes, gadgetHashes, gadgetFilesVersion, inSync: isEqualHashes(localHashes, gadgetHashes) };\n }\n\n private async _getChangesFromGadget({\n filesVersion,\n changes,\n }: {\n filesVersion: bigint;\n changes: Changes | ChangesWithHash;\n }): Promise<void> {\n this.log.debug(\"getting changes from gadget\", { filesVersion, changes });\n const created = changes.created();\n const updated = changes.updated();\n\n let files: File[] = [];\n if (created.length > 0 || updated.length > 0) {\n const { fileSyncFiles } = await this.editGraphQL.query({\n query: FILE_SYNC_FILES_QUERY,\n variables: {\n paths: [...created, ...updated],\n filesVersion: String(filesVersion),\n encoding: FileSyncEncoding.Base64,\n },\n });\n\n files = fileSyncFiles.files;\n }\n\n await this._writeToLocalFilesystem({\n filesVersion,\n files,\n delete: changes.deleted(),\n });\n\n printChanges({\n changes,\n tense: \"past\",\n message: sprint`← Received {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n });\n }\n\n private async _sendChangesToGadget({\n expectedFilesVersion = this.filesVersion,\n changes,\n printLimit,\n }: {\n expectedFilesVersion?: bigint;\n changes: Changes;\n printLimit?: number;\n }): Promise<void> {\n this.log.debug(\"sending changes to gadget\", { expectedFilesVersion, changes });\n const changed: FileSyncChangedEventInput[] = [];\n const deleted: FileSyncDeletedEventInput[] = [];\n\n await pMap(changes, async ([normalizedPath, change]) => {\n if (change.type === \"delete\") {\n deleted.push({ path: normalizedPath });\n return;\n }\n\n const absolutePath = this.directory.absolute(normalizedPath);\n\n let stats;\n try {\n stats = await fs.stat(absolutePath);\n } catch (error) {\n swallowEnoent(error);\n this.log.debug(\"skipping change because file doesn't exist\", { path: normalizedPath });\n return;\n }\n\n let content = \"\";\n if (stats.isFile()) {\n content = await fs.readFile(absolutePath, FileSyncEncoding.Base64);\n }\n\n let oldPath;\n if (change.type === \"create\" && change.oldPath) {\n oldPath = change.oldPath;\n }\n\n changed.push({\n content,\n oldPath,\n path: normalizedPath,\n mode: stats.mode,\n encoding: FileSyncEncoding.Base64,\n });\n });\n\n if (changed.length === 0 && deleted.length === 0) {\n this.log.debug(\"skipping send because there are no changes\");\n return;\n }\n\n const {\n publishFileSyncEvents: { remoteFilesVersion },\n } = await this.editGraphQL.query({\n query: PUBLISH_FILE_SYNC_EVENTS_MUTATION,\n variables: {\n input: {\n expectedRemoteFilesVersion: String(expectedFilesVersion),\n changed,\n deleted,\n },\n },\n });\n\n await this._save(remoteFilesVersion);\n\n printChanges({\n changes,\n tense: \"past\",\n message: sprint`→ Sent {gray ${dayjs().format(\"hh:mm:ss A\")}}`,\n limit: printLimit,\n });\n }\n\n private async _writeToLocalFilesystem(options: { filesVersion: bigint | string; files: File[]; delete: string[] }): Promise<Changes> {\n const filesVersion = BigInt(options.filesVersion);\n assert(filesVersion >= this.filesVersion, \"filesVersion must be greater than or equal to current filesVersion\");\n\n this.log.debug(\"writing to local filesystem\", {\n filesVersion,\n files: options.files.map((file) => file.path),\n delete: options.delete,\n });\n\n const created: string[] = [];\n const updated: string[] = [];\n\n await pMap(options.delete, async (filepath) => {\n const currentPath = this.directory.absolute(filepath);\n const backupPath = this.directory.absolute(\".gadget/backup\", this.directory.relative(filepath));\n\n // rather than `rm -rf`ing files, we move them to\n // `.gadget/backup/` so that users can recover them if something\n // goes wrong. We've seen a lot of EBUSY/EINVAL errors when moving\n // files so we retry a few times.\n await pRetry(\n async () => {\n try {\n // remove the current backup file in case it exists and is a\n // different type (file vs directory)\n await fs.remove(backupPath);\n await fs.move(currentPath, backupPath);\n } catch (error) {\n // replicate the behavior of `rm -rf` and ignore ENOENT\n swallowEnoent(error);\n }\n },\n {\n retries: 2,\n minTimeout: ms(\"100ms\"),\n onFailedAttempt: (error) => {\n this.log.warn(\"failed to move file to backup\", { error, currentPath, backupPath });\n },\n },\n );\n });\n\n await pMap(options.files, async (file) => {\n const absolutePath = this.directory.absolute(file.path);\n if (await fs.pathExists(absolutePath)) {\n updated.push(file.path);\n } else {\n created.push(file.path);\n }\n\n if (file.path.endsWith(\"/\")) {\n await fs.ensureDir(absolutePath);\n } else {\n await fs.outputFile(absolutePath, Buffer.from(file.content, file.encoding));\n }\n\n if (supportsPermissions) {\n // the os's default umask makes setting the mode during creation\n // not work, so an additional fs.chmod call is necessary to\n // ensure the file has the correct mode\n await fs.chmod(absolutePath, file.mode & 0o777);\n }\n\n if (absolutePath === this.directory.absolute(\".ignore\")) {\n await this.directory.loadIgnoreFile();\n }\n });\n\n await this._save(String(filesVersion));\n\n return new Changes([\n ...created.map((path) => [path, { type: \"create\" }] as const),\n ...updated.map((path) => [path, { type: \"update\" }] as const),\n ...options.delete.map((path) => [path, { type: \"delete\" }] as const),\n ]);\n }\n\n /**\n * Updates {@linkcode _state} and saves it to `.gadget/sync.json`.\n */\n private async _save(filesVersion: string | bigint): Promise<void> {\n this._state = { ...this._state, mtime: Date.now() + 1, filesVersion: String(filesVersion) };\n this.log.debug(\"saving state\", { state: this._state });\n await fs.outputJSON(this.directory.absolute(\".gadget/sync.json\"), this._state, { spaces: 2 });\n }\n}\n\n/**\n * Checks if a directory is empty or non-existent.\n *\n * @param dir - The directory path to check.\n * @returns A Promise that resolves to a boolean indicating whether the directory is empty or non-existent.\n */\nexport const isEmptyOrNonExistentDir = async (dir: string): Promise<boolean> => {\n try {\n for await (const _ of await fs.opendir(dir, { bufferSize: 1 })) {\n return false;\n }\n return true;\n } catch (error) {\n swallowEnoent(error);\n return true;\n }\n};\n\nexport const assertAllGadgetFiles = ({ gadgetChanges }: { gadgetChanges: Changes }): void => {\n assert(\n gadgetChanges.created().length > 0 || gadgetChanges.deleted().length > 0 || gadgetChanges.updated().length > 0,\n \"expected gadgetChanges to have changes\",\n );\n\n const allGadgetFiles = Array.from(gadgetChanges.keys()).every((path) => path.startsWith(\".gadget/\"));\n assert(allGadgetFiles, \"expected all gadgetChanges to be .gadget/ files\");\n};\n\nexport const ConflictPreference = Object.freeze({\n CANCEL: \"Cancel (Ctrl+C)\",\n LOCAL: \"Keep my conflicting changes\",\n GADGET: \"Keep Gadget's conflicting changes\",\n});\n\nexport type ConflictPreference = (typeof ConflictPreference)[keyof typeof ConflictPreference];\n\nexport const ConflictPreferenceArg = (value: string, name: string): ConflictPreference => {\n if ([\"local\", \"gadget\"].includes(value)) {\n return ConflictPreference[value.toUpperCase() as keyof typeof ConflictPreference];\n }\n\n throw new ArgError(sprint`\n ${name} must be {bold local} or {bold gadget}\n\n {bold EXAMPLES:}\n ${name} local\n ${name} gadget\n `);\n};\n"],"names":["dayjs","findUp","fs","ms","assert","path","process","pMap","PQueue","pRetry","z","FileSyncEncoding","getApps","EditGraphQL","FILE_SYNC_COMPARISON_HASHES_QUERY","FILE_SYNC_FILES_QUERY","FILE_SYNC_HASHES_QUERY","PUBLISH_FILE_SYNC_EVENTS_MUTATION","REMOTE_FILE_SYNC_EVENTS_SUBSCRIPTION","ArgError","config","homePath","createLogger","select","sprint","sortBySimilar","noop","Changes","printChanges","getConflicts","printConflicts","withoutConflictingChanges","Directory","supportsPermissions","swallowEnoent","InvalidSyncFileError","TooManySyncAttemptsError","getChanges","isEqualHashes","log","name","FileSync","filesVersion","BigInt","_state","mtime","init","options","apps","user","length","email","dir","filepath","join","cwd","windows","startsWith","slice","wasEmptyOrNonExistent","isEmptyOrNonExistentDir","ensureDir","resolve","state","readJson","then","json","object","app","string","number","parse","catch","appSlug","message","choices","map","x","slug","find","similarAppSlugs","concat","directory","force","idle","_syncOperations","onIdle","sendChangesToGadget","changes","add","_sendChangesToGadget","subscribeToGadgetChanges","beforeChanges","afterChanges","onError","editGraphQL","subscribe","query","variables","localFilesVersion","String","onData","remoteFileSyncEvents","changed","deleted","remoteFilesVersion","warn","debug","change","filterIgnoredFiles","file","ignored","ignores","filter","_save","_writeToLocalFilesystem","files","delete","size","format","tense","limit","sync","preference","maxAttempts","pause","attempt","inSync","hashes","info","gadgetFilesVersion","_sync","start","filesVersionHashes","localHashes","gadgetHashes","localChanges","from","to","existing","ignore","gadgetChanges","assertAllGadgetFiles","conflicts","Object","values","ConflictPreference","CANCEL","exit","LOCAL","GADGET","_getChangesFromGadget","expectedFilesVersion","Promise","all","fileSyncHashes","fileSyncComparisonHashes","latestFilesVersionHashes","created","updated","fileSyncFiles","paths","encoding","Base64","printLimit","normalizedPath","type","push","absolutePath","absolute","stats","stat","error","content","isFile","readFile","oldPath","mode","publishFileSyncEvents","input","expectedRemoteFilesVersion","currentPath","backupPath","relative","remove","move","retries","minTimeout","onFailedAttempt","pathExists","endsWith","outputFile","Buffer","chmod","loadIgnoreFile","Date","now","outputJSON","spaces","extend","concurrency","_","opendir","bufferSize","allGadgetFiles","Array","keys","every","freeze","ConflictPreferenceArg","value","includes","toUpperCase"],"mappings":";AAAA,OAAOA,WAAW,QAAQ;AAC1B,SAASC,MAAM,QAAQ,UAAU;AACjC,OAAOC,QAAQ,WAAW;AAC1B,OAAOC,QAAQ,KAAK;AACpB,OAAOC,YAAY,cAAc;AACjC,OAAOC,UAAU,YAAY;AAC7B,OAAOC,aAAa,eAAe;AACnC,OAAOC,UAAU,QAAQ;AACzB,OAAOC,YAAY,UAAU;AAC7B,OAAOC,YAAY,UAAU;AAE7B,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,gBAAgB,QAAwE,iCAAiC;AAElI,SAASC,OAAO,QAAQ,gBAAgB;AACxC,SACEC,WAAW,EACXC,iCAAiC,EACjCC,qBAAqB,EACrBC,sBAAsB,EACtBC,iCAAiC,EACjCC,oCAAoC,QAC/B,yBAAyB;AAChC,SAASC,QAAQ,QAAQ,oBAAoB;AAC7C,SAASC,MAAM,EAAEC,QAAQ,QAAQ,sBAAsB;AACvD,SAASC,YAAY,QAAQ,0BAA0B;AACvD,SAASC,MAAM,QAAQ,sBAAsB;AAC7C,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,aAAa,QAAQ,wBAAwB;AACtD,SAASC,IAAI,QAAQ,sBAAsB;AAC3C,SAASC,OAAO,EAAEC,YAAY,QAAQ,eAAe;AACrD,SAASC,YAAY,EAAEC,cAAc,EAAEC,yBAAyB,QAAQ,iBAAiB;AACzF,SAASC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,QAAqB,iBAAiB;AAC5F,SAASC,oBAAoB,EAAEC,wBAAwB,QAAQ,aAAa;AAE5E,SAASC,UAAU,EAAEC,aAAa,QAA8B,cAAc;AAE9E,MAAM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];
|
|
142
142
|
if (!bHash || !isEqualHash(aPath, aHash, bHash)) {
|
|
143
|
-
log.
|
|
143
|
+
log.debug("hashes are not equal", {
|
|
144
144
|
path: aPath,
|
|
145
145
|
aHash,
|
|
146
146
|
bHash
|
|
@@ -150,7 +150,7 @@ export const isEqualHashes = (a, b)=>{
|
|
|
150
150
|
}
|
|
151
151
|
for (const bPath of Object.keys(b)){
|
|
152
152
|
if (!a[bPath]) {
|
|
153
|
-
log.
|
|
153
|
+
log.debug("hashes are not equal", {
|
|
154
154
|
path: bPath,
|
|
155
155
|
aHash: undefined,
|
|
156
156
|
bHash: b[bPath]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/filesync/hashes.ts"],"sourcesContent":["import assert from \"node:assert\";\nimport { createLogger } from \"../output/log/logger.js\";\nimport { isNil } from \"../util/is.js\";\nimport { type Create, type Delete, type Update } from \"./changes.js\";\nimport type { Hash, Hashes } from \"./directory.js\";\n\nconst log = createLogger({ name: \"hashes\" });\n\nexport type CreateWithHash = Create & { targetHash: Hash };\nexport type UpdateWithHash = Update & { sourceHash: Hash; targetHash: Hash };\nexport type DeleteWithHash = Delete & { sourceHash: Hash };\nexport type ChangeWithHash = CreateWithHash | UpdateWithHash | DeleteWithHash;\n\nexport class ChangesWithHash extends Map<string, ChangeWithHash> {\n created(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"create\")\n .map(([path]) => path);\n }\n\n updated(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"update\")\n .map(([path]) => path);\n }\n\n deleted(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"delete\")\n .map(([path]) => path);\n }\n}\n\n/**\n * Calculates the changes that were made to `from` to make it end up as `to`.\n *\n * If `existing` is provided, only the changes that are necessary to\n * apply to `existing` are returned.\n *\n * If `ignore` is provided, any changes that were made to a path that\n * starts with any of the `ignore` paths are skipped.\n */\nexport const getChanges = ({\n from: source,\n to: target,\n existing,\n ignore,\n}: {\n from: Hashes;\n to: Hashes;\n existing?: Hashes;\n ignore?: string[];\n}): ChangesWithHash => {\n const changes = new ChangesWithHash();\n const targetPaths = Object.keys(target);\n\n for (const [sourcePath, sourceHash] of Object.entries(source)) {\n if (ignore?.some((ignored) => sourcePath.startsWith(ignored))) {\n continue;\n }\n\n const targetHash = target[sourcePath];\n if (!targetHash) {\n if (!sourcePath.endsWith(\"/\") || !targetPaths.some((targetPath) => targetPath.startsWith(sourcePath))) {\n // sourcePath is a file and it doesn't exist in target OR\n // sourcePath is a directory and target doesn't have any\n // existing files inside it, therefor the sourcePath has been\n // deleted\n changes.set(sourcePath, { type: \"delete\", sourceHash });\n log.trace(\"file deleted\", { path: sourcePath, sourceHash });\n }\n } else if (!isEqualHash(sourcePath, sourceHash, targetHash)) {\n // the file or directory exists in target, but has a different\n // hash, so it's been updated\n changes.set(sourcePath, { type: \"update\", sourceHash, targetHash });\n log.trace(\"file updated\", { path: sourcePath, sourceHash, targetHash });\n }\n }\n\n for (const targetPath of targetPaths) {\n if (ignore?.some((ignored) => targetPath.startsWith(ignored))) {\n continue;\n }\n\n if (!source[targetPath]) {\n // the targetPath doesn't exist in source, so it's been created\n const targetHash = target[targetPath];\n assert(targetHash, \"targetHash should exist\");\n\n changes.set(targetPath, { type: \"create\", targetHash });\n log.trace(\"file created\", { path: targetPath, targetHash });\n }\n }\n\n if (!existing) {\n return changes;\n }\n\n return withoutUnnecessaryChanges({ changes, existing });\n};\n\n/**\n * Filters out changes that the existing filesystem already has.\n */\nexport const withoutUnnecessaryChanges = ({ changes, existing }: { changes: ChangesWithHash; existing: Hashes }): ChangesWithHash => {\n const necessaryChanges = new ChangesWithHash();\n\n for (const [path, change] of changes) {\n const existingHash = existing[path];\n if (change.type === \"delete\" && !existingHash) {\n // already deleted\n log.trace(\"already deleted\", { path });\n continue;\n }\n\n if (change.type !== \"delete\" && existingHash && isEqualHash(path, change.targetHash, existingHash)) {\n // already created or updated\n log.trace(\"already created or updated\", { path, existingHash, targetHash: change.targetHash });\n continue;\n }\n\n // we could do this:\n // if (change.type === \"update\" && !existingHash) {\n // change = { type: \"create\", targetHash: change.targetHash };\n // }\n // but, changing the type makes the output look confusing and it\n // doesn't change the outcome, so we just leave it as is\n\n necessaryChanges.set(path, change);\n }\n\n return necessaryChanges;\n};\n\nexport const isEqualHash = (path: string, aHash: Hash, bHash: Hash): boolean => {\n if (aHash.sha1 !== bHash.sha1) {\n // the contents are different\n return false;\n }\n\n if (path.endsWith(\"/\")) {\n // it's a directory, so we don't care about permissions\n return true;\n }\n\n if (isNil(aHash.permissions) || isNil(bHash.permissions)) {\n // one of the filesystems doesn't support permissions, so ignore them\n return true;\n }\n\n // the contents are the same, and both filesystems support permissions\n // so ensure the permissions are also the same\n return aHash.permissions === bHash.permissions;\n};\n\nexport const isEqualHashes = (a: Hashes, b: Hashes): boolean => {\n for (const [aPath, aHash] of Object.entries(a)) {\n const bHash = b[aPath];\n if (!bHash || !isEqualHash(aPath, aHash, bHash)) {\n log.
|
|
1
|
+
{"version":3,"sources":["../../../src/services/filesync/hashes.ts"],"sourcesContent":["import assert from \"node:assert\";\nimport { createLogger } from \"../output/log/logger.js\";\nimport { isNil } from \"../util/is.js\";\nimport { type Create, type Delete, type Update } from \"./changes.js\";\nimport type { Hash, Hashes } from \"./directory.js\";\n\nconst log = createLogger({ name: \"hashes\" });\n\nexport type CreateWithHash = Create & { targetHash: Hash };\nexport type UpdateWithHash = Update & { sourceHash: Hash; targetHash: Hash };\nexport type DeleteWithHash = Delete & { sourceHash: Hash };\nexport type ChangeWithHash = CreateWithHash | UpdateWithHash | DeleteWithHash;\n\nexport class ChangesWithHash extends Map<string, ChangeWithHash> {\n created(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"create\")\n .map(([path]) => path);\n }\n\n updated(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"update\")\n .map(([path]) => path);\n }\n\n deleted(): string[] {\n return Array.from(this.entries())\n .filter(([, change]) => change.type === \"delete\")\n .map(([path]) => path);\n }\n}\n\n/**\n * Calculates the changes that were made to `from` to make it end up as `to`.\n *\n * If `existing` is provided, only the changes that are necessary to\n * apply to `existing` are returned.\n *\n * If `ignore` is provided, any changes that were made to a path that\n * starts with any of the `ignore` paths are skipped.\n */\nexport const getChanges = ({\n from: source,\n to: target,\n existing,\n ignore,\n}: {\n from: Hashes;\n to: Hashes;\n existing?: Hashes;\n ignore?: string[];\n}): ChangesWithHash => {\n const changes = new ChangesWithHash();\n const targetPaths = Object.keys(target);\n\n for (const [sourcePath, sourceHash] of Object.entries(source)) {\n if (ignore?.some((ignored) => sourcePath.startsWith(ignored))) {\n continue;\n }\n\n const targetHash = target[sourcePath];\n if (!targetHash) {\n if (!sourcePath.endsWith(\"/\") || !targetPaths.some((targetPath) => targetPath.startsWith(sourcePath))) {\n // sourcePath is a file and it doesn't exist in target OR\n // sourcePath is a directory and target doesn't have any\n // existing files inside it, therefor the sourcePath has been\n // deleted\n changes.set(sourcePath, { type: \"delete\", sourceHash });\n log.trace(\"file deleted\", { path: sourcePath, sourceHash });\n }\n } else if (!isEqualHash(sourcePath, sourceHash, targetHash)) {\n // the file or directory exists in target, but has a different\n // hash, so it's been updated\n changes.set(sourcePath, { type: \"update\", sourceHash, targetHash });\n log.trace(\"file updated\", { path: sourcePath, sourceHash, targetHash });\n }\n }\n\n for (const targetPath of targetPaths) {\n if (ignore?.some((ignored) => targetPath.startsWith(ignored))) {\n continue;\n }\n\n if (!source[targetPath]) {\n // the targetPath doesn't exist in source, so it's been created\n const targetHash = target[targetPath];\n assert(targetHash, \"targetHash should exist\");\n\n changes.set(targetPath, { type: \"create\", targetHash });\n log.trace(\"file created\", { path: targetPath, targetHash });\n }\n }\n\n if (!existing) {\n return changes;\n }\n\n return withoutUnnecessaryChanges({ changes, existing });\n};\n\n/**\n * Filters out changes that the existing filesystem already has.\n */\nexport const withoutUnnecessaryChanges = ({ changes, existing }: { changes: ChangesWithHash; existing: Hashes }): ChangesWithHash => {\n const necessaryChanges = new ChangesWithHash();\n\n for (const [path, change] of changes) {\n const existingHash = existing[path];\n if (change.type === \"delete\" && !existingHash) {\n // already deleted\n log.trace(\"already deleted\", { path });\n continue;\n }\n\n if (change.type !== \"delete\" && existingHash && isEqualHash(path, change.targetHash, existingHash)) {\n // already created or updated\n log.trace(\"already created or updated\", { path, existingHash, targetHash: change.targetHash });\n continue;\n }\n\n // we could do this:\n // if (change.type === \"update\" && !existingHash) {\n // change = { type: \"create\", targetHash: change.targetHash };\n // }\n // but, changing the type makes the output look confusing and it\n // doesn't change the outcome, so we just leave it as is\n\n necessaryChanges.set(path, change);\n }\n\n return necessaryChanges;\n};\n\nexport const isEqualHash = (path: string, aHash: Hash, bHash: Hash): boolean => {\n if (aHash.sha1 !== bHash.sha1) {\n // the contents are different\n return false;\n }\n\n if (path.endsWith(\"/\")) {\n // it's a directory, so we don't care about permissions\n return true;\n }\n\n if (isNil(aHash.permissions) || isNil(bHash.permissions)) {\n // one of the filesystems doesn't support permissions, so ignore them\n return true;\n }\n\n // the contents are the same, and both filesystems support permissions\n // so ensure the permissions are also the same\n return aHash.permissions === bHash.permissions;\n};\n\nexport const isEqualHashes = (a: Hashes, b: Hashes): boolean => {\n for (const [aPath, aHash] of Object.entries(a)) {\n const bHash = b[aPath];\n if (!bHash || !isEqualHash(aPath, aHash, bHash)) {\n log.debug(\"hashes are not equal\", { path: aPath, aHash, bHash });\n return false;\n }\n }\n\n for (const bPath of Object.keys(b)) {\n if (!a[bPath]) {\n log.debug(\"hashes are not equal\", { path: bPath, aHash: undefined, bHash: b[bPath] });\n return false;\n }\n }\n\n return true;\n};\n"],"names":["assert","createLogger","isNil","log","name","ChangesWithHash","Map","created","Array","from","entries","filter","change","type","map","path","updated","deleted","getChanges","source","to","target","existing","ignore","changes","targetPaths","Object","keys","sourcePath","sourceHash","some","ignored","startsWith","targetHash","endsWith","targetPath","set","trace","isEqualHash","withoutUnnecessaryChanges","necessaryChanges","existingHash","a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D,CAAC,CAACI,MAAM,EAAE;YACbhD,IAAI+C,KAAK,CAAC,wBAAwB;gBAAEnC,MAAMoC;gBAAOT,OAAOU;gBAAWT,OAAOK,CAAC,CAACG,MAAM;YAAC;YACnF,OAAO;QACT;IACF;IAEA,OAAO;AACT,EAAE"}
|
|
@@ -80,7 +80,10 @@ const formatFields = (fields, indent = 2)=>{
|
|
|
80
80
|
}
|
|
81
81
|
value = Object.fromEntries(value.entries());
|
|
82
82
|
}
|
|
83
|
-
if (
|
|
83
|
+
if (value instanceof Map) {
|
|
84
|
+
value = Object.fromEntries(value);
|
|
85
|
+
}
|
|
86
|
+
if (isObject(value)) {
|
|
84
87
|
const entries = Object.entries(value);
|
|
85
88
|
if (entries.length === 0) {
|
|
86
89
|
buf.push(formatValue(" {}", gray, indent));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/services/output/log/format/pretty.ts"],"sourcesContent":["import chalk, { Chalk } from \"chalk\";\nimport dayjs from \"dayjs\";\nimport assert from \"node:assert\";\nimport { config } from \"../../../config/config.js\";\nimport { env } from \"../../../config/env.js\";\nimport { isObject } from \"../../../util/is.js\";\nimport { Level } from \"../level.js\";\nimport type { Formatter } from \"./format.js\";\n\nexport const formatPretty: Formatter = (level, name, msg, fields) => {\n return `${formatTimestamp()} ${formatLevel(level)} ${formatName(name)}:${formatMessage(msg)}${formatFields(fields)}${NEW_LINE}`;\n};\n\nconst color = new Chalk({\n // we always turn off colors in tests (FORCE_COLOR=0) so that we get\n // predictable output, but if we're running with logs enabled\n // (GGT_LOG_LEVEL=info), we still want to see colors in our logs\n level: env.testLike && config.logLevel < Level.PRINT ? 3 : chalk.level,\n});\n\nconst blue = color.hex(\"#86B5F7\");\nconst blueLight = color.hex(\"#B2D0FA\");\nconst gray = color.hex(\"#D6D6D6\");\nconst grayDark = color.hex(\"#C2C2C2\");\nconst green = color.hex(\"#9DE6A4\");\nconst greenLight = color.hex(\"#BEEEC3\");\nconst orange = color.hex(\"#EEAC78\");\nconst orangeLight = color.hex(\"#F4C7A4\");\nconst pink = color.hex(\"#FAACB5\");\nconst red = color.hex(\"#A64E4E\");\nconst white = color.hex(\"#FFFFFF\");\n\nconst EMPTY = \"\";\nconst SPACE = \" \";\nconst NEW_LINE = \"\\n\";\nconst COLON = \":\";\nconst QUOTE = \"'\";\n\nconst formatKey = (key: string, indent: number): string => {\n const color = key === \"error\" ? red : gray;\n\n const buf: string[] = [];\n buf.push(NEW_LINE);\n for (let i = 0; i < indent; i++) {\n buf.push(SPACE);\n }\n buf.push(color(key));\n buf.push(COLON);\n\n return buf.join(\"\");\n};\n\nconst formatValue = (value: string, color: (s: string) => string, indent: number): string => {\n const lines = value.split(NEW_LINE);\n if (lines.length === 0) {\n return EMPTY;\n }\n\n const buf: string[] = [];\n const firstLine = lines.shift();\n assert(firstLine);\n buf.push(color(firstLine));\n\n // color the rest of the lines\n for (const line of lines) {\n if (!line) {\n continue;\n }\n\n buf.push(NEW_LINE);\n for (let i = 0; i < indent; i++) {\n buf.push(SPACE);\n }\n\n buf.push(color(line));\n }\n\n return buf.join(EMPTY);\n};\n\nconst formatFields = (fields: Record<string, unknown>, indent = 2): string => {\n if (Object.keys(fields).length === 0) {\n return EMPTY;\n }\n\n const buf: string[] = [];\n for (let [key, value] of Object.entries(fields)) {\n buf.push(formatKey(key, indent));\n\n if (value instanceof Set) {\n value = Array.from(value);\n }\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n buf.push(formatValue(\" []\", gray, indent));\n continue;\n }\n\n value = Object.fromEntries(value.entries());\n }\n\n if (
|
|
1
|
+
{"version":3,"sources":["../../../../../src/services/output/log/format/pretty.ts"],"sourcesContent":["import chalk, { Chalk } from \"chalk\";\nimport dayjs from \"dayjs\";\nimport assert from \"node:assert\";\nimport { config } from \"../../../config/config.js\";\nimport { env } from \"../../../config/env.js\";\nimport { isObject } from \"../../../util/is.js\";\nimport { Level } from \"../level.js\";\nimport type { Formatter } from \"./format.js\";\n\nexport const formatPretty: Formatter = (level, name, msg, fields) => {\n return `${formatTimestamp()} ${formatLevel(level)} ${formatName(name)}:${formatMessage(msg)}${formatFields(fields)}${NEW_LINE}`;\n};\n\nconst color = new Chalk({\n // we always turn off colors in tests (FORCE_COLOR=0) so that we get\n // predictable output, but if we're running with logs enabled\n // (GGT_LOG_LEVEL=info), we still want to see colors in our logs\n level: env.testLike && config.logLevel < Level.PRINT ? 3 : chalk.level,\n});\n\nconst blue = color.hex(\"#86B5F7\");\nconst blueLight = color.hex(\"#B2D0FA\");\nconst gray = color.hex(\"#D6D6D6\");\nconst grayDark = color.hex(\"#C2C2C2\");\nconst green = color.hex(\"#9DE6A4\");\nconst greenLight = color.hex(\"#BEEEC3\");\nconst orange = color.hex(\"#EEAC78\");\nconst orangeLight = color.hex(\"#F4C7A4\");\nconst pink = color.hex(\"#FAACB5\");\nconst red = color.hex(\"#A64E4E\");\nconst white = color.hex(\"#FFFFFF\");\n\nconst EMPTY = \"\";\nconst SPACE = \" \";\nconst NEW_LINE = \"\\n\";\nconst COLON = \":\";\nconst QUOTE = \"'\";\n\nconst formatKey = (key: string, indent: number): string => {\n const color = key === \"error\" ? red : gray;\n\n const buf: string[] = [];\n buf.push(NEW_LINE);\n for (let i = 0; i < indent; i++) {\n buf.push(SPACE);\n }\n buf.push(color(key));\n buf.push(COLON);\n\n return buf.join(\"\");\n};\n\nconst formatValue = (value: string, color: (s: string) => string, indent: number): string => {\n const lines = value.split(NEW_LINE);\n if (lines.length === 0) {\n return EMPTY;\n }\n\n const buf: string[] = [];\n const firstLine = lines.shift();\n assert(firstLine);\n buf.push(color(firstLine));\n\n // color the rest of the lines\n for (const line of lines) {\n if (!line) {\n continue;\n }\n\n buf.push(NEW_LINE);\n for (let i = 0; i < indent; i++) {\n buf.push(SPACE);\n }\n\n buf.push(color(line));\n }\n\n return buf.join(EMPTY);\n};\n\nconst formatFields = (fields: Record<string, unknown>, indent = 2): string => {\n if (Object.keys(fields).length === 0) {\n return EMPTY;\n }\n\n const buf: string[] = [];\n for (let [key, value] of Object.entries(fields)) {\n buf.push(formatKey(key, indent));\n\n if (value instanceof Set) {\n value = Array.from(value);\n }\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n buf.push(formatValue(\" []\", gray, indent));\n continue;\n }\n\n value = Object.fromEntries(value.entries());\n }\n\n if (value instanceof Map) {\n value = Object.fromEntries(value);\n }\n\n if (isObject(value)) {\n const entries = Object.entries(value);\n if (entries.length === 0) {\n buf.push(formatValue(\" {}\", gray, indent));\n continue;\n }\n\n if (entries.length > 10 && config.logLevel > Level.TRACE) {\n // truncate objects to 10 keys when not tracing\n value = Object.fromEntries([...entries.slice(0, 10), [\"…\", `${entries.length - 10} more`]]);\n }\n\n buf.push(formatFields(value as Record<string, unknown>, indent + 2));\n continue;\n }\n\n buf.push(SPACE);\n\n switch (typeof value) {\n case \"string\":\n buf.push(formatValue(QUOTE + value.replaceAll(NEW_LINE, NEW_LINE + SPACE.repeat(indent + key.length)) + QUOTE, blueLight, indent));\n break;\n case \"number\":\n buf.push(formatValue(String(value), orangeLight, indent));\n break;\n case \"bigint\":\n buf.push(formatValue(String(value) + \"n\", orangeLight, indent));\n break;\n case \"boolean\":\n buf.push(formatValue(String(value), greenLight, indent));\n break;\n default:\n buf.push(formatValue(String(value), white, indent));\n break;\n }\n }\n\n return buf.join(EMPTY);\n};\n\nconst formatTimestamp = (): string => {\n const ts = dayjs().format(\"hh:mm:ss\");\n return grayDark(ts);\n};\n\nconst formatLevel = (level: Level): string => {\n switch (level) {\n case Level.PRINT:\n return gray(\"PRINT\");\n case Level.TRACE:\n return blue(\"TRACE\");\n case Level.DEBUG:\n return orange(\"DEBUG\");\n case Level.INFO:\n return green(\"INFO\");\n case Level.WARN:\n return pink(\"WARN\");\n case Level.ERROR:\n return red(\"ERROR\");\n // case \"fatal\":\n // return red(colors.bold(level));\n }\n};\n\nconst formatName = (name: string): string => {\n return white(name);\n};\n\nconst formatMessage = (msg: string): string => {\n const lines = msg.split(NEW_LINE);\n if (lines.length === 1) {\n return SPACE + white(msg);\n }\n return NEW_LINE + lines.map((line) => SPACE + SPACE + line).join(NEW_LINE);\n};\n"],"names":["chalk","Chalk","dayjs","assert","config","env","isObject","Level","formatPretty","level","name","msg","fields","formatTimestamp","formatLevel","formatName","formatMessage","formatFields","NEW_LINE","color","testLike","logLevel","PRINT","blue","hex","blueLight","gray","grayDark","green","greenLight","orange","orangeLight","pink","red","white","EMPTY","SPACE","COLON","QUOTE","formatKey","key","indent","buf","push","i","join","formatValue","value","lines","split","length","firstLine","shift","line","Object","keys","entries","Set","Array","from","isArray","fromEntries","Map","TRACE","slice","replaceAll","repeat","String","ts","format","DEBUG","INFO","WARN","ERROR","map"],"mappings":"AAAA,OAAOA,SAASC,KAAK,QAAQ,QAAQ;AACrC,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,YAAY,cAAc;AACjC,SAASC,MAAM,QAAQ,4BAA4B;AACnD,SAASC,GAAG,QAAQ,yBAAyB;AAC7C,SAASC,QAAQ,QAAQ,sBAAsB;AAC/C,SAASC,KAAK,QAAQ,cAAc;AAGpC,OAAO,MAAMC,eAA0B,CAACC,OAAOC,MAAMC,KAAKC;IACxD,OAAO,CAAC,EAAEC,kBAAkB,CAAC,EAAEC,YAAYL,OAAO,CAAC,EAAEM,WAAWL,MAAM,CAAC,EAAEM,cAAcL,KAAK,EAAEM,aAAaL,QAAQ,EAAEM,SAAS,CAAC;AACjI,EAAE;AAEF,MAAMC,QAAQ,IAAIlB,MAAM;IACtB,oEAAoE;IACpE,6DAA6D;IAC7D,gEAAgE;IAChEQ,OAAOJ,IAAIe,QAAQ,IAAIhB,OAAOiB,QAAQ,GAAGd,MAAMe,KAAK,GAAG,IAAItB,MAAMS,KAAK;AACxE;AAEA,MAAMc,OAAOJ,MAAMK,GAAG,CAAC;AACvB,MAAMC,YAAYN,MAAMK,GAAG,CAAC;AAC5B,MAAME,OAAOP,MAAMK,GAAG,CAAC;AACvB,MAAMG,WAAWR,MAAMK,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