@gadgetinc/ggt 0.1.8 → 0.1.10

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.
@@ -1 +1 @@
1
- {"version":3,"file":"base-command.js","sourceRoot":"","sources":["../../src/utils/base-command.ts"],"names":[],"mappings":";;;;AACA,sCAAuD;AACvD,mDAAmD;AACnD,0DAA0B;AAC1B,gEAA+B;AAE/B,+BAAoC;AACpC,uCAAkC;AAElC,iDAAuC;AAMvC,wDAAwB;AACxB,wDAAwB;AACxB,uCAAqD;AACrD,qCAAsE;AAEtE,MAAsB,WAAY,SAAQ,cAAO;IAsB/C,YAAY,IAAc,EAAE,MAAc;QACxC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAPtB;;;WAGG;QACH;;;;mBAAgC,KAAK;WAAC;QAKpC,sGAAsG;QACtG,mJAAmJ;QACnJ,kGAAkG;QAClG,IAAI,CAAC,IAAI,CAAC,KAAK,GAAG,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,WAAW,CAAC,WAAW,EAAE,CAAC;IACvE,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACd,OAAO,CAAC,CAAC,eAAQ,CAAC,KAAK,CAAC;IAC1B,CAAC;IAEQ,KAAK,CAAC,IAAI;QACjB,MAAM,KAAK,CAAC,IAAI,EAAE,CAAC;QACnB,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,WAAW,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;QAE5F,6GAA6G;QAC7G,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,IAAI,KAAK,CAAC,KAAK,EAAE;YACf,eAAQ,CAAC,KAAK,GAAG,IAAI,CAAC;YACtB,eAAK,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,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sC;YAC/C,SAAS,EAAE,QAAQ;YACnB,OAAO,EAAE,KAAK;SACf,CAAC;KACH;GAAC","sourcesContent":["import type { Config } from \"@oclif/core\";\nimport { Command, Flags, settings } from \"@oclif/core\";\nimport { ExitError } from \"@oclif/core/lib/errors\";\nimport Debug from \"debug\";\nimport getPort from \"get-port\";\nimport type { Server } from \"http\";\nimport { createServer } from \"http\";\nimport { prompt } from \"inquirer\";\nimport type { Notification } from \"node-notifier\";\nimport { notify } from \"node-notifier\";\nimport type WindowsBalloon from \"node-notifier/notifiers/balloon\";\nimport type Growl from \"node-notifier/notifiers/growl\";\nimport type NotificationCenter from \"node-notifier/notifiers/notificationcenter\";\nimport type NotifySend from \"node-notifier/notifiers/notifysend\";\nimport type WindowsToaster from \"node-notifier/notifiers/toaster\";\nimport open from \"open\";\nimport path from \"path\";\nimport { context, GADGET_ENDPOINT } from \"./context\";\nimport { BaseError, UnexpectedError as UnknownError } from \"./errors\";\n\nexport abstract class BaseCommand extends Command {\n /**\n * Determines how high the command is listed in the README. The lower the number, the higher the command is listed. Equal numbers are\n * sorted alphabetically.\n */\n static priority = Infinity;\n\n static override globalFlags = {\n debug: Flags.boolean({\n char: \"D\",\n summary: \"Whether to output debug information.\",\n helpGroup: \"global\",\n default: false,\n }),\n };\n\n /**\n * Determines whether the command requires the user to be logged in or not.\n * If true and the user is not logged in, the user will be prompted to login before the command is run.\n */\n readonly requireUser: boolean = false;\n\n constructor(argv: string[], config: Config) {\n super(argv, config);\n\n // TODO: Remove this once the `@oclif/core` warnIfFlagDeprecated function checks global flags as well.\n // warnIfFlagDeprecated throws a null pointer because it assumes all parsed flags are in the flags object (which is not the case for global flags).\n // https://github.com/oclif/core/blob/11c5752cec838d08bb27cd55f0f1aa2390df3c5e/src/command.ts#L259\n this.ctor.flags = { ...this.ctor.flags, ...BaseCommand.globalFlags };\n }\n\n /**\n * Indicates whether the command is being run with the `-D/--debug` flag.\n */\n get debugEnabled(): boolean {\n return !!settings.debug;\n }\n\n override async init(): Promise<void> {\n await super.init();\n const { flags, argv } = await this.parse({ flags: BaseCommand.globalFlags, strict: false });\n\n // remove global flags from argv so that when the implementation calls parse, it doesn't get confused by them\n this.argv = argv;\n\n if (flags.debug) {\n settings.debug = true;\n Debug.enable(`${this.config.bin}:*`);\n }\n\n context.config = this.config;\n\n if (this.requireUser && !(await context.getUser())) {\n const { login } = await prompt<{ login: boolean }>({\n type: \"confirm\",\n name: \"login\",\n message: \"You must be logged in to use this command. Would you like to log in?\",\n });\n\n if (!login) {\n return this.exit(0);\n }\n\n await this.login();\n }\n }\n\n /**\n * Sends a native OS notification to the user.\n *\n * @see {@link https://www.npmjs.com/package/node-notifier node-notifier}\n */\n notify(\n notification:\n | Notification\n | NotificationCenter.Notification\n | NotifySend.Notification\n | WindowsToaster.Notification\n | WindowsBalloon.Notification\n | Growl.Notification\n ): void {\n notify(\n {\n title: \"Gadget\",\n contentImage: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n icon: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n sound: true,\n timeout: false,\n ...notification,\n },\n (error) => {\n if (error) this.warn(error);\n }\n );\n }\n\n /**\n * Opens the Gadget login page in the user's default browser and waits for the user to login.\n */\n async login(): Promise<void> {\n let server: Server | undefined;\n\n try {\n const port = await getPort();\n const receiveSession = new Promise<void>((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n server = createServer(async (req, res) => {\n const redirectTo = new URL(`${GADGET_ENDPOINT}/auth/cli`);\n\n try {\n if (!req.url) throw new Error(\"missing url\");\n const incomingUrl = new URL(req.url, `http://localhost:${port}`);\n\n const value = incomingUrl.searchParams.get(\"session\");\n if (!value) throw new Error(\"missing session\");\n\n context.session = value;\n\n const user = await context.getUser();\n if (!user) throw new Error(\"missing current user\");\n\n if (user.name) {\n this.log(`Hello, ${user.name} (${user.email})`);\n } else {\n this.log(`Hello, ${user.email}`);\n }\n\n redirectTo.searchParams.set(\"success\", \"true\");\n resolve();\n } catch (error) {\n context.session = undefined;\n redirectTo.searchParams.set(\"success\", \"false\");\n reject(error);\n } finally {\n res.writeHead(303, { Location: redirectTo.toString() });\n res.end();\n }\n });\n\n server.listen(port);\n });\n\n const url = new URL(`${GADGET_ENDPOINT}/auth/login`);\n url.searchParams.set(\"returnTo\", `${GADGET_ENDPOINT}/auth/cli/callback?port=${port}`);\n await open(url.toString());\n\n this.log(\"Your browser has been opened. Please log in to your account.\");\n\n await receiveSession;\n } finally {\n server?.close();\n }\n }\n\n /**\n * Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called automatically by oclif when\n * an error is thrown during the `init` or `run` methods.\n */\n override async catch(cause: Error & { exitCode?: number }): Promise<never> {\n const error = cause instanceof BaseError ? cause : new UnknownError(cause);\n await error.capture();\n console.error(error.render());\n\n // The original implementation of `catch` re-throws the error so that it's caught and printed by oclif's `handle` method. We still want\n // to end up in oclif's `handle` method, but we don't want it to print the error again so we throw an ExitError instead. This will cause\n // `handle` to not print the error, but still exit with the correct exit code.\n //\n // catch: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/command.ts#L261\n // handle: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/errors/handle.ts#L15\n throw new ExitError(process.exitCode ?? cause.exitCode ?? 1);\n }\n}\n"]}
1
+ {"version":3,"file":"base-command.js","sourceRoot":"","sources":["../../src/utils/base-command.ts"],"names":[],"mappings":";;;;AACA,sCAAuD;AACvD,mDAAmD;AACnD,0DAA0B;AAC1B,0DAA0B;AAC1B,gEAA+B;AAE/B,+BAAoC;AACpC,uCAAkC;AAElC,iDAAuC;AAMvC,wDAAwB;AACxB,wDAAwB;AACxB,kEAA+B;AAC/B,uCAAqD;AACrD,qCAAsE;AAEtE,MAAsB,WAAY,SAAQ,cAAO;IAsB/C,YAAY,IAAc,EAAE,MAAc;QACxC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAPtB;;;WAGG;QACH;;;;mBAA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AA;;;;OAId,CAAC,CAAC;YAEH,MAAM,cAAc,CAAC;SACtB;gBAAS;YACR,MAAM,EAAE,KAAK,EAAE,CAAC;SACjB;IACH,CAAC;IAED;;;OAGG;IACM,KAAK,CAAC,KAAK,CAAC,KAAoC;QACvD,MAAM,KAAK,GAAG,KAAK,YAAY,kBAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,wBAAY,CAAC,KAAK,CAAC,CAAC;QAC3E,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;QAC9B,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QAEtB,uIAAuI;QACvI,wIAAwI;QACxI,8EAA8E;QAC9E,EAAE;QACF,0GAA0G;QAC1G,+GAA+G;QAC/G,MAAM,IAAI,kBAAS,CAAC,OAAO,CAAC,QAAQ,IAAI,KAAK,CAAC,QAAQ,IAAI,CAAC,CAAC,CAAC;IAC/D,CAAC;;AA9KH,kCA+KC;AA9KC;;;GAGG;AACI;;;;WAAW,QAAQ;GAAC;AAEpB;;;;WAAuB;QAC5B,KAAK,EAAE,YAAK,CAAC,OAAO,CAAC;YACnB,IAAI,EAAE,GAAG;YACT,OAAO,EAAE,sCAAsC;YAC/C,SAAS,EAAE,QAAQ;YACnB,OAAO,EAAE,KAAK;SACf,CAAC;KACH;GAAC","sourcesContent":["import type { Config } from \"@oclif/core\";\nimport { Command, Flags, settings } from \"@oclif/core\";\nimport { ExitError } from \"@oclif/core/lib/errors\";\nimport chalk from \"chalk\";\nimport Debug from \"debug\";\nimport getPort from \"get-port\";\nimport type { Server } from \"http\";\nimport { createServer } from \"http\";\nimport { prompt } from \"inquirer\";\nimport type { Notification } from \"node-notifier\";\nimport { notify } from \"node-notifier\";\nimport type WindowsBalloon from \"node-notifier/notifiers/balloon\";\nimport type Growl from \"node-notifier/notifiers/growl\";\nimport type NotificationCenter from \"node-notifier/notifiers/notificationcenter\";\nimport type NotifySend from \"node-notifier/notifiers/notifysend\";\nimport type WindowsToaster from \"node-notifier/notifiers/toaster\";\nimport open from \"open\";\nimport path from \"path\";\nimport dedent from \"ts-dedent\";\nimport { context, GADGET_ENDPOINT } from \"./context\";\nimport { BaseError, UnexpectedError as UnknownError } from \"./errors\";\n\nexport abstract class BaseCommand extends Command {\n /**\n * Determines how high the command is listed in the README. The lower the number, the higher the command is listed. Equal numbers are\n * sorted alphabetically.\n */\n static priority = Infinity;\n\n static override globalFlags = {\n debug: Flags.boolean({\n char: \"D\",\n summary: \"Whether to output debug information.\",\n helpGroup: \"global\",\n default: false,\n }),\n };\n\n /**\n * Determines whether the command requires the user to be logged in or not.\n * If true and the user is not logged in, the user will be prompted to login before the command is run.\n */\n readonly requireUser: boolean = false;\n\n constructor(argv: string[], config: Config) {\n super(argv, config);\n\n // TODO: Remove this once the `@oclif/core` warnIfFlagDeprecated function checks global flags as well.\n // warnIfFlagDeprecated throws a null pointer because it assumes all parsed flags are in the flags object (which is not the case for global flags).\n // https://github.com/oclif/core/blob/11c5752cec838d08bb27cd55f0f1aa2390df3c5e/src/command.ts#L259\n this.ctor.flags = { ...this.ctor.flags, ...BaseCommand.globalFlags };\n }\n\n /**\n * Indicates whether the command is being run with the `-D/--debug` flag.\n */\n get debugEnabled(): boolean {\n return !!settings.debug;\n }\n\n override async init(): Promise<void> {\n await super.init();\n const { flags, argv } = await this.parse({ flags: BaseCommand.globalFlags, strict: false });\n\n // remove global flags from argv so that when the implementation calls parse, it doesn't get confused by them\n this.argv = argv;\n\n if (flags.debug) {\n settings.debug = true;\n Debug.enable(`${this.config.bin}:*`);\n }\n\n context.config = this.config;\n\n if (this.requireUser && !(await context.getUser())) {\n const { login } = await prompt<{ login: boolean }>({\n type: \"confirm\",\n name: \"login\",\n message: \"You must be logged in to use this command. Would you like to log in?\",\n });\n\n if (!login) {\n return this.exit(0);\n }\n\n await this.login();\n }\n }\n\n /**\n * Sends a native OS notification to the user.\n *\n * @see {@link https://www.npmjs.com/package/node-notifier node-notifier}\n */\n notify(\n notification:\n | Notification\n | NotificationCenter.Notification\n | NotifySend.Notification\n | WindowsToaster.Notification\n | WindowsBalloon.Notification\n | Growl.Notification\n ): void {\n notify(\n {\n title: \"Gadget\",\n contentImage: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n icon: path.join(this.config.root, \"assets\", \"favicon-128@4x.png\"),\n sound: true,\n timeout: false,\n ...notification,\n },\n (error) => {\n if (error) this.warn(error);\n }\n );\n }\n\n /**\n * Opens the Gadget login page in the user's default browser and waits for the user to login.\n */\n async login(): Promise<void> {\n let server: Server | undefined;\n\n try {\n const port = await getPort();\n const receiveSession = new Promise<void>((resolve, reject) => {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n server = createServer(async (req, res) => {\n const redirectTo = new URL(`${GADGET_ENDPOINT}/auth/cli`);\n\n try {\n if (!req.url) throw new Error(\"missing url\");\n const incomingUrl = new URL(req.url, `http://localhost:${port}`);\n\n const value = incomingUrl.searchParams.get(\"session\");\n if (!value) throw new Error(\"missing session\");\n\n context.session = value;\n\n const user = await context.getUser();\n if (!user) throw new Error(\"missing current user\");\n\n if (user.name) {\n this.log(chalk`Hello, ${user.name} {gray (${user.email})}`);\n } else {\n this.log(`Hello, ${user.email}`);\n }\n\n redirectTo.searchParams.set(\"success\", \"true\");\n resolve();\n } catch (error) {\n context.session = undefined;\n redirectTo.searchParams.set(\"success\", \"false\");\n reject(error);\n } finally {\n res.writeHead(303, { Location: redirectTo.toString() });\n res.end();\n }\n });\n\n server.listen(port);\n });\n\n const url = new URL(`${GADGET_ENDPOINT}/auth/login`);\n url.searchParams.set(\"returnTo\", `${GADGET_ENDPOINT}/auth/cli/callback?port=${port}`);\n await open(url.toString());\n\n this.log(dedent`\n We've opened Gadget's login page using your default browser.\n\n Please log in and then return to this terminal.\\n\n `);\n\n await receiveSession;\n } finally {\n server?.close();\n }\n }\n\n /**\n * Overrides the default `catch` behavior so we can control how errors are printed to the user. This is called automatically by oclif when\n * an error is thrown during the `init` or `run` methods.\n */\n override async catch(cause: Error & { exitCode?: number }): Promise<never> {\n const error = cause instanceof BaseError ? cause : new UnknownError(cause);\n console.error(error.render());\n await error.capture();\n\n // The original implementation of `catch` re-throws the error so that it's caught and printed by oclif's `handle` method. We still want\n // to end up in oclif's `handle` method, but we don't want it to print the error again so we throw an ExitError instead. This will cause\n // `handle` to not print the error, but still exit with the correct exit code.\n //\n // catch: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/command.ts#L261\n // handle: https://github.com/oclif/core/blob/12e31ff2288606e583e03bf774a3244f3136cd10/src/errors/handle.ts#L15\n throw new ExitError(process.exitCode ?? cause.exitCode ?? 1);\n }\n}\n"]}
@@ -106,14 +106,14 @@ class Client {
106
106
  if (this.status == ConnectionStatus.RECONNECTING) {
107
107
  // subscribePayload.variables is supposed to be readonly (it's not) and payload.variables may have been re-assigned (it won't)
108
108
  subscribePayload.variables = payload.variables();
109
- debug("re-sending%s", subscribePayload.query.split(" ", 2)[0], subscribePayload.query);
109
+ debug("re-sending %s%s%O", subscribePayload.query.split(/\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);
110
110
  }
111
111
  });
112
112
  }
113
113
  else {
114
114
  subscribePayload = payload;
115
115
  }
116
- debug("sending%s", subscribePayload.query.split(/\s+/, 2)[0], subscribePayload.query);
116
+ debug("sending %s%s%O", subscribePayload.query.split(/\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);
117
117
  const unsubscribe = this._client.subscribe(subscribePayload, {
118
118
  next: (result) => sink.next(result),
119
119
  error: (error) => sink.error(new errors_1.ClientError(subscribePayload, error)),
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/utils/client.ts"],"names":[],"mappings":";;;;AAAA,4DAA4B;AAC5B,0DAA0B;AAG1B,2CAA0C;AAE1C,mCAA0C;AAG1C,oDAA2B;AAC3B,uCAAoC;AACpC,qCAAuC;AAEvC,MAAM,KAAK,GAAG,IAAA,eAAK,EAAC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C,OAAO,EAAE,qCAAqC,CAAC,CAAC;QACxF,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IAC/B,CAAC;CACF;AAxJD,wBAwJC","sourcesContent":["import assert from \"assert\";\nimport Debug from \"debug\";\nimport type { GraphQLError } from \"graphql\";\nimport type { ExecutionResult, SubscribePayload } from \"graphql-ws\";\nimport { createClient } from \"graphql-ws\";\nimport type { ClientRequestArgs } from \"http\";\nimport { isFunction, noop } from \"lodash\";\nimport type { JsonObject, SetOptional } from \"type-fest\";\nimport type { CloseEvent, ErrorEvent } from \"ws\";\nimport WebSocket from \"ws\";\nimport { context } from \"./context\";\nimport { ClientError } from \"./errors\";\n\nconst debug = Debug(\"ggt:client\");\n\nenum ConnectionStatus {\n CONNECTED,\n DISCONNECTED,\n RECONNECTING,\n}\n\nexport class Client {\n // assume the client is going to connect\n status = ConnectionStatus.CONNECTED;\n\n private _client: ReturnType<typeof createClient>;\n\n constructor() {\n assert(context.app, \"context.app must be set before instantiating the Client\");\n const domain = context.env.productionLike ? \"gadget.app\" : \"ggt.pub:3000\";\n\n this._client = createClient({\n url: `wss://${context.app.slug}.${domain}/edit/api/graphql-ws`,\n shouldRetry: () => true,\n webSocketImpl: class extends WebSocket {\n constructor(address: string | URL, protocols?: string | string[], wsOptions?: WebSocket.ClientOptions | ClientRequestArgs) {\n assert(context.session, \"context.session must be set before instantiating the Client\");\n super(address, protocols, {\n ...wsOptions,\n headers: {\n ...wsOptions?.headers,\n \"user-agent\": context.config.userAgent,\n cookie: `session=${encodeURIComponent(context.session)};`,\n },\n });\n }\n },\n on: {\n connecting: () => {\n switch (this.status) {\n case ConnectionStatus.DISCONNECTED:\n this.status = ConnectionStatus.RECONNECTING;\n debug(\"reconnecting...\");\n break;\n case ConnectionStatus.RECONNECTING:\n debug(\"retrying...\");\n break;\n default:\n debug(\"connecting...\");\n break;\n }\n },\n connected: () => {\n if (this.status === ConnectionStatus.RECONNECTING) {\n debug(\"reconnected\");\n } else {\n debug(\"connected\");\n }\n\n // let the other on connected listeners see what status we're in\n setImmediate(() => (this.status = ConnectionStatus.CONNECTED));\n },\n closed: (e) => {\n const event = e as CloseEvent;\n if (event.wasClean) {\n debug(\"connection closed\");\n return;\n }\n\n if (this.status === ConnectionStatus.CONNECTED) {\n this.status = ConnectionStatus.DISCONNECTED;\n debug(\"disconnected\");\n }\n },\n error: (error) => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n debug(\"failed to reconnect %o\", { error });\n } else {\n debug(\"connection error %o\", { error });\n }\n },\n },\n });\n }\n\n subscribe<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>,\n sink: SetOptional<Sink<Data, Extensions>, \"complete\">\n ): () => void {\n let subscribePayload: SubscribePayload;\n let removeConnectedListener: () => void;\n\n if (isFunction(payload.variables)) {\n // the caller wants us to re-evaluate the variables every time graphql-ws re-subscribes after reconnecting\n subscribePayload = { ...payload, variables: payload.variables() };\n removeConnectedListener = this._client.on(\"connected\", () => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n // subscribePayload.variables is supposed to be readonly (it's not) and payload.variables may have been re-assigned (it won't)\n (subscribePayload as any).variables = (payload.variables as any)();\n debug(\"re-sending%s\", subscribePayload.query.split(\" \", 2)[0], subscribePayload.query);\n }\n });\n } else {\n subscribePayload = payload as SubscribePayload;\n }\n\n debug(\"sending%s\", subscribePayload.query.split(/\\s+/, 2)[0], subscribePayload.query);\n const unsubscribe = this._client.subscribe(subscribePayload, {\n next: (result: ExecutionResult<Data, Extensions>) => sink.next(result),\n error: (error) => sink.error(new ClientError(subscribePayload, error as Error | GraphQLError[] | CloseEvent | ErrorEvent)),\n complete: () => sink.complete?.() ?? noop,\n });\n\n return () => {\n removeConnectedListener?.();\n unsubscribe();\n };\n }\n\n subscribeUnwrap<Data extends JsonObject, Variables extends JsonObject>(\n payload: Payload<Data, Variables>,\n sink: { next: (data: Data) => void; error: (error: ClientError) => void }\n ): () => void {\n const unsubscribe = this.subscribe(payload, {\n ...sink,\n next: (result) => {\n if (result.errors) {\n unsubscribe();\n sink.error(new ClientError(payload, result.errors));\n return;\n }\n\n if (!result.data) {\n sink.error(new ClientError(payload, \"We received a response without data\"));\n unsubscribe();\n return;\n }\n\n sink.next(result.data);\n },\n });\n\n return unsubscribe;\n }\n\n query<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>\n ): Promise<ExecutionResult<Data, Extensions>> {\n return new Promise((resolve, reject) => {\n this.subscribe<Data, Variables, Extensions>(payload, { next: resolve, error: reject });\n });\n }\n\n async queryUnwrap<Data extends JsonObject, Variables extends JsonObject>(payload: Payload<Data, Variables>): Promise<Data> {\n const result = await this.query(payload);\n if (result.errors) throw new ClientError(payload, result.errors);\n if (!result.data) throw new ClientError(payload, \"We received a response without data\");\n return result.data;\n }\n\n async dispose(): Promise<void> {\n await this._client.dispose();\n }\n}\n\nexport type Query<\n Data extends JsonObject,\n Variables extends JsonObject = JsonObject,\n Extensions extends JsonObject = JsonObject\n> = string & {\n __TData?: Data;\n __TVariables?: Variables;\n __TExtensions?: Extensions;\n};\n\nexport interface Payload<Data extends JsonObject, Variables extends JsonObject> {\n readonly query: Query<Data, Variables>;\n readonly variables?: Variables | (() => Variables) | null;\n}\n\nexport interface Sink<Data extends JsonObject, Extensions extends JsonObject> {\n next(value: ExecutionResult<Data, Extensions>): void;\n error(error: ClientError): void;\n complete(): void;\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/utils/client.ts"],"names":[],"mappings":";;;;AAAA,4DAA4B;AAC5B,0DAA0B;AAG1B,2CAA0C;AAE1C,mCAA0C;AAG1C,oDAA2B;AAC3B,uCAAoC;AACpC,qCAAuC;AAEvC,MAAM,KAAK,GAAG,IAAA,eAAK,EAAC,YAAY,CAAC,CAAC;AA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C,IAAI;YAAE,MAAM,IAAI,oBAAW,CAAC,OAAO,EAAE,qCAAqC,CAAC,CAAC;QACxF,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IAC/B,CAAC;CACF;AAxJD,wBAwJC","sourcesContent":["import assert from \"assert\";\nimport Debug from \"debug\";\nimport type { GraphQLError } from \"graphql\";\nimport type { ExecutionResult, SubscribePayload } from \"graphql-ws\";\nimport { createClient } from \"graphql-ws\";\nimport type { ClientRequestArgs } from \"http\";\nimport { isFunction, noop } from \"lodash\";\nimport type { JsonObject, SetOptional } from \"type-fest\";\nimport type { CloseEvent, ErrorEvent } from \"ws\";\nimport WebSocket from \"ws\";\nimport { context } from \"./context\";\nimport { ClientError } from \"./errors\";\n\nconst debug = Debug(\"ggt:client\");\n\nenum ConnectionStatus {\n CONNECTED,\n DISCONNECTED,\n RECONNECTING,\n}\n\nexport class Client {\n // assume the client is going to connect\n status = ConnectionStatus.CONNECTED;\n\n private _client: ReturnType<typeof createClient>;\n\n constructor() {\n assert(context.app, \"context.app must be set before instantiating the Client\");\n const domain = context.env.productionLike ? \"gadget.app\" : \"ggt.pub:3000\";\n\n this._client = createClient({\n url: `wss://${context.app.slug}.${domain}/edit/api/graphql-ws`,\n shouldRetry: () => true,\n webSocketImpl: class extends WebSocket {\n constructor(address: string | URL, protocols?: string | string[], wsOptions?: WebSocket.ClientOptions | ClientRequestArgs) {\n assert(context.session, \"context.session must be set before instantiating the Client\");\n super(address, protocols, {\n ...wsOptions,\n headers: {\n ...wsOptions?.headers,\n \"user-agent\": context.config.userAgent,\n cookie: `session=${encodeURIComponent(context.session)};`,\n },\n });\n }\n },\n on: {\n connecting: () => {\n switch (this.status) {\n case ConnectionStatus.DISCONNECTED:\n this.status = ConnectionStatus.RECONNECTING;\n debug(\"reconnecting...\");\n break;\n case ConnectionStatus.RECONNECTING:\n debug(\"retrying...\");\n break;\n default:\n debug(\"connecting...\");\n break;\n }\n },\n connected: () => {\n if (this.status === ConnectionStatus.RECONNECTING) {\n debug(\"reconnected\");\n } else {\n debug(\"connected\");\n }\n\n // let the other on connected listeners see what status we're in\n setImmediate(() => (this.status = ConnectionStatus.CONNECTED));\n },\n closed: (e) => {\n const event = e as CloseEvent;\n if (event.wasClean) {\n debug(\"connection closed\");\n return;\n }\n\n if (this.status === ConnectionStatus.CONNECTED) {\n this.status = ConnectionStatus.DISCONNECTED;\n debug(\"disconnected\");\n }\n },\n error: (error) => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n debug(\"failed to reconnect %o\", { error });\n } else {\n debug(\"connection error %o\", { error });\n }\n },\n },\n });\n }\n\n subscribe<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>,\n sink: SetOptional<Sink<Data, Extensions>, \"complete\">\n ): () => void {\n let subscribePayload: SubscribePayload;\n let removeConnectedListener: () => void;\n\n if (isFunction(payload.variables)) {\n // the caller wants us to re-evaluate the variables every time graphql-ws re-subscribes after reconnecting\n subscribePayload = { ...payload, variables: payload.variables() };\n removeConnectedListener = this._client.on(\"connected\", () => {\n if (this.status == ConnectionStatus.RECONNECTING) {\n // subscribePayload.variables is supposed to be readonly (it's not) and payload.variables may have been re-assigned (it won't)\n (subscribePayload as any).variables = (payload.variables as any)();\n debug(\"re-sending %s%s%O\", subscribePayload.query.split(/\\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);\n }\n });\n } else {\n subscribePayload = payload as SubscribePayload;\n }\n\n debug(\"sending %s%s%O\", subscribePayload.query.split(/\\s+/g, 1)[0], subscribePayload.query, subscribePayload.variables);\n const unsubscribe = this._client.subscribe(subscribePayload, {\n next: (result: ExecutionResult<Data, Extensions>) => sink.next(result),\n error: (error) => sink.error(new ClientError(subscribePayload, error as Error | GraphQLError[] | CloseEvent | ErrorEvent)),\n complete: () => sink.complete?.() ?? noop,\n });\n\n return () => {\n removeConnectedListener?.();\n unsubscribe();\n };\n }\n\n subscribeUnwrap<Data extends JsonObject, Variables extends JsonObject>(\n payload: Payload<Data, Variables>,\n sink: { next: (data: Data) => void; error: (error: ClientError) => void }\n ): () => void {\n const unsubscribe = this.subscribe(payload, {\n ...sink,\n next: (result) => {\n if (result.errors) {\n unsubscribe();\n sink.error(new ClientError(payload, result.errors));\n return;\n }\n\n if (!result.data) {\n sink.error(new ClientError(payload, \"We received a response without data\"));\n unsubscribe();\n return;\n }\n\n sink.next(result.data);\n },\n });\n\n return unsubscribe;\n }\n\n query<Data extends JsonObject, Variables extends JsonObject, Extensions extends JsonObject = JsonObject>(\n payload: Payload<Data, Variables>\n ): Promise<ExecutionResult<Data, Extensions>> {\n return new Promise((resolve, reject) => {\n this.subscribe<Data, Variables, Extensions>(payload, { next: resolve, error: reject });\n });\n }\n\n async queryUnwrap<Data extends JsonObject, Variables extends JsonObject>(payload: Payload<Data, Variables>): Promise<Data> {\n const result = await this.query(payload);\n if (result.errors) throw new ClientError(payload, result.errors);\n if (!result.data) throw new ClientError(payload, \"We received a response without data\");\n return result.data;\n }\n\n async dispose(): Promise<void> {\n await this._client.dispose();\n }\n}\n\nexport type Query<\n Data extends JsonObject,\n Variables extends JsonObject = JsonObject,\n Extensions extends JsonObject = JsonObject\n> = string & {\n __TData?: Data;\n __TVariables?: Variables;\n __TExtensions?: Extensions;\n};\n\nexport interface Payload<Data extends JsonObject, Variables extends JsonObject> {\n readonly query: Query<Data, Variables>;\n readonly variables?: Variables | (() => Variables) | null;\n}\n\nexport interface Sink<Data extends JsonObject, Extensions extends JsonObject> {\n next(value: ExecutionResult<Data, Extensions>): void;\n error(error: ClientError): void;\n complete(): void;\n}\n"]}
@@ -45,6 +45,7 @@ export interface App {
45
45
  id: string | number;
46
46
  name: string;
47
47
  slug: string;
48
+ hasSplitEnvironments: boolean;
48
49
  }
49
50
  export declare const context: Context;
50
51
  export declare const GADGET_ENDPOINT: string;
@@ -1 +1 @@
1
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AAe,IAAI,IAAI,CAAC,QAAQ,CAAC;IAC/C,CAAC;CACF;AAcY,QAAA,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;AAExB,QAAA,eAAe,GAAG,eAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,0BAA0B,CAAC","sourcesContent":["import type { Config } from \"@oclif/core\";\nimport assert from \"assert\";\nimport fs from \"fs-extra\";\nimport got, { HTTPError } from \"got\";\nimport { isString } from \"lodash\";\nimport path from \"path\";\nimport { ignoreEnoent } from \"./fs-utils\";\n\nclass Context {\n /**\n * A reference to oclif's {@linkcode Config}.\n *\n * By default, oclif's {@linkcode Config} is only available as an instance property on a Command, but we want to be able to access it from\n * anywhere. To do this, we created this global variable that references the Config. It is set by the init function in the BaseCommand.\n */\n config!: Config;\n\n env = new Env();\n\n app?: App;\n\n private _session?: string;\n\n private _user?: User;\n\n private _availableApps: App[] = [];\n\n private _request = got.extend({\n hooks: {\n beforeRequest: [\n (options) => {\n options.headers[\"user-agent\"] = this.config.userAgent;\n if (options.url.origin === GADGET_ENDPOINT && this.session) {\n options.headers[\"cookie\"] = `session=${encodeURIComponent(this.session)};`;\n }\n },\n ],\n },\n });\n\n get session(): string | undefined {\n if (this._session) return this._session;\n\n try {\n this._session = fs.readFileSync(path.join(this.config.configDir, \"session.txt\"), \"utf-8\");\n return this._session;\n } catch (error) {\n ignoreEnoent(error);\n return undefined;\n }\n }\n\n set session(value: string | undefined) {\n this.clear();\n this._session = value;\n if (this._session) {\n fs.outputFileSync(path.join(this.config.configDir, \"session.txt\"), this._session);\n } else {\n fs.removeSync(path.join(this.config.configDir, \"session.txt\"));\n }\n }\n\n /**\n * @returns The current user, or undefined if the user is not logged in.\n */\n async getUser(): Promise<User | undefined> {\n if (!this.session) return undefined;\n if (this._user) return this._user;\n\n try {\n this._user = await this._request(`${GADGET_ENDPOINT}/auth/api/current-user`).json<User>();\n return this._user;\n } catch (error) {\n if (error instanceof HTTPError && error.response.statusCode === 401) {\n this.session = undefined;\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * @returns The list of Gadget applications the current user has access to.\n */\n async getAvailableApps(): Promise<App[]> {\n if (!this.session) return [];\n if (this._availableApps.length > 0) return this._availableApps;\n\n this._availableApps = await this._request(`${GADGET_ENDPOINT}/auth/api/apps`).json<App[]>();\n return this._availableApps;\n }\n\n async setApp(value: App | string | undefined): Promise<void> {\n if (isString(value)) {\n const app = await this.getAvailableApps().then((apps) => apps.find((app) => app.name == value || app.slug == value));\n assert(app, `attempted to set app to \"${value}\" but no app with that name or slug was found`);\n this.app = app;\n } else {\n this.app = value;\n }\n }\n\n clear(): void {\n this._session = undefined;\n this._user = undefined;\n this.app = undefined;\n this._availableApps = [];\n }\n}\n\n/**\n * Captures the name and nature of the environment\n */\nclass Env {\n get value(): string {\n return process.env[\"GGT_ENV\"] || \"production\";\n }\n\n get productionLike(): boolean {\n return this.value.startsWith(\"production\");\n }\n\n get developmentLike(): boolean {\n return this.value.startsWith(\"development\");\n }\n\n get testLike(): boolean {\n return this.value.startsWith(\"test\");\n }\n\n get developmentOrTestLike(): boolean {\n return this.developmentLike || this.testLike;\n }\n}\n\nexport interface User {\n id: string | number;\n email: string;\n name?: string;\n}\n\nexport interface App {\n id: string | number;\n name: string;\n slug: string;\n}\n\nexport const context = new Context();\n\nexport const GADGET_ENDPOINT = context.env.productionLike ? \"https://app.gadget.dev\" : \"https://app.ggt.dev:3000\";\n"]}
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/utils/context.ts"],"names":[],"mappings":";;;;AACA,4DAA4B;AAC5B,gEAA0B;AAC1B,mDAAqC;AACrC,mCAAkC;AAClC,wDAAwB;AACxB,yCAA0C;AAE1C,MAAM,OAAO;IAAb;QACE;;;;;WAKG;QACH;;;;;WAAgB;QAEhB;;;;mBAAM,IAAI,GAAG,EAAE;WAAC;QAEhB;;;;;WAAU;QAEV;;;;;WAA0B;QAE1B;;;;;WAAqB;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GAAG,CAAC,IAAI,IAAI,KAAK,IAAI,GAAG,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC;YACrH,IAAA,gBAAM,EAAC,GAAG,EAAE,4BAA4B,KAAK,+CAA+C,CAAC,CAAC;YAC9F,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;SAChB;aAAM;YACL,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC;SAClB;IACH,CAAC;IAED,KAAK;QACH,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC1B,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;IAC3B,CAAC;CACF;AAED;;GAEG;AACH,MAAM,GAAG;IACP,IAAI,KAAK;QACP,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,YAAY,CAAC;IAChD,CAAC;IAED,IAAI,cAAc;QAChB,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;IAC9C,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,eAAe,IAAI,IAAI,CAAC,QAAQ,CAAC;IAC/C,CAAC;CACF;AAeY,QAAA,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;AAExB,QAAA,eAAe,GAAG,eAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,0BAA0B,CAAC","sourcesContent":["import type { Config } from \"@oclif/core\";\nimport assert from \"assert\";\nimport fs from \"fs-extra\";\nimport got, { HTTPError } from \"got\";\nimport { isString } from \"lodash\";\nimport path from \"path\";\nimport { ignoreEnoent } from \"./fs-utils\";\n\nclass Context {\n /**\n * A reference to oclif's {@linkcode Config}.\n *\n * By default, oclif's {@linkcode Config} is only available as an instance property on a Command, but we want to be able to access it from\n * anywhere. To do this, we created this global variable that references the Config. It is set by the init function in the BaseCommand.\n */\n config!: Config;\n\n env = new Env();\n\n app?: App;\n\n private _session?: string;\n\n private _user?: User;\n\n private _availableApps: App[] = [];\n\n private _request = got.extend({\n hooks: {\n beforeRequest: [\n (options) => {\n options.headers[\"user-agent\"] = this.config.userAgent;\n if (options.url.origin === GADGET_ENDPOINT && this.session) {\n options.headers[\"cookie\"] = `session=${encodeURIComponent(this.session)};`;\n }\n },\n ],\n },\n });\n\n get session(): string | undefined {\n if (this._session) return this._session;\n\n try {\n this._session = fs.readFileSync(path.join(this.config.configDir, \"session.txt\"), \"utf-8\");\n return this._session;\n } catch (error) {\n ignoreEnoent(error);\n return undefined;\n }\n }\n\n set session(value: string | undefined) {\n this.clear();\n this._session = value;\n if (this._session) {\n fs.outputFileSync(path.join(this.config.configDir, \"session.txt\"), this._session);\n } else {\n fs.removeSync(path.join(this.config.configDir, \"session.txt\"));\n }\n }\n\n /**\n * @returns The current user, or undefined if the user is not logged in.\n */\n async getUser(): Promise<User | undefined> {\n if (!this.session) return undefined;\n if (this._user) return this._user;\n\n try {\n this._user = await this._request(`${GADGET_ENDPOINT}/auth/api/current-user`).json<User>();\n return this._user;\n } catch (error) {\n if (error instanceof HTTPError && error.response.statusCode === 401) {\n this.session = undefined;\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * @returns The list of Gadget applications the current user has access to.\n */\n async getAvailableApps(): Promise<App[]> {\n if (!this.session) return [];\n if (this._availableApps.length > 0) return this._availableApps;\n\n this._availableApps = await this._request(`${GADGET_ENDPOINT}/auth/api/apps`).json<App[]>();\n return this._availableApps;\n }\n\n async setApp(value: App | string | undefined): Promise<void> {\n if (isString(value)) {\n const app = await this.getAvailableApps().then((apps) => apps.find((app) => app.name == value || app.slug == value));\n assert(app, `attempted to set app to \"${value}\" but no app with that name or slug was found`);\n this.app = app;\n } else {\n this.app = value;\n }\n }\n\n clear(): void {\n this._session = undefined;\n this._user = undefined;\n this.app = undefined;\n this._availableApps = [];\n }\n}\n\n/**\n * Captures the name and nature of the environment\n */\nclass Env {\n get value(): string {\n return process.env[\"GGT_ENV\"] || \"production\";\n }\n\n get productionLike(): boolean {\n return this.value.startsWith(\"production\");\n }\n\n get developmentLike(): boolean {\n return this.value.startsWith(\"development\");\n }\n\n get testLike(): boolean {\n return this.value.startsWith(\"test\");\n }\n\n get developmentOrTestLike(): boolean {\n return this.developmentLike || this.testLike;\n }\n}\n\nexport interface User {\n id: string | number;\n email: string;\n name?: string;\n}\n\nexport interface App {\n id: string | number;\n name: string;\n slug: string;\n hasSplitEnvironments: boolean;\n}\n\nexport const context = new Context();\n\nexport const GADGET_ENDPOINT = context.env.productionLike ? \"https://app.gadget.dev\" : \"https://app.ggt.dev:3000\";\n"]}
@@ -15,7 +15,7 @@ export declare abstract class BaseError extends Error {
15
15
  /**
16
16
  * The Sentry event ID for this error.
17
17
  */
18
- sentryEventId?: string;
18
+ sentryEventId: string;
19
19
  /**
20
20
  * The underlying *thing* that caused this error.
21
21
  */
@@ -11,6 +11,7 @@ const util_1 = require("util");
11
11
  const context_1 = require("./context");
12
12
  const Sentry = tslib_1.__importStar(require("@sentry/node"));
13
13
  const os_1 = tslib_1.__importDefault(require("os"));
14
+ const crypto_1 = require("crypto");
14
15
  if (context_1.context.env.productionLike) {
15
16
  Sentry.init({ dsn: "https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266" });
16
17
  }
@@ -38,7 +39,7 @@ class BaseError extends Error {
38
39
  enumerable: true,
39
40
  configurable: true,
40
41
  writable: true,
41
- value: void 0
42
+ value: context_1.context.env.testLike ? "00000000-0000-0000-0000-000000000000" : (0, crypto_1.randomUUID)()
42
43
  });
43
44
  /**
44
45
  * The underlying *thing* that caused this error.
@@ -65,32 +66,35 @@ class BaseError extends Error {
65
66
  if (this.isBug == IsBug.NO)
66
67
  return;
67
68
  const user = await context_1.context.getUser().catch(lodash_1.noop);
68
- this.sentryEventId = Sentry.captureException(this, {
69
- user: user ? { id: String(user.id), email: user.email, username: user.name } : undefined,
70
- tags: {
71
- applicationId: context_1.context.app?.id,
72
- arch: context_1.context.config.arch,
73
- isBug: this.isBug,
74
- code: this.code,
75
- environment: context_1.context.env.value,
76
- platform: context_1.context.config.platform,
77
- shell: context_1.context.config.shell,
78
- version: context_1.context.config.version,
79
- },
80
- contexts: {
81
- cause: this.cause ? serializeError(this.cause) : undefined,
82
- app: {
83
- command: `${context_1.context.config.bin} ${process.argv.slice(2).join(" ")}`,
84
- argv: process.argv,
85
- },
86
- device: {
87
- name: os_1.default.hostname(),
88
- family: os_1.default.type(),
89
- arch: os_1.default.arch(),
69
+ Sentry.getCurrentHub().captureException(this, {
70
+ event_id: this.sentryEventId,
71
+ captureContext: {
72
+ user: user ? { id: String(user.id), email: user.email, username: user.name } : undefined,
73
+ tags: {
74
+ applicationId: context_1.context.app?.id,
75
+ arch: context_1.context.config.arch,
76
+ isBug: this.isBug,
77
+ code: this.code,
78
+ environment: context_1.context.env.value,
79
+ platform: context_1.context.config.platform,
80
+ shell: context_1.context.config.shell,
81
+ version: context_1.context.config.version,
90
82
  },
91
- runtime: {
92
- name: process.release.name,
93
- version: process.version,
83
+ contexts: {
84
+ cause: this.cause ? serializeError(this.cause) : undefined,
85
+ app: {
86
+ command: `${context_1.context.config.bin} ${process.argv.slice(2).join(" ")}`,
87
+ argv: process.argv,
88
+ },
89
+ device: {
90
+ name: os_1.default.hostname(),
91
+ family: os_1.default.type(),
92
+ arch: os_1.default.arch(),
93
+ },
94
+ runtime: {
95
+ name: process.release.name,
96
+ version: process.version,
97
+ },
94
98
  },
95
99
  },
96
100
  });
@@ -124,7 +128,7 @@ class BaseError extends Error {
124
128
  return (0, ts_dedent_1.default) `
125
129
  ${this.isBug == IsBug.YES ? "This is a bug" : "If you think this is a bug"}, please submit an issue using the link below.
126
130
 
127
- https://github.com/gadget-inc/ggt/issues/new?template=bug_report.yml${this.sentryEventId ? `&error-id=${this.sentryEventId}` : ""}
131
+ https://github.com/gadget-inc/ggt/issues/new?template=bug_report.yml&error-id=${this.sentryEventId}
128
132
  `;
129
133
  }
130
134
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/utils/errors.ts"],"names":[],"mappings":";;;;AAAA,sEAAqC;AACrC,6BAAgC;AAEhC,mCAA8F;AAC9F,qDAAuE;AACvE,kEAA+B;AAE/B,+BAA+B;AAI/B,uCAAoC;AACpC,6DAAuC;AACvC,oDAAoB;AAEpB,IAAI,iBAAO,CAAC,GAAG,CAAC,cAAc,EAAE;IAC9B,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,2EAA2E,EAAE,CAAC,CAAC;CACnG;AAED;;;;GAIG;AACH,MAAsB,SAAU,SAAQ,KAAK;IA0B3C,YAAY,IAAY,EAAE,OAAe;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QA1BjB;;WAEG;QACH;;;;;WAAa;QAEb;;WAEG;QACH;;;;;WAAuB;QAEvB;;WAEG;QACH;;;;;WAAqB;QAErB;;WAEG;QACH;;;;;WAAwB;QAStB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;IAED,KAAK,CAAC,OAAO;QACX,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,EAAE;YAAE,OAAO;QAEnC,MAAM,IAAI,GAAG,MAAM,iBAAO,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,aAAI,CAAC,CAAC;QAEjD,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE;YACjD,IAAI,EAAE,IAAI,C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} from \"got\";\nimport type { GraphQLError } from \"graphql\";\nimport { isArray, isBoolean, isError, isNil, isNumber, isString, noop, uniqBy } from \"lodash\";\nimport { serializeError as baseSerializeError } from \"serialize-error\";\nimport dedent from \"ts-dedent\";\nimport type { SetOptional } from \"type-fest\";\nimport { inspect } from \"util\";\nimport type { CloseEvent, ErrorEvent } from \"ws\";\nimport type Sync from \"../commands/sync\";\nimport type { Payload } from \"./client\";\nimport { context } from \"./context\";\nimport * as Sentry from \"@sentry/node\";\nimport os from \"os\";\n\nif (context.env.productionLike) {\n Sentry.init({ dsn: \"https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266\" });\n}\n\n/**\n * Base class for all errors.\n *\n * Inspired by gadget's GadgetError and oclif's PrettyPrintableError.\n */\nexport abstract class BaseError extends Error {\n /**\n * A GGT_CLI_SOMETHING human/machine readable unique identifier for this error.\n */\n code: string;\n\n /**\n * The Sentry event ID for this error.\n */\n sentryEventId?: string;\n\n /**\n * The underlying *thing* that caused this error.\n */\n override cause?: any;\n\n /**\n * Assume the stack trace exists.\n */\n override stack!: string;\n\n /**\n * Indicates whether this error is considered a bug or not.\n */\n abstract isBug: IsBug;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n Error.captureStackTrace(this, this.constructor);\n }\n\n async capture(): Promise<void> {\n if (this.isBug == IsBug.NO) return;\n\n const user = await context.getUser().catch(noop);\n\n this.sentryEventId = Sentry.captureException(this, {\n user: user ? { id: String(user.id), email: user.email, username: user.name } : undefined,\n tags: {\n applicationId: context.app?.id,\n arch: context.config.arch,\n isBug: this.isBug,\n code: this.code,\n environment: context.env.value,\n platform: context.config.platform,\n shell: context.config.shell,\n version: context.config.version,\n },\n contexts: {\n cause: this.cause ? serializeError(this.cause) : undefined,\n app: {\n command: `${context.config.bin} ${process.argv.slice(2).join(\" \")}`,\n argv: process.argv,\n },\n device: {\n name: os.hostname(),\n family: os.type(),\n arch: os.arch(),\n },\n runtime: {\n name: process.release.name,\n version: process.version,\n },\n },\n });\n\n await Sentry.flush(2000);\n }\n\n /**\n * Turns this error into a user-friendly message that explains what went wrong and how to fix it. A good write up of what an error should\n * look like can be found here: {@link https://clig.dev/#errors}\n */\n render(): string {\n const rendered = dedent`\n ${this.header()}\n\n ${this.body()}\n `;\n\n const footer = this.footer();\n if (!footer) return rendered;\n\n return dedent`\n ${rendered}\n\n ${footer}\n `;\n }\n\n protected header(): string {\n return `${this.code}: ${this.message}`;\n }\n\n protected footer(): string {\n if (this.isBug == IsBug.NO) return \"\";\n\n return dedent`\n ${this.isBug == IsBug.YES ? \"This is a bug\" : \"If you think this is a bug\"}, please submit an issue using the link below.\n\n https://github.com/gadget-inc/ggt/issues/new?template=bug_report.yml${this.sentryEventId ? `&error-id=${this.sentryEventId}` : \"\"}\n `;\n }\n\n protected abstract body(): string;\n}\n\n/**\n * Universal Error object to json blob serializer.\n * Wraps `serialize-error` with some handy stuff, like special support for Got HTTP errors\n */\nexport function serializeError(error: Error | string | unknown): Record<string, any> {\n let serialized = baseSerializeError(isArray(error) ? new AggregateError(error) : error);\n if (typeof serialized == \"string\") {\n serialized = { message: serialized };\n }\n\n if (error instanceof HTTPError && error.name === \"RequestError\") {\n delete serialized[\"timings\"];\n serialized[\"options\"] = { method: error.options.method, url: error.options.url.toJSON() };\n serialized[\"responseBody\"] = inspect(error.response?.body);\n }\n\n return serialized;\n}\n\nexport enum IsBug {\n YES = \"yes\",\n NO = \"no\",\n MAYBE = \"maybe\",\n}\n\n/**\n * Our \"catch all\" error. If this error is thrown, we almost certainly have a bug.\n *\n * Whenever possible, we should use a more specific error so that we can provide more useful information.\n */\nexport class UnexpectedError extends BaseError {\n isBug = IsBug.YES;\n\n constructor(override cause: Error) {\n super(\"GGT_CLI_UNEXPECTED_ERROR\", \"An unexpected error occurred\");\n }\n\n protected body(): string {\n return cleanStack(this.cause.stack ?? this.stack);\n }\n}\n\nexport class ClientError extends BaseError {\n isBug = IsBug.MAYBE;\n\n constructor(readonly payload: Payload<any, any>, override cause: string | Error | readonly GraphQLError[] | CloseEvent | ErrorEvent) {\n super(\"GGT_CLI_CLIENT_ERROR\", \"An error occurred while communicating with Gadget\");\n\n // ErrorEvent and CloseEvent aren't serializable, so we reconstruct them into an object. We discard the `target` property because it's large and not that useful\n if (isErrorEvent(cause)) {\n this.cause = {\n type: cause.type,\n message: cause.message,\n error: serializeError(cause.error),\n } as any;\n } else if (isCloseEvent(cause)) {\n this.cause = {\n type: cause.type,\n code: cause.code,\n reason: cause.reason,\n wasClean: cause.wasClean,\n } as any;\n }\n }\n\n override body(): string {\n if (isGraphQLErrors(this.cause)) {\n if (this.cause.length > 1) {\n const errors = uniqBy(this.cause, \"message\");\n\n let output = \"Gadget responded with multiple errors:\\n\";\n for (let i = 0; i < errors.length; i++) {\n output += `\\n ${i + 1}. ${errors[i]?.message}`;\n }\n\n return output;\n } else {\n return dedent`\n Gadget responded with the following error:\n\n ${this.cause[0]?.message}\n `;\n }\n }\n\n if (isCloseEvent(this.cause)) {\n return \"The connection to Gadget closed unexpectedly.\";\n }\n\n if (isErrorEvent(this.cause) || isError(this.cause)) {\n return this.cause.message;\n }\n\n return this.cause;\n }\n}\n\nexport class YarnNotFoundError extends BaseError {\n isBug = IsBug.NO;\n\n constructor() {\n super(\"GGT_CLI_YARN_NOT_FOUND\", \"Yarn not found\");\n }\n\n protected body(): string {\n return dedent`\n Yarn must be installed to sync your application. You can install it by running:\n\n $ npm install --global yarn\n\n For more information, see: https://classic.yarnpkg.com/en/docs/install\n `;\n }\n}\n\nexport class FlagError<T extends { name: string; char?: string } = { name: string; char?: string }> extends BaseError {\n isBug = IsBug.NO;\n\n constructor(readonly flag: T, readonly description: string) {\n const name = flag.char ? `-${flag.char}, --${flag.name}` : `--${flag.name}`;\n super(\"GGT_CLI_FLAG_ERROR\", `Invalid value provided for the ${name} flag`);\n }\n\n protected body(): string {\n return this.description;\n }\n}\n\nexport class InvalidSyncFileError extends BaseError {\n isBug = IsBug.MAYBE;\n\n constructor(override readonly cause: unknown, readonly sync: Sync, readonly app: string | undefined) {\n super(\"GGT_CLI_INVALID_SYNC_FILE\", \"The .gadget/sync.json file was invalid or not found\");\n }\n\n protected body(): string {\n return dedent`\n We failed to read the Gadget metadata file in this directory:\n\n ${this.sync.dir}\n\n If you're running \\`ggt sync\\` for the first time, we recommend using an empty directory such as:\n\n ~/gadget/${this.app || \"<name of app>\"}\n\n Otherwise, if you're sure you want to sync the contents of that directory to Gadget, run \\`ggt sync\\` again with the \\`--force\\` flag:\n\n $ ggt sync ${this.sync.argv.join(\" \")} --force\n\n You will be prompted to either merge your local files with your remote ones or reset your local files to your remote ones.\n `;\n }\n}\n\nexport class InvalidSyncAppFlagError extends FlagError {\n constructor(sync: Sync, app: string) {\n super(\n { name: \"app\", char: \"a\" },\n dedent`\n You were about to sync the following app to the following directory:\n\n ${app} → ${sync.dir}\n\n However, that directory has already been synced with this app:\n\n ${sync.metadata.app}\n\n If you're sure that you want to sync \"${app}\" to \"${sync.dir}\", run \\`ggt sync\\` again with the \\`--force\\` flag:\n\n $ ggt sync ${sync.argv.join(\" \")} --force\n `\n );\n }\n}\n\nfunction isCloseEvent(e: any): e is SetOptional<CloseEvent, \"target\"> {\n return !isNil(e) && isString(e.type) && isNumber(e.code) && isString(e.reason) && isBoolean(e.wasClean);\n}\n\nfunction isErrorEvent(e: any): e is SetOptional<ErrorEvent, \"target\"> {\n return !isNil(e) && isString(e.type) && isString(e.message) && !isNil(e.error);\n}\n\nfunction isGraphQLErrors(e: any): e is readonly GraphQLError[] {\n return isArray(e) && e.every((e) => !isNil(e) && isString(e.message) && isArray(e.locations ?? []) && isArray(e.path ?? []));\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/utils/errors.ts"],"names":[],"mappings":";;;;AAAA,sEAAqC;AACrC,6BAAgC;AAEhC,mCAA8F;AAC9F,qDAAuE;AACvE,kEAA+B;AAE/B,+BAA+B;AAI/B,uCAAoC;AACpC,6DAAuC;AACvC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CAAC,IAAI,IAAA,iBAAQ,EAAC,CAAC,CAAC,IAAI,CAAC,IAAI,IAAA,iBAAQ,EAAC,CAAC,CAAC,IAAI,CAAC,IAAI,IAAA,iBAAQ,EAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAA,kBAAS,EAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AAC1G,CAAC;AAED,SAAS,YAAY,CAAC,CAAM;IAC1B,OAAO,CAAC,IAAA,cAAK,EAAC,CAAC,CAAC,IAAI,IAAA,iBAAQ,EAAC,CAAC,CAAC,IAAI,CAAC,IAAI,IAAA,iBAAQ,EAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAA,cAAK,EAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACjF,CAAC;AAED,SAAS,eAAe,CAAC,CAAM;IAC7B,OAAO,IAAA,gBAAO,EAAC,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAA,cAAK,EAAC,CAAC,CAAC,IAAI,IAAA,iBAAQ,EAAC,CAAC,CAAC,OAAO,CAAC,IAAI,IAAA,gBAAO,EAAC,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,IAAI,IAAA,gBAAO,EAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;AAC/H,CAAC","sourcesContent":["import cleanStack from \"clean-stack\";\nimport { HTTPError } from \"got\";\nimport type { GraphQLError } from \"graphql\";\nimport { isArray, isBoolean, isError, isNil, isNumber, isString, noop, uniqBy } from \"lodash\";\nimport { serializeError as baseSerializeError } from \"serialize-error\";\nimport dedent from \"ts-dedent\";\nimport type { SetOptional } from \"type-fest\";\nimport { inspect } from \"util\";\nimport type { CloseEvent, ErrorEvent } from \"ws\";\nimport type Sync from \"../commands/sync\";\nimport type { Payload } from \"./client\";\nimport { context } from \"./context\";\nimport * as Sentry from \"@sentry/node\";\nimport os from \"os\";\nimport { randomUUID } from \"crypto\";\n\nif (context.env.productionLike) {\n Sentry.init({ dsn: \"https://0c26e0d8afd94e77a88ee1c3aa9e7065@o250689.ingest.sentry.io/6703266\" });\n}\n\n/**\n * Base class for all errors.\n *\n * Inspired by gadget's GadgetError and oclif's PrettyPrintableError.\n */\nexport abstract class BaseError extends Error {\n /**\n * A GGT_CLI_SOMETHING human/machine readable unique identifier for this error.\n */\n code: string;\n\n /**\n * The Sentry event ID for this error.\n */\n sentryEventId = context.env.testLike ? \"00000000-0000-0000-0000-000000000000\" : randomUUID();\n\n /**\n * The underlying *thing* that caused this error.\n */\n override cause?: any;\n\n /**\n * Assume the stack trace exists.\n */\n override stack!: string;\n\n /**\n * Indicates whether this error is considered a bug or not.\n */\n abstract isBug: IsBug;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n Error.captureStackTrace(this, this.constructor);\n }\n\n async capture(): Promise<void> {\n if (this.isBug == IsBug.NO) return;\n\n const user = await context.getUser().catch(noop);\n\n Sentry.getCurrentHub().captureException(this, {\n event_id: this.sentryEventId,\n captureContext: {\n user: user ? { id: String(user.id), email: user.email, username: user.name } : undefined,\n tags: {\n applicationId: context.app?.id,\n arch: context.config.arch,\n isBug: this.isBug,\n code: this.code,\n environment: context.env.value,\n platform: context.config.platform,\n shell: context.config.shell,\n version: context.config.version,\n },\n contexts: {\n cause: this.cause ? serializeError(this.cause) : undefined,\n app: {\n command: `${context.config.bin} ${process.argv.slice(2).join(\" \")}`,\n argv: process.argv,\n },\n device: {\n name: os.hostname(),\n family: os.type(),\n arch: os.arch(),\n },\n runtime: {\n name: process.release.name,\n version: process.version,\n },\n },\n },\n });\n\n await Sentry.flush(2000);\n }\n\n /**\n * Turns this error into a user-friendly message that explains what went wrong and how to fix it. A good write up of what an error should\n * look like can be found here: {@link https://clig.dev/#errors}\n */\n render(): string {\n const rendered = dedent`\n ${this.header()}\n\n ${this.body()}\n `;\n\n const footer = this.footer();\n if (!footer) return rendered;\n\n return dedent`\n ${rendered}\n\n ${footer}\n `;\n }\n\n protected header(): string {\n return `${this.code}: ${this.message}`;\n }\n\n protected footer(): string {\n if (this.isBug == IsBug.NO) return \"\";\n\n return dedent`\n ${this.isBug == IsBug.YES ? \"This is a bug\" : \"If you think this is a bug\"}, please submit an issue using the link below.\n\n https://github.com/gadget-inc/ggt/issues/new?template=bug_report.yml&error-id=${this.sentryEventId}\n `;\n }\n\n protected abstract body(): string;\n}\n\n/**\n * Universal Error object to json blob serializer.\n * Wraps `serialize-error` with some handy stuff, like special support for Got HTTP errors\n */\nexport function serializeError(error: Error | string | unknown): Record<string, any> {\n let serialized = baseSerializeError(isArray(error) ? new AggregateError(error) : error);\n if (typeof serialized == \"string\") {\n serialized = { message: serialized };\n }\n\n if (error instanceof HTTPError && error.name === \"RequestError\") {\n delete serialized[\"timings\"];\n serialized[\"options\"] = { method: error.options.method, url: error.options.url.toJSON() };\n serialized[\"responseBody\"] = inspect(error.response?.body);\n }\n\n return serialized;\n}\n\nexport enum IsBug {\n YES = \"yes\",\n NO = \"no\",\n MAYBE = \"maybe\",\n}\n\n/**\n * Our \"catch all\" error. If this error is thrown, we almost certainly have a bug.\n *\n * Whenever possible, we should use a more specific error so that we can provide more useful information.\n */\nexport class UnexpectedError extends BaseError {\n isBug = IsBug.YES;\n\n constructor(override cause: Error) {\n super(\"GGT_CLI_UNEXPECTED_ERROR\", \"An unexpected error occurred\");\n }\n\n protected body(): string {\n return cleanStack(this.cause.stack ?? this.stack);\n }\n}\n\nexport class ClientError extends BaseError {\n isBug = IsBug.MAYBE;\n\n constructor(readonly payload: Payload<any, any>, override cause: string | Error | readonly GraphQLError[] | CloseEvent | ErrorEvent) {\n super(\"GGT_CLI_CLIENT_ERROR\", \"An error occurred while communicating with Gadget\");\n\n // ErrorEvent and CloseEvent aren't serializable, so we reconstruct them into an object. We discard the `target` property because it's large and not that useful\n if (isErrorEvent(cause)) {\n this.cause = {\n type: cause.type,\n message: cause.message,\n error: serializeError(cause.error),\n } as any;\n } else if (isCloseEvent(cause)) {\n this.cause = {\n type: cause.type,\n code: cause.code,\n reason: cause.reason,\n wasClean: cause.wasClean,\n } as any;\n }\n }\n\n override body(): string {\n if (isGraphQLErrors(this.cause)) {\n if (this.cause.length > 1) {\n const errors = uniqBy(this.cause, \"message\");\n\n let output = \"Gadget responded with multiple errors:\\n\";\n for (let i = 0; i < errors.length; i++) {\n output += `\\n ${i + 1}. ${errors[i]?.message}`;\n }\n\n return output;\n } else {\n return dedent`\n Gadget responded with the following error:\n\n ${this.cause[0]?.message}\n `;\n }\n }\n\n if (isCloseEvent(this.cause)) {\n return \"The connection to Gadget closed unexpectedly.\";\n }\n\n if (isErrorEvent(this.cause) || isError(this.cause)) {\n return this.cause.message;\n }\n\n return this.cause;\n }\n}\n\nexport class YarnNotFoundError extends BaseError {\n isBug = IsBug.NO;\n\n constructor() {\n super(\"GGT_CLI_YARN_NOT_FOUND\", \"Yarn not found\");\n }\n\n protected body(): string {\n return dedent`\n Yarn must be installed to sync your application. You can install it by running:\n\n $ npm install --global yarn\n\n For more information, see: https://classic.yarnpkg.com/en/docs/install\n `;\n }\n}\n\nexport class FlagError<T extends { name: string; char?: string } = { name: string; char?: string }> extends BaseError {\n isBug = IsBug.NO;\n\n constructor(readonly flag: T, readonly description: string) {\n const name = flag.char ? `-${flag.char}, --${flag.name}` : `--${flag.name}`;\n super(\"GGT_CLI_FLAG_ERROR\", `Invalid value provided for the ${name} flag`);\n }\n\n protected body(): string {\n return this.description;\n }\n}\n\nexport class InvalidSyncFileError extends BaseError {\n isBug = IsBug.MAYBE;\n\n constructor(override readonly cause: unknown, readonly sync: Sync, readonly app: string | undefined) {\n super(\"GGT_CLI_INVALID_SYNC_FILE\", \"The .gadget/sync.json file was invalid or not found\");\n }\n\n protected body(): string {\n return dedent`\n We failed to read the Gadget metadata file in this directory:\n\n ${this.sync.dir}\n\n If you're running \\`ggt sync\\` for the first time, we recommend using an empty directory such as:\n\n ~/gadget/${this.app || \"<name of app>\"}\n\n Otherwise, if you're sure you want to sync the contents of that directory to Gadget, run \\`ggt sync\\` again with the \\`--force\\` flag:\n\n $ ggt sync ${this.sync.argv.join(\" \")} --force\n\n You will be prompted to either merge your local files with your remote ones or reset your local files to your remote ones.\n `;\n }\n}\n\nexport class InvalidSyncAppFlagError extends FlagError {\n constructor(sync: Sync, app: string) {\n super(\n { name: \"app\", char: \"a\" },\n dedent`\n You were about to sync the following app to the following directory:\n\n ${app} → ${sync.dir}\n\n However, that directory has already been synced with this app:\n\n ${sync.metadata.app}\n\n If you're sure that you want to sync \"${app}\" to \"${sync.dir}\", run \\`ggt sync\\` again with the \\`--force\\` flag:\n\n $ ggt sync ${sync.argv.join(\" \")} --force\n `\n );\n }\n}\n\nfunction isCloseEvent(e: any): e is SetOptional<CloseEvent, \"target\"> {\n return !isNil(e) && isString(e.type) && isNumber(e.code) && isString(e.reason) && isBoolean(e.wasClean);\n}\n\nfunction isErrorEvent(e: any): e is SetOptional<ErrorEvent, \"target\"> {\n return !isNil(e) && isString(e.type) && isString(e.message) && !isNil(e.error);\n}\n\nfunction isGraphQLErrors(e: any): e is readonly GraphQLError[] {\n return isArray(e) && e.every((e) => !isNil(e) && isString(e.message) && isArray(e.locations ?? []) && isArray(e.path ?? []));\n}\n"]}
@@ -12,10 +12,11 @@ exports.app = core_1.Flags.custom({
12
12
  char: "a",
13
13
  name: "app",
14
14
  summary: "The Gadget application this command applies to.",
15
+ helpValue: "<name>",
15
16
  parse: async (value) => {
16
- const name = /^(https:\/\/)?(?<name>[\w-]+)(\..*)?/.exec(value)?.groups?.["name"];
17
- if (!name)
18
- throw new errors_1.FlagError(exports.app, (0, ts_dedent_1.default) `
17
+ const parsed = /^(https:\/\/)?(?<name>[\w-]+)/.exec(value)?.groups?.["name"];
18
+ if (!parsed)
19
+ throw new errors_1.FlagError({ char: "a", name: "app" }, (0, ts_dedent_1.default) `
19
20
  The -a, --app flag must be the application's name, slug, or URL
20
21
 
21
22
  Examples:
@@ -25,12 +26,13 @@ exports.app = core_1.Flags.custom({
25
26
  --app https://my-app.gadget.app
26
27
  --app https://my-app.gadget.app/edit
27
28
  `);
29
+ const name = parsed.endsWith("--development") ? parsed.slice(0, -"--development".length) : parsed;
28
30
  const availableApps = await context_1.context.getAvailableApps();
29
31
  const foundApp = availableApps.find((a) => a.name == name || a.slug == name);
30
32
  if (foundApp) {
31
33
  return foundApp.slug;
32
34
  }
33
- throw new errors_1.FlagError(exports.app, availableApps.length > 0
35
+ throw new errors_1.FlagError({ char: "a", name: "app" }, availableApps.length > 0
34
36
  ? (0, ts_dedent_1.default) `
35
37
  Unknown application:
36
38
 
@@ -1 +1 @@
1
- {"version":3,"file":"flags.js","sourceRoot":"","sources":["../../src/utils/flags.ts"],"names":[],"mappings":";;;;AAAA,sCAAoC;AACpC,gFAA2C;AAC3C,mCAAgC;AAChC,kEAA+B;AAC/B,uCAAoC;AACpC,qCAAqC;AAExB,QAAA,GAAG,GAAG,YAAK,CAAC,MAAM,CAAC;IAC9B,IAAI,EAAE,GAAG;IACT,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,iDAAiD;IAC1D,KAAK,EAAE,KAAK,EAAE,KAAa,EAAE,EAAE;QAC7B,MAAM,IAAI,GAAG,sCAAsC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC,MAAM,CAAC,CAAC;QAClF,IAAI,CAAC,IAAI;YACP,MAAM,IAAI,kBAAS,CACjB,WAAG,EACH,IAAA,mBAAM,EAAA;;;;;;;;;SASL,CACF,CAAC;QAEJ,MAAM,aAAa,GAAG,MAAM,iBAAO,CAAC,gBAAgB,EAAE,CAAC;QACvD,MAAM,QAAQ,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC;QAC7E,IAAI,QAAQ,EAAE;YACZ,OAAO,QAAQ,CAAC,IAAI,CAAC;SACtB;QAED,MAAM,IAAI,kBAAS,CACjB,WAAG,EACH,aAAa,CAAC,MAAM,GAAG,CAAC;YACtB,CAAC,CAAC,IAAA,mBAAM,EAAA;;;kBAGE,KAAK;;;;kBAIL,IAAA,eAAM,EAAC,aAAa,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,0BAAW,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;iBAC9D,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;iBACZ,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC;iBAC7B,IAAI,CAAC,IAAI,CAAC;aAChB;YACL,CAAC,CAAC,IAAA,mBAAM,EAAA;;;kBAGE,KAAK;;;;;aAKV,CACR,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { Flags } from \"@oclif/core\";\nimport levenshtein from \"fast-levenshtein\";\nimport { sortBy } from \"lodash\";\nimport dedent from \"ts-dedent\";\nimport { context } from \"./context\";\nimport { FlagError } from \"./errors\";\n\nexport const app = Flags.custom({\n char: \"a\",\n name: \"app\",\n summary: \"The Gadget application this command applies to.\",\n parse: async (value: string) => {\n const name = /^(https:\\/\\/)?(?<name>[\\w-]+)(\\..*)?/.exec(value)?.groups?.[\"name\"];\n if (!name)\n throw new FlagError(\n app,\n dedent`\n The -a, --app flag must be the application's name, slug, or URL\n\n Examples:\n\n --app my-app\n --app my-app.gadget.app\n --app https://my-app.gadget.app\n --app https://my-app.gadget.app/edit\n `\n );\n\n const availableApps = await context.getAvailableApps();\n const foundApp = availableApps.find((a) => a.name == name || a.slug == name);\n if (foundApp) {\n return foundApp.slug;\n }\n\n throw new FlagError(\n app,\n availableApps.length > 0\n ? dedent`\n Unknown application:\n\n ${value}\n\n Did you mean one of these?\n\n ${sortBy(availableApps, (app) => levenshtein.get(app.slug, name))\n .slice(0, 10)\n .map((app) => `* ${app.slug}`)\n .join(\"\\n\")}\n `\n : dedent`\n Unknown application:\n\n ${value}\n\n It doesn't look like you have any applications.\n\n Visit https://gadget.new to create one!\n `\n );\n },\n});\n"]}
1
+ {"version":3,"file":"flags.js","sourceRoot":"","sources":["../../src/utils/flags.ts"],"names":[],"mappings":";;;;AAAA,sCAAoC;AACpC,gFAA2C;AAC3C,mCAAgC;AAChC,kEAA+B;AAC/B,uCAAoC;AACpC,qCAAqC;AAExB,QAAA,GAAG,GAAG,YAAK,CAAC,MAAM,CAAC;IAC9B,IAAI,EAAE,GAAG;IACT,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,iDAAiD;IAC1D,SAAS,EAAE,QAAQ;IACnB,KAAK,EAAE,KAAK,EAAE,KAAa,EAAE,EAAE;QAC7B,MAAM,MAAM,GAAG,+BAA+B,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC,MAAM,CAAC,CAAC;QAC7E,IAAI,CAAC,MAAM;YACT,MAAM,IAAI,kBAAS,CACjB,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,EAC1B,IAAA,mBAAM,EAAA;;;;;;;;;SASL,CACF,CAAC;QAEJ,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAElG,MAAM,aAAa,GAAG,MAAM,iBAAO,CAAC,gBAAgB,EAAE,CAAC;QACvD,MAAM,QAAQ,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC;QAC7E,IAAI,QAAQ,EAAE;YACZ,OAAO,QAAQ,CAAC,IAAI,CAAC;SACtB;QAED,MAAM,IAAI,kBAAS,CACjB,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,EAC1B,aAAa,CAAC,MAAM,GAAG,CAAC;YACtB,CAAC,CAAC,IAAA,mBAAM,EAAA;;;kBAGE,KAAK;;;;kBAIL,IAAA,eAAM,EAAC,aAAa,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,0BAAW,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;iBAC9D,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;iBACZ,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC;iBAC7B,IAAI,CAAC,IAAI,CAAC;aAChB;YACL,CAAC,CAAC,IAAA,mBAAM,EAAA;;;kBAGE,KAAK;;;;;aAKV,CACR,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { Flags } from \"@oclif/core\";\nimport levenshtein from \"fast-levenshtein\";\nimport { sortBy } from \"lodash\";\nimport dedent from \"ts-dedent\";\nimport { context } from \"./context\";\nimport { FlagError } from \"./errors\";\n\nexport const app = Flags.custom({\n char: \"a\",\n name: \"app\",\n summary: \"The Gadget application this command applies to.\",\n helpValue: \"<name>\",\n parse: async (value: string) => {\n const parsed = /^(https:\\/\\/)?(?<name>[\\w-]+)/.exec(value)?.groups?.[\"name\"];\n if (!parsed)\n throw new FlagError(\n { char: \"a\", name: \"app\" },\n dedent`\n The -a, --app flag must be the application's name, slug, or URL\n\n Examples:\n\n --app my-app\n --app my-app.gadget.app\n --app https://my-app.gadget.app\n --app https://my-app.gadget.app/edit\n `\n );\n\n const name = parsed.endsWith(\"--development\") ? parsed.slice(0, -\"--development\".length) : parsed;\n\n const availableApps = await context.getAvailableApps();\n const foundApp = availableApps.find((a) => a.name == name || a.slug == name);\n if (foundApp) {\n return foundApp.slug;\n }\n\n throw new FlagError(\n { char: \"a\", name: \"app\" },\n availableApps.length > 0\n ? dedent`\n Unknown application:\n\n ${value}\n\n Did you mean one of these?\n\n ${sortBy(availableApps, (app) => levenshtein.get(app.slug, name))\n .slice(0, 10)\n .map((app) => `* ${app.slug}`)\n .join(\"\\n\")}\n `\n : dedent`\n Unknown application:\n\n ${value}\n\n It doesn't look like you have any applications.\n\n Visit https://gadget.new to create one!\n `\n );\n },\n});\n"]}
@@ -1,4 +1,5 @@
1
1
  import { CommandHelp as OclifCommandHelp, Help as OclifHelp } from "@oclif/core";
2
+ import type { Example } from "@oclif/core/lib/interfaces";
2
3
  export default class Help extends OclifHelp {
3
4
  CommandHelpClass: typeof CommandHelp;
4
5
  }
@@ -10,5 +11,9 @@ declare class CommandHelp extends OclifCommandHelp {
10
11
  * This overrides the default behavior to just use the description as-is if it already exists.
11
12
  */
12
13
  protected description(): string | undefined;
14
+ /**
15
+ * Same as above, but for examples.
16
+ */
17
+ protected examples(examples: string | string[] | Example[] | undefined): string | undefined;
13
18
  }
14
19
  export {};
package/lib/utils/help.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const core_1 = require("@oclif/core");
4
+ const lodash_1 = require("lodash");
4
5
  class Help extends core_1.Help {
5
6
  constructor() {
6
7
  super(...arguments);
@@ -26,5 +27,17 @@ class CommandHelp extends core_1.CommandHelp {
26
27
  }
27
28
  return super.description();
28
29
  }
30
+ /**
31
+ * Same as above, but for examples.
32
+ */
33
+ examples(examples) {
34
+ if ((0, lodash_1.isString)(examples)) {
35
+ return examples;
36
+ }
37
+ if (Array.isArray(examples) && examples.every(lodash_1.isString)) {
38
+ return examples.join("\n\n");
39
+ }
40
+ return super.examples(examples);
41
+ }
29
42
  }
30
43
  //# sourceMappingURL=help.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"help.js","sourceRoot":"","sources":["../../src/utils/help.ts"],"names":[],"mappings":";;AAAA,sCAAiF;AAEjF,MAAqB,IAAK,SAAQ,WAAS;IAA3C;;QACE;;;;mBAA4B,WAAW;WAAC;IAC1C,CAAC;CAAA;AAFD,uBAEC;AAED,MAAM,WAAY,SAAQ,kBAAgB;IACxC;;;;;OAKG;IACgB,WAAW;QAC5B,IAAI,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE;YAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC;SACjC;QACD,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import { CommandHelp as OclifCommandHelp, Help as OclifHelp } from \"@oclif/core\";\n\nexport default class Help extends OclifHelp {\n override CommandHelpClass = CommandHelp;\n}\n\nclass CommandHelp extends OclifCommandHelp {\n /**\n * By default, oclif tries to format the description so that it fit's within the terminal window. However, if the description is already\n * formatted with `dedent`, then the description gets mangled and the help output is not pretty.\n *\n * This overrides the default behavior to just use the description as-is if it already exists.\n */\n protected override description(): string | undefined {\n if (this.command.description) {\n return this.command.description;\n }\n return super.description();\n }\n}\n"]}
1
+ {"version":3,"file":"help.js","sourceRoot":"","sources":["../../src/utils/help.ts"],"names":[],"mappings":";;AAAA,sCAAiF;AAEjF,mCAAkC;AAElC,MAAqB,IAAK,SAAQ,WAAS;IAA3C;;QACE;;;;mBAA4B,WAAW;WAAC;IAC1C,CAAC;CAAA;AAFD,uBAEC;AAED,MAAM,WAAY,SAAQ,kBAAgB;IACxC;;;;;OAKG;IACgB,WAAW;QAC5B,IAAI,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE;YAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC;SACjC;QACD,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;IAC7B,CAAC;IAED;;OAEG;IACgB,QAAQ,CAAC,QAAmD;QAC7E,IAAI,IAAA,iBAAQ,EAAC,QAAQ,CAAC,EAAE;YACtB,OAAO,QAAQ,CAAC;SACjB;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,iBAAQ,CAAC,EAAE;YACvD,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SAC9B;QACD,OAAO,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAClC,CAAC;CACF","sourcesContent":["import { CommandHelp as OclifCommandHelp, Help as OclifHelp } from \"@oclif/core\";\nimport type { Example } from \"@oclif/core/lib/interfaces\";\nimport { isString } from \"lodash\";\n\nexport default class Help extends OclifHelp {\n override CommandHelpClass = CommandHelp;\n}\n\nclass CommandHelp extends OclifCommandHelp {\n /**\n * By default, oclif tries to format the description so that it fit's within the terminal window. However, if the description is already\n * formatted with `dedent`, then the description gets mangled and the help output is not pretty.\n *\n * This overrides the default behavior to just use the description as-is if it already exists.\n */\n protected override description(): string | undefined {\n if (this.command.description) {\n return this.command.description;\n }\n return super.description();\n }\n\n /**\n * Same as above, but for examples.\n */\n protected override examples(examples: string | string[] | Example[] | undefined): string | undefined {\n if (isString(examples)) {\n return examples;\n }\n if (Array.isArray(examples) && examples.every(isString)) {\n return examples.join(\"\\n\\n\");\n }\n return super.examples(examples);\n }\n}\n"]}