@sentry/wizard 3.7.1 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/bin.ts +14 -0
  3. package/dist/bin.js +9 -0
  4. package/dist/bin.js.map +1 -1
  5. package/dist/lib/Helper/Logging.d.ts +1 -0
  6. package/dist/lib/Helper/Logging.js +2 -1
  7. package/dist/lib/Helper/Logging.js.map +1 -1
  8. package/dist/lib/Helper/__tests__/MergeConfig.js.map +1 -1
  9. package/dist/lib/Setup.js +4 -0
  10. package/dist/lib/Setup.js.map +1 -1
  11. package/dist/lib/Steps/ChooseIntegration.js +12 -26
  12. package/dist/lib/Steps/ChooseIntegration.js.map +1 -1
  13. package/dist/lib/Steps/Integrations/Cordova.js.map +1 -1
  14. package/dist/lib/Steps/Integrations/Electron.js.map +1 -1
  15. package/dist/lib/Steps/Integrations/MobileProject.js.map +1 -1
  16. package/dist/lib/Steps/Integrations/ReactNative.js +5 -5
  17. package/dist/lib/Steps/Integrations/ReactNative.js.map +1 -1
  18. package/dist/lib/Steps/Integrations/__tests__/ReactNative.js +5 -6
  19. package/dist/lib/Steps/Integrations/__tests__/ReactNative.js.map +1 -1
  20. package/dist/package.json +11 -7
  21. package/dist/src/apple/apple-wizard.js +31 -2
  22. package/dist/src/apple/apple-wizard.js.map +1 -1
  23. package/dist/src/apple/cocoapod.d.ts +2 -0
  24. package/dist/src/apple/cocoapod.js +122 -0
  25. package/dist/src/apple/cocoapod.js.map +1 -0
  26. package/dist/src/apple/code-tools.js +22 -12
  27. package/dist/src/apple/code-tools.js.map +1 -1
  28. package/dist/src/apple/fastlane.d.ts +2 -0
  29. package/dist/src/apple/fastlane.js +179 -0
  30. package/dist/src/apple/fastlane.js.map +1 -0
  31. package/dist/src/apple/templates.d.ts +1 -0
  32. package/dist/src/apple/templates.js +7 -3
  33. package/dist/src/apple/templates.js.map +1 -1
  34. package/dist/src/apple/xcode-manager.d.ts +1 -1
  35. package/dist/src/apple/xcode-manager.js +35 -28
  36. package/dist/src/apple/xcode-manager.js.map +1 -1
  37. package/dist/src/nextjs/nextjs-wizard.js +71 -81
  38. package/dist/src/nextjs/nextjs-wizard.js.map +1 -1
  39. package/dist/src/sourcemaps/sourcemaps-wizard.js +61 -46
  40. package/dist/src/sourcemaps/sourcemaps-wizard.js.map +1 -1
  41. package/dist/src/sourcemaps/tools/nextjs.d.ts +3 -0
  42. package/dist/src/sourcemaps/tools/nextjs.js +135 -0
  43. package/dist/src/sourcemaps/tools/nextjs.js.map +1 -0
  44. package/dist/src/sourcemaps/tools/sentry-cli.js +120 -16
  45. package/dist/src/sourcemaps/tools/sentry-cli.js.map +1 -1
  46. package/dist/src/sourcemaps/tools/vite.js +102 -12
  47. package/dist/src/sourcemaps/tools/vite.js.map +1 -1
  48. package/dist/src/sourcemaps/utils/detect-tool.d.ts +1 -1
  49. package/dist/src/sourcemaps/utils/detect-tool.js +1 -0
  50. package/dist/src/sourcemaps/utils/detect-tool.js.map +1 -1
  51. package/dist/src/sourcemaps/utils/other-wizards.js +35 -12
  52. package/dist/src/sourcemaps/utils/other-wizards.js.map +1 -1
  53. package/dist/src/sveltekit/sdk-setup.d.ts +9 -1
  54. package/dist/src/sveltekit/sdk-setup.js +73 -29
  55. package/dist/src/sveltekit/sdk-setup.js.map +1 -1
  56. package/dist/src/sveltekit/sveltekit-wizard.js +23 -13
  57. package/dist/src/sveltekit/sveltekit-wizard.js.map +1 -1
  58. package/dist/src/utils/ast-utils.d.ts +8 -0
  59. package/dist/src/utils/ast-utils.js +45 -0
  60. package/dist/src/utils/ast-utils.js.map +1 -0
  61. package/dist/src/utils/bash.d.ts +2 -1
  62. package/dist/src/utils/bash.js +14 -2
  63. package/dist/src/utils/bash.js.map +1 -1
  64. package/dist/src/utils/clack-utils.d.ts +7 -14
  65. package/dist/src/utils/clack-utils.js +46 -2
  66. package/dist/src/utils/clack-utils.js.map +1 -1
  67. package/dist/src/utils/debug.d.ts +2 -0
  68. package/dist/src/utils/debug.js +51 -0
  69. package/dist/src/utils/debug.js.map +1 -0
  70. package/dist/src/utils/package-json.d.ts +1 -1
  71. package/dist/src/utils/package-json.js.map +1 -1
  72. package/dist/src/utils/types.d.ts +24 -0
  73. package/dist/src/utils/types.js.map +1 -1
  74. package/dist/test/utils/ast-utils.test.d.ts +1 -0
  75. package/dist/test/utils/ast-utils.test.js +21 -0
  76. package/dist/test/utils/ast-utils.test.js.map +1 -0
  77. package/lib/Helper/Logging.ts +1 -1
  78. package/lib/Helper/__tests__/MergeConfig.ts +9 -4
  79. package/lib/Setup.ts +5 -0
  80. package/lib/Steps/ChooseIntegration.ts +13 -3
  81. package/lib/Steps/Integrations/Cordova.ts +3 -3
  82. package/lib/Steps/Integrations/Electron.ts +1 -2
  83. package/lib/Steps/Integrations/MobileProject.ts +1 -1
  84. package/lib/Steps/Integrations/ReactNative.ts +23 -17
  85. package/lib/Steps/Integrations/__tests__/ReactNative.ts +24 -15
  86. package/package.json +11 -7
  87. package/src/apple/apple-wizard.ts +35 -3
  88. package/src/apple/cocoapod.ts +57 -0
  89. package/src/apple/code-tools.ts +80 -57
  90. package/src/apple/fastlane.ts +160 -0
  91. package/src/apple/templates.ts +26 -10
  92. package/src/apple/xcode-manager.ts +137 -120
  93. package/src/nextjs/nextjs-wizard.ts +4 -13
  94. package/src/sourcemaps/sourcemaps-wizard.ts +40 -28
  95. package/src/sourcemaps/tools/nextjs.ts +114 -0
  96. package/src/sourcemaps/tools/sentry-cli.ts +134 -8
  97. package/src/sourcemaps/tools/vite.ts +101 -12
  98. package/src/sourcemaps/utils/detect-tool.ts +3 -1
  99. package/src/sourcemaps/utils/other-wizards.ts +32 -13
  100. package/src/sveltekit/sdk-setup.ts +122 -43
  101. package/src/sveltekit/sveltekit-wizard.ts +15 -6
  102. package/src/utils/ast-utils.ts +20 -0
  103. package/src/utils/bash.ts +43 -30
  104. package/src/utils/clack-utils.ts +42 -14
  105. package/src/utils/debug.ts +20 -0
  106. package/src/utils/package-json.ts +1 -1
  107. package/src/utils/types.ts +22 -0
  108. package/test/utils/ast-utils.test.ts +44 -0
  109. package/dist/src/sveltekit/sentry-cli-setup.d.ts +0 -2
  110. package/dist/src/sveltekit/sentry-cli-setup.js +0 -71
  111. package/dist/src/sveltekit/sentry-cli-setup.js.map +0 -1
  112. package/package-lock.json +0 -8910
  113. package/src/sveltekit/sentry-cli-setup.ts +0 -27
@@ -1 +1 @@
1
- {"version":3,"file":"vite.js","sourceRoot":"","sources":["../../../../src/sourcemaps/tools/vite.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yEAAyE;AACzE,wDAA+C;AAC/C,gDAA0B;AAC1B,uDAKiC;AACjC,yDAA+D;AAO/D,IAAM,cAAc,GAAG,UAAC,OAAgD;IACtE,OAAA,eAAK,CAAC,IAAI,CAAC,oDAEX,eAAK,CAAC,WAAW,CAAC,wDAAwD,CAAC,iEAIvE,eAAK,CAAC,WAAW,CACjB,6DAA6D,CAC9D,kGAIC,eAAK,CAAC,WAAW,CAAC,4FAEV,OAAO,CAAC,OAAO,mCACX,OAAO,CAAC,WAAW,gBAC/B,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,yBAAiB,OAAO,CAAC,GAAG,QAAI,CAAC,CAAC,CAAC,EAAE,cAExD,CAAC,kBAGR,CAAC;AArBA,CAqBA,CAAC;AAEI,IAAM,mBAAmB,GAC9B,UAAO,OAAO;;;;;;gBACN,KAAA,4BAAc,CAAA;;oBAClB,WAAW,EAAE,qBAAqB;;gBAChB,KAAA,kCAAmB,CAAA;sBACnC,qBAAqB;gBACrB,qBAAM,IAAA,+BAAiB,GAAE,EAAA;oBAJ7B,qBAAM,mBAEJ,mBAAgB,GAAE,4BAEhB,SAAyB,GAC1B;6BACD,EAAA;;gBANF,SAME,CAAC;gBAEH,iBAAK,CAAC,GAAG,CAAC,IAAI,CACZ,yCAAkC,eAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAQ,CACvE,CAAC;gBAEF,8FAA8F;gBAC9F,sCAAsC;gBACtC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;gBAErC,qBAAM,IAAA,8BAAgB,EACpB,IAAA,gBAAM,EAAC;wBACL,OAAO,EAAE,iCAAiC;wBAC1C,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;wBACnD,YAAY,EAAE,IAAI;qBACnB,CAAC,CACH,EAAA;;gBAND,SAMC,CAAC;gBAEF,qBAAM,IAAA,4CAA8B,EAAC,OAAO,CAAC,SAAS,CAAC,EAAA;;gBAAvD,SAAuD,CAAC;;;;KACzD,CAAC;AA3BS,QAAA,mBAAmB,uBA2B5B","sourcesContent":["// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack, { select } from '@clack/prompts';\nimport chalk from 'chalk';\nimport {\n abortIfCancelled,\n addDotEnvSentryBuildPluginFile,\n getPackageDotJson,\n installPackage,\n} from '../../utils/clack-utils';\nimport { hasPackageInstalled } from '../../utils/package-json';\n\nimport {\n SourceMapUploadToolConfigurationFunction,\n SourceMapUploadToolConfigurationOptions,\n} from './types';\n\nconst getCodeSnippet = (options: SourceMapUploadToolConfigurationOptions) =>\n chalk.gray(`\nimport { defineConfig } from \"vite\";\n${chalk.greenBright('import { sentryVitePlugin } from \"@sentry/vite-plugin\"')};\n\nexport default defineConfig({\n build: {\n ${chalk.greenBright(\n 'sourcemap: true, // Source map generation must be turned on',\n )}\n },\n plugins: [\n // Put the Sentry vite plugin after all other plugins\n ${chalk.greenBright(`sentryVitePlugin({\n authToken: process.env.SENTRY_AUTH_TOKEN,\n org: \"${options.orgSlug}\",\n project: \"${options.projectSlug}\",${\n options.selfHosted ? `\\n url: \"${options.url}\",` : ''\n }\n }),`)}\n ],\n});\n`);\n\nexport const configureVitePlugin: SourceMapUploadToolConfigurationFunction =\n async (options) => {\n await installPackage({\n packageName: '@sentry/vite-plugin',\n alreadyInstalled: hasPackageInstalled(\n '@sentry/vite-plugin',\n await getPackageDotJson(),\n ),\n });\n\n clack.log.step(\n `Add the following code to your ${chalk.bold('vite.config.js')} file:`,\n );\n\n // Intentially logging directly to console here so that the code can be copied/pasted directly\n // eslint-disable-next-line no-console\n console.log(getCodeSnippet(options));\n\n await abortIfCancelled(\n select({\n message: 'Did you copy the snippet above?',\n options: [{ label: 'Yes, continue!', value: true }],\n initialValue: true,\n }),\n );\n\n await addDotEnvSentryBuildPluginFile(options.authToken);\n };\n"]}
1
+ {"version":3,"file":"vite.js","sourceRoot":"","sources":["../../../../src/sourcemaps/tools/vite.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yEAAyE;AACzE,wDAA+C;AAC/C,4EAA4E;AAC5E,qCAAqD;AACrD,4EAA4E;AAC5E,4CAAiD;AAEjD,mDAAuC;AAEvC,gDAA0B;AAC1B,uDAKiC;AACjC,yDAA+D;AAM/D,mDAAyE;AAEzE,yCAA6B;AAC7B,qCAAyB;AACzB,2CAA0C;AAE1C,IAAM,cAAc,GAAG,UAAC,OAAgD;IACtE,OAAA,eAAK,CAAC,IAAI,CAAC,oDAEX,eAAK,CAAC,WAAW,CAAC,wDAAwD,CAAC,iEAIvE,eAAK,CAAC,WAAW,CACjB,6DAA6D,CAC9D,kGAIC,eAAK,CAAC,WAAW,CAAC,4FAEV,OAAO,CAAC,OAAO,mCACX,OAAO,CAAC,WAAW,gBAC/B,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,yBAAiB,OAAO,CAAC,GAAG,QAAI,CAAC,CAAC,CAAC,EAAE,cAExD,CAAC,kBAGR,CAAC;AArBA,CAqBA,CAAC;AAEI,IAAM,mBAAmB,GAC9B,UAAO,OAAO;;;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;oBAEhD,iBAAK,CAAC,GAAG,CAAC,IAAI,CACZ,yCAAkC,eAAK,CAAC,IAAI,CAAC,kBAAkB,CAAC,WAAQ,CACzE,CAAC;oBAEF,gGAAgG;oBAChG,sCAAsC;oBACtC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;oBAErC,qBAAM,IAAA,8BAAgB,EACpB,IAAA,gBAAM,EAAC;4BACL,OAAO,EAAE,iCAAiC;4BAC1C,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;4BACnD,YAAY,EAAE,IAAI;yBACnB,CAAC,CACH,EAAA;;oBAND,SAMC,CAAC;;;;;CACH","sourcesContent":["// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack, { select } from '@clack/prompts';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { generateCode, parseModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { addVitePlugin } from 'magicast/helpers';\n\nimport * as Sentry from '@sentry/node';\n\nimport chalk from 'chalk';\nimport {\n abortIfCancelled,\n addDotEnvSentryBuildPluginFile,\n getPackageDotJson,\n installPackage,\n} from '../../utils/clack-utils';\nimport { hasPackageInstalled } from '../../utils/package-json';\n\nimport {\n SourceMapUploadToolConfigurationFunction,\n SourceMapUploadToolConfigurationOptions,\n} from './types';\nimport { findScriptFile, hasSentryContent } from '../../utils/ast-utils';\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { debug } from '../../utils/debug';\n\nconst getCodeSnippet = (options: SourceMapUploadToolConfigurationOptions) =>\n chalk.gray(`\nimport { defineConfig } from \"vite\";\n${chalk.greenBright('import { sentryVitePlugin } from \"@sentry/vite-plugin\"')};\n\nexport default defineConfig({\n build: {\n ${chalk.greenBright(\n 'sourcemap: true, // Source map generation must be turned on',\n )}\n },\n plugins: [\n // Put the Sentry vite plugin after all other plugins\n ${chalk.greenBright(`sentryVitePlugin({\n authToken: process.env.SENTRY_AUTH_TOKEN,\n org: \"${options.orgSlug}\",\n project: \"${options.projectSlug}\",${\n options.selfHosted ? `\\n url: \"${options.url}\",` : ''\n }\n }),`)}\n ],\n});\n`);\n\nexport const configureVitePlugin: SourceMapUploadToolConfigurationFunction =\n async (options) => {\n await installPackage({\n packageName: '@sentry/vite-plugin',\n alreadyInstalled: hasPackageInstalled(\n '@sentry/vite-plugin',\n await getPackageDotJson(),\n ),\n });\n\n const viteConfigPath = findScriptFile(\n path.resolve(process.cwd(), 'vite.config'),\n );\n\n let successfullyAdded = false;\n if (viteConfigPath) {\n successfullyAdded = await addVitePluginToConfig(viteConfigPath, options);\n } else {\n Sentry.setTag('ast-mod-fail-reason', 'config-not-found');\n }\n\n if (successfullyAdded) {\n Sentry.setTag('ast-mod', 'success');\n } else {\n Sentry.setTag('ast-mod', 'fail');\n await showCopyPasteInstructions(\n path.basename(viteConfigPath || 'vite.config.js'),\n options,\n );\n }\n\n await addDotEnvSentryBuildPluginFile(options.authToken);\n };\n\nasync function addVitePluginToConfig(\n viteConfigPath: string,\n options: SourceMapUploadToolConfigurationOptions,\n): Promise<boolean> {\n try {\n const prettyViteConfigFilename = chalk.cyan(path.basename(viteConfigPath));\n\n const viteConfigContent = (\n await fs.promises.readFile(viteConfigPath)\n ).toString();\n\n const mod = parseModule(viteConfigContent);\n\n if (hasSentryContent(mod)) {\n clack.log.warn(\n `File ${prettyViteConfigFilename} already contains Sentry code. \nPlease follow the instruction below`,\n );\n Sentry.setTag('ast-mod-fail-reason', 'has-sentry-content');\n return false;\n }\n\n const { orgSlug: org, projectSlug: project, selfHosted, url } = options;\n\n addVitePlugin(mod, {\n imported: 'sentryVitePlugin',\n from: '@sentry/vite-plugin',\n constructor: 'sentryVitePlugin',\n options: {\n org,\n project,\n ...(selfHosted && { url }),\n },\n });\n\n const code = generateCode(mod.$ast).code;\n\n await fs.promises.writeFile(viteConfigPath, code);\n\n clack.log.success(\n `Added the Sentry Vite plugin to ${prettyViteConfigFilename}`,\n );\n\n return true;\n } catch (e) {\n debug(e);\n Sentry.setTag('ast-mod-fail-reason', 'insertion-fail');\n return false;\n }\n}\n\nasync function showCopyPasteInstructions(\n viteConfigFilename: string,\n options: SourceMapUploadToolConfigurationOptions,\n) {\n clack.log.step(\n `Add the following code to your ${chalk.cyan(viteConfigFilename)} file:`,\n );\n\n // Intentionally logging directly to console here so that the code can be copied/pasted directly\n // eslint-disable-next-line no-console\n console.log(getCodeSnippet(options));\n\n await abortIfCancelled(\n select({\n message: 'Did you copy the snippet above?',\n options: [{ label: 'Yes, continue!', value: true }],\n initialValue: true,\n }),\n );\n}\n"]}
@@ -1,3 +1,3 @@
1
- export type SupportedTools = 'webpack' | 'vite' | 'rollup' | 'esbuild' | 'tsc' | 'sentry-cli' | 'create-react-app' | 'angular';
1
+ export type SupportedTools = 'webpack' | 'vite' | 'rollup' | 'esbuild' | 'tsc' | 'sentry-cli' | 'create-react-app' | 'angular' | 'nextjs';
2
2
  export declare const TOOL_PACKAGE_MAP: Record<string, SupportedTools>;
3
3
  export declare function detectUsedTool(): Promise<SupportedTools>;
@@ -46,6 +46,7 @@ var package_json_1 = require("../../utils/package-json");
46
46
  exports.TOOL_PACKAGE_MAP = {
47
47
  '@angular/core': 'angular',
48
48
  'create-react-app': 'create-react-app',
49
+ next: 'nextjs',
49
50
  webpack: 'webpack',
50
51
  vite: 'vite',
51
52
  esbuild: 'esbuild',
@@ -1 +1 @@
1
- {"version":3,"file":"detect-tool.js","sourceRoot":"","sources":["../../../../src/sourcemaps/utils/detect-tool.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uDAA4D;AAC5D,yDAAwE;AAYxE,oDAAoD;AACpD,kFAAkF;AAClF,sEAAsE;AACtE,YAAY;AACC,QAAA,gBAAgB,GAAmC;IAC9D,eAAe,EAAE,SAAS;IAC1B,kBAAkB,EAAE,kBAAkB;IACtC,OAAO,EAAE,SAAS;IAClB,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;IAChB,UAAU,EAAE,KAAK;CAClB,CAAC;AAEF,SAAsB,cAAc;;;;;wBACd,qBAAM,IAAA,+BAAiB,GAAE,EAAA;;oBAAvC,WAAW,GAAG,SAAyB;oBAEvC,gBAAgB,GAAG,IAAA,2CAA4B,EACnD,MAAM,CAAC,IAAI,CAAC,wBAAgB,CAAC,EAC7B,WAAW,CACZ,CAAC;oBAEF,IAAI,gBAAgB,EAAE;wBACpB,sBAAO,wBAAgB,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAC;qBAChD;oBAED,sBAAO,YAAY,EAAC;;;;CACrB;AAbD,wCAaC","sourcesContent":["import { getPackageDotJson } from '../../utils/clack-utils';\nimport { findInstalledPackageFromList } from '../../utils/package-json';\n\nexport type SupportedTools =\n | 'webpack'\n | 'vite'\n | 'rollup'\n | 'esbuild'\n | 'tsc'\n | 'sentry-cli'\n | 'create-react-app'\n | 'angular';\n\n// A map of package names pointing to the tool slug.\n// The order is important, because we want to detect the most specific tool first.\n// For instance, webpack needs to come before tsc because typescript c\n// Similarly\nexport const TOOL_PACKAGE_MAP: Record<string, SupportedTools> = {\n '@angular/core': 'angular',\n 'create-react-app': 'create-react-app',\n webpack: 'webpack',\n vite: 'vite',\n esbuild: 'esbuild',\n rollup: 'rollup',\n typescript: 'tsc',\n};\n\nexport async function detectUsedTool(): Promise<SupportedTools> {\n const packageJson = await getPackageDotJson();\n\n const foundToolPackage = findInstalledPackageFromList(\n Object.keys(TOOL_PACKAGE_MAP),\n packageJson,\n );\n\n if (foundToolPackage) {\n return TOOL_PACKAGE_MAP[foundToolPackage.name];\n }\n\n return 'sentry-cli';\n}\n"]}
1
+ {"version":3,"file":"detect-tool.js","sourceRoot":"","sources":["../../../../src/sourcemaps/utils/detect-tool.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uDAA4D;AAC5D,yDAAwE;AAaxE,oDAAoD;AACpD,kFAAkF;AAClF,sEAAsE;AACtE,YAAY;AACC,QAAA,gBAAgB,GAAmC;IAC9D,eAAe,EAAE,SAAS;IAC1B,kBAAkB,EAAE,kBAAkB;IACtC,IAAI,EAAE,QAAQ;IACd,OAAO,EAAE,SAAS;IAClB,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;IAChB,UAAU,EAAE,KAAK;CAClB,CAAC;AAEF,SAAsB,cAAc;;;;;wBACd,qBAAM,IAAA,+BAAiB,GAAE,EAAA;;oBAAvC,WAAW,GAAG,SAAyB;oBAEvC,gBAAgB,GAAG,IAAA,2CAA4B,EACnD,MAAM,CAAC,IAAI,CAAC,wBAAgB,CAAC,EAC7B,WAAW,CACZ,CAAC;oBAEF,IAAI,gBAAgB,EAAE;wBACpB,sBAAO,wBAAgB,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAC;qBAChD;oBAED,sBAAO,YAAY,EAAC;;;;CACrB;AAbD,wCAaC","sourcesContent":["import { getPackageDotJson } from '../../utils/clack-utils';\nimport { findInstalledPackageFromList } from '../../utils/package-json';\n\nexport type SupportedTools =\n | 'webpack'\n | 'vite'\n | 'rollup'\n | 'esbuild'\n | 'tsc'\n | 'sentry-cli'\n | 'create-react-app'\n | 'angular'\n | 'nextjs';\n\n// A map of package names pointing to the tool slug.\n// The order is important, because we want to detect the most specific tool first.\n// For instance, webpack needs to come before tsc because typescript c\n// Similarly\nexport const TOOL_PACKAGE_MAP: Record<string, SupportedTools> = {\n '@angular/core': 'angular',\n 'create-react-app': 'create-react-app',\n next: 'nextjs',\n webpack: 'webpack',\n vite: 'vite',\n esbuild: 'esbuild',\n rollup: 'rollup',\n typescript: 'tsc',\n};\n\nexport async function detectUsedTool(): Promise<SupportedTools> {\n const packageJson = await getPackageDotJson();\n\n const foundToolPackage = findInstalledPackageFromList(\n Object.keys(TOOL_PACKAGE_MAP),\n packageJson,\n );\n\n if (foundToolPackage) {\n return TOOL_PACKAGE_MAP[foundToolPackage.name];\n }\n\n return 'sentry-cli';\n}\n"]}
@@ -58,6 +58,15 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
58
58
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
59
  }
60
60
  };
61
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
62
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
63
+ if (ar || !(i in from)) {
64
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
65
+ ar[i] = from[i];
66
+ }
67
+ }
68
+ return to.concat(ar || Array.prototype.slice.call(from));
69
+ };
61
70
  var __importDefault = (this && this.__importDefault) || function (mod) {
62
71
  return (mod && mod.__esModule) ? mod : { "default": mod };
63
72
  };
@@ -66,26 +75,26 @@ exports.checkIfMoreSuitableWizardExistsAndAskForRedirect = void 0;
66
75
  // @ts-ignore - clack is ESM and TS complains about that. It works though
67
76
  var prompts_1 = __importDefault(require("@clack/prompts"));
68
77
  var chalk_1 = __importDefault(require("chalk"));
69
- var nextjs_wizard_1 = require("../../nextjs/nextjs-wizard");
70
78
  var sveltekit_wizard_1 = require("../../sveltekit/sveltekit-wizard");
71
79
  var clack_utils_1 = require("../../utils/clack-utils");
72
80
  var package_json_1 = require("../../utils/package-json");
73
81
  var Sentry = __importStar(require("@sentry/node"));
82
+ var childProcess = __importStar(require("child_process"));
74
83
  var sdkMap = {
75
- '@sentry/nextjs': {
76
- frameworkName: 'Next.js',
77
- frameworkSlug: 'nextjs',
78
- frameworkPackage: 'next',
79
- sourcemapsDocsLink: 'https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#configure-source-maps',
80
- wizard: nextjs_wizard_1.runNextjsWizard,
81
- },
82
84
  '@sentry/sveltekit': {
83
85
  frameworkName: 'SvelteKit',
84
- frameworkSlug: 'sveltekit',
85
86
  frameworkPackage: '@sveltejs/kit',
86
87
  sourcemapsDocsLink: 'https://docs.sentry.io/platforms/javascript/guides/sveltekit/manual-setup/#configure-source-maps-upload',
88
+ troubleshootingDocsLink: 'https://docs.sentry.io/platforms/javascript/guides/sveltekit/sourcemaps/troubleshooting_js/',
87
89
  wizard: sveltekit_wizard_1.runSvelteKitWizard,
88
90
  },
91
+ '@sentry/react-native': {
92
+ frameworkName: 'React Native',
93
+ frameworkPackage: 'react-native',
94
+ sourcemapsDocsLink: 'https://docs.sentry.io/platforms/react-native/sourcemaps/',
95
+ troubleshootingDocsLink: 'https://docs.sentry.io/platforms/react-native/troubleshooting/#source-maps',
96
+ wizard: runReactNativeWizard,
97
+ },
89
98
  };
90
99
  function checkIfMoreSuitableWizardExistsAndAskForRedirect() {
91
100
  return __awaiter(this, void 0, void 0, function () {
@@ -135,12 +144,12 @@ function checkIfMoreSuitableWizardExists() {
135
144
  }
136
145
  function askForRedirect(sdkName) {
137
146
  return __awaiter(this, void 0, void 0, function () {
138
- var _a, frameworkName, sourcemapsDocsLink, frameworkSlug, wizard, nextStep, _b;
147
+ var _a, frameworkName, sourcemapsDocsLink, troubleshootingDocsLink, wizard, nextStep, _b;
139
148
  return __generator(this, function (_c) {
140
149
  switch (_c.label) {
141
150
  case 0:
142
- _a = sdkMap[sdkName], frameworkName = _a.frameworkName, sourcemapsDocsLink = _a.sourcemapsDocsLink, frameworkSlug = _a.frameworkSlug, wizard = _a.wizard;
143
- prompts_1.default.log.warn("".concat(chalk_1.default.yellow("It seems like you're using this wizard in a ".concat(frameworkName, " project.")), "\n\nWe recommend using our dedicated ").concat(frameworkName, " wizard instead of this wizard.\nThe ").concat(frameworkName, " wizard will set up our ").concat(sdkName, " SDK and also configure uploading source maps for you.\n\nIf you already tried the ").concat(frameworkName, " wizard and it didn't work for you, check out the following guides:\n\nManual source maps configuration for ").concat(frameworkName, ":\n").concat(sourcemapsDocsLink, "\n\nTroubleshooting Source Maps:\nhttps://docs.sentry.io/platforms/javascript/guides/").concat(frameworkSlug, "/sourcemaps/troubleshooting_js/\n"));
151
+ _a = sdkMap[sdkName], frameworkName = _a.frameworkName, sourcemapsDocsLink = _a.sourcemapsDocsLink, troubleshootingDocsLink = _a.troubleshootingDocsLink, wizard = _a.wizard;
152
+ prompts_1.default.log.warn("".concat(chalk_1.default.yellow("It seems like you're using this wizard in a ".concat(frameworkName, " project.")), "\n\nWe recommend using our dedicated ").concat(frameworkName, " wizard instead of this wizard.\nThe ").concat(frameworkName, " wizard will set up our ").concat(sdkName, " SDK and also configure uploading source maps for you.\n\nIf you already tried the ").concat(frameworkName, " wizard and it didn't work for you, check out the following guides:\n\nManual source maps configuration for ").concat(frameworkName, ":\n").concat(sourcemapsDocsLink, "\n\nTroubleshooting Source Maps:\n").concat(troubleshootingDocsLink, "\n"));
144
153
  return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)(prompts_1.default.select({
145
154
  message: "Do you want to run the ".concat(frameworkName, " wizard now?"),
146
155
  options: [
@@ -180,4 +189,18 @@ function askForRedirect(sdkName) {
180
189
  });
181
190
  });
182
191
  }
192
+ function runReactNativeWizard() {
193
+ var _a = __spreadArray([], process.argv, true), runner = _a[0], wizardArgs = _a.slice(1);
194
+ wizardArgs.push('--integration', 'reactNative');
195
+ try {
196
+ childProcess.spawnSync(runner, wizardArgs, {
197
+ cwd: process.cwd(),
198
+ stdio: 'inherit',
199
+ });
200
+ }
201
+ catch (_b) {
202
+ return Promise.reject();
203
+ }
204
+ return Promise.resolve();
205
+ }
183
206
  //# sourceMappingURL=other-wizards.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"other-wizards.js","sourceRoot":"","sources":["../../../../src/sourcemaps/utils/other-wizards.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yEAAyE;AACzE,2DAAmC;AACnC,gDAA0B;AAC1B,4DAA6D;AAC7D,qEAAsE;AAEtE,uDAIiC;AACjC,yDAGkC;AAElC,mDA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;;CAEtB","sourcesContent":["// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\nimport chalk from 'chalk';\nimport { runNextjsWizard } from '../../nextjs/nextjs-wizard';\nimport { runSvelteKitWizard } from '../../sveltekit/sveltekit-wizard';\n\nimport {\n abort,\n abortIfCancelled,\n getPackageDotJson,\n} from '../../utils/clack-utils';\nimport {\n findInstalledPackageFromList,\n hasPackageInstalled,\n} from '../../utils/package-json';\n\nimport * as Sentry from '@sentry/node';\nimport { WizardOptions } from '../../utils/types';\n\ntype WizardFunction = (options: WizardOptions) => Promise<void>;\n\ntype FrameworkInfo = {\n frameworkName: string;\n frameworkSlug: string;\n frameworkPackage: string;\n sourcemapsDocsLink: string;\n wizard: WizardFunction;\n};\n\nconst sdkMap: Record<string, FrameworkInfo> = {\n '@sentry/nextjs': {\n frameworkName: 'Next.js',\n frameworkSlug: 'nextjs',\n frameworkPackage: 'next',\n sourcemapsDocsLink:\n 'https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#configure-source-maps',\n wizard: runNextjsWizard,\n },\n '@sentry/sveltekit': {\n frameworkName: 'SvelteKit',\n frameworkSlug: 'sveltekit',\n frameworkPackage: '@sveltejs/kit',\n sourcemapsDocsLink:\n 'https://docs.sentry.io/platforms/javascript/guides/sveltekit/manual-setup/#configure-source-maps-upload',\n wizard: runSvelteKitWizard,\n },\n};\n\nexport async function checkIfMoreSuitableWizardExistsAndAskForRedirect(): Promise<\n WizardFunction | undefined\n> {\n const sdkName = await checkIfMoreSuitableWizardExists();\n\n if (!sdkName) {\n return undefined;\n }\n\n return await askForRedirect(sdkName);\n}\n\nasync function checkIfMoreSuitableWizardExists(): Promise<string | undefined> {\n Sentry.setTag('using-wrong-wizard', false);\n\n const packageJson = await getPackageDotJson();\n\n const installedSdkPackage = findInstalledPackageFromList(\n Object.keys(sdkMap),\n packageJson,\n );\n\n if (!installedSdkPackage) {\n return undefined;\n }\n\n const sdkPackageName = installedSdkPackage.name;\n\n const { frameworkPackage } = sdkMap[sdkPackageName];\n\n if (!hasPackageInstalled(frameworkPackage, packageJson)) {\n // The user has installed the SDK but not the framework.\n // Maybe it's a false positive and the user is using a different framework.\n // Let's not redirect them to the framework wizard in that case.\n return undefined;\n }\n\n Sentry.setTag('using-wrong-wizard', true);\n\n return sdkPackageName;\n}\n\nasync function askForRedirect(\n sdkName: string,\n): Promise<WizardFunction | undefined> {\n const { frameworkName, sourcemapsDocsLink, frameworkSlug, wizard } =\n sdkMap[sdkName];\n\n clack.log.warn(\n `${chalk.yellow(\n `It seems like you're using this wizard in a ${frameworkName} project.`,\n )}\n\nWe recommend using our dedicated ${frameworkName} wizard instead of this wizard.\nThe ${frameworkName} wizard will set up our ${sdkName} SDK and also configure uploading source maps for you.\n\nIf you already tried the ${frameworkName} wizard and it didn't work for you, check out the following guides:\n\nManual source maps configuration for ${frameworkName}:\n${sourcemapsDocsLink}\n\nTroubleshooting Source Maps:\nhttps://docs.sentry.io/platforms/javascript/guides/${frameworkSlug}/sourcemaps/troubleshooting_js/\n`,\n );\n\n const nextStep: 'redirect' | 'continue' | 'stop' = await abortIfCancelled(\n clack.select({\n message: `Do you want to run the ${frameworkName} wizard now?`,\n options: [\n {\n label: 'Yes',\n value: 'redirect',\n hint: `${chalk.green('Recommended')}`,\n },\n {\n label: 'No, continue with this wizard',\n value: 'continue',\n },\n {\n label: \"No, I'll check out the guides \",\n value: 'stop',\n hint: 'Exit this wizard',\n },\n ],\n }),\n );\n\n Sentry.setTag('wrong-wizard-decision', nextStep);\n\n switch (nextStep) {\n case 'redirect':\n return wizard;\n case 'stop':\n await abort('Exiting Wizard', 0);\n break;\n default:\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"other-wizards.js","sourceRoot":"","sources":["../../../../src/sourcemaps/utils/other-wizards.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yEAA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AM,IAAA,mBAAK,EAAC,gBAAgB,EAAE,CAAC,CAAC,EAAA;;oBAAhC,SAAgC,CAAC;oBACjC,wBAAM;wBAEN,sBAAO,SAAS,EAAC;;;;;CAEtB;AAED,SAAS,oBAAoB;IACrB,IAAA,uBAA8B,OAAO,CAAC,IAAI,OAAC,EAA1C,MAAM,QAAA,EAAK,UAAU,cAAqB,CAAC;IAClD,UAAU,CAAC,IAAI,CAAC,eAAe,EAAE,aAAa,CAAC,CAAC;IAEhD,IAAI;QACF,YAAY,CAAC,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE;YACzC,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE;YAClB,KAAK,EAAE,SAAS;SACjB,CAAC,CAAC;KACJ;IAAC,WAAM;QACN,OAAO,OAAO,CAAC,MAAM,EAAE,CAAC;KACzB;IAED,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\nimport chalk from 'chalk';\nimport { runSvelteKitWizard } from '../../sveltekit/sveltekit-wizard';\n\nimport {\n abort,\n abortIfCancelled,\n getPackageDotJson,\n} from '../../utils/clack-utils';\nimport {\n findInstalledPackageFromList,\n hasPackageInstalled,\n} from '../../utils/package-json';\n\nimport * as Sentry from '@sentry/node';\nimport { WizardOptions } from '../../utils/types';\n\nimport * as childProcess from 'child_process';\n\ntype WizardFunction = (options: WizardOptions) => Promise<void>;\n\ntype FrameworkInfo = {\n frameworkName: string;\n frameworkPackage: string;\n troubleshootingDocsLink: string;\n sourcemapsDocsLink: string;\n wizard: WizardFunction;\n};\n\nconst sdkMap: Record<string, FrameworkInfo> = {\n '@sentry/sveltekit': {\n frameworkName: 'SvelteKit',\n frameworkPackage: '@sveltejs/kit',\n sourcemapsDocsLink:\n 'https://docs.sentry.io/platforms/javascript/guides/sveltekit/manual-setup/#configure-source-maps-upload',\n troubleshootingDocsLink:\n 'https://docs.sentry.io/platforms/javascript/guides/sveltekit/sourcemaps/troubleshooting_js/',\n wizard: runSvelteKitWizard,\n },\n '@sentry/react-native': {\n frameworkName: 'React Native',\n frameworkPackage: 'react-native',\n sourcemapsDocsLink:\n 'https://docs.sentry.io/platforms/react-native/sourcemaps/',\n troubleshootingDocsLink:\n 'https://docs.sentry.io/platforms/react-native/troubleshooting/#source-maps',\n wizard: runReactNativeWizard,\n },\n};\n\nexport async function checkIfMoreSuitableWizardExistsAndAskForRedirect(): Promise<\n WizardFunction | undefined\n> {\n const sdkName = await checkIfMoreSuitableWizardExists();\n\n if (!sdkName) {\n return undefined;\n }\n\n return await askForRedirect(sdkName);\n}\n\nasync function checkIfMoreSuitableWizardExists(): Promise<string | undefined> {\n Sentry.setTag('using-wrong-wizard', false);\n\n const packageJson = await getPackageDotJson();\n\n const installedSdkPackage = findInstalledPackageFromList(\n Object.keys(sdkMap),\n packageJson,\n );\n\n if (!installedSdkPackage) {\n return undefined;\n }\n\n const sdkPackageName = installedSdkPackage.name;\n\n const { frameworkPackage } = sdkMap[sdkPackageName];\n\n if (!hasPackageInstalled(frameworkPackage, packageJson)) {\n // The user has installed the SDK but not the framework.\n // Maybe it's a false positive and the user is using a different framework.\n // Let's not redirect them to the framework wizard in that case.\n return undefined;\n }\n\n Sentry.setTag('using-wrong-wizard', true);\n\n return sdkPackageName;\n}\n\nasync function askForRedirect(\n sdkName: string,\n): Promise<WizardFunction | undefined> {\n const { frameworkName, sourcemapsDocsLink, troubleshootingDocsLink, wizard } =\n sdkMap[sdkName];\n\n clack.log.warn(\n `${chalk.yellow(\n `It seems like you're using this wizard in a ${frameworkName} project.`,\n )}\n\nWe recommend using our dedicated ${frameworkName} wizard instead of this wizard.\nThe ${frameworkName} wizard will set up our ${sdkName} SDK and also configure uploading source maps for you.\n\nIf you already tried the ${frameworkName} wizard and it didn't work for you, check out the following guides:\n\nManual source maps configuration for ${frameworkName}:\n${sourcemapsDocsLink}\n\nTroubleshooting Source Maps:\n${troubleshootingDocsLink}\n`,\n );\n\n const nextStep: 'redirect' | 'continue' | 'stop' = await abortIfCancelled(\n clack.select({\n message: `Do you want to run the ${frameworkName} wizard now?`,\n options: [\n {\n label: 'Yes',\n value: 'redirect',\n hint: `${chalk.green('Recommended')}`,\n },\n {\n label: 'No, continue with this wizard',\n value: 'continue',\n },\n {\n label: \"No, I'll check out the guides \",\n value: 'stop',\n hint: 'Exit this wizard',\n },\n ],\n }),\n );\n\n Sentry.setTag('wrong-wizard-decision', nextStep);\n\n switch (nextStep) {\n case 'redirect':\n return wizard;\n case 'stop':\n await abort('Exiting Wizard', 0);\n break;\n default:\n return undefined;\n }\n}\n\nfunction runReactNativeWizard(): Promise<void> {\n const [runner, ...wizardArgs] = [...process.argv];\n wizardArgs.push('--integration', 'reactNative');\n\n try {\n childProcess.spawnSync(runner, wizardArgs, {\n cwd: process.cwd(),\n stdio: 'inherit',\n });\n } catch {\n return Promise.reject();\n }\n\n return Promise.resolve();\n}\n"]}
@@ -9,5 +9,13 @@ export type PartialSvelteConfig = {
9
9
  };
10
10
  };
11
11
  };
12
- export declare function createOrMergeSvelteKitFiles(dsn: string, svelteConfig: PartialSvelteConfig): Promise<void>;
12
+ type ProjectInfo = {
13
+ dsn: string;
14
+ org: string;
15
+ project: string;
16
+ selfHosted: boolean;
17
+ url: string;
18
+ };
19
+ export declare function createOrMergeSvelteKitFiles(projectInfo: ProjectInfo, svelteConfig: PartialSvelteConfig): Promise<void>;
13
20
  export declare function loadSvelteConfig(): Promise<PartialSvelteConfig>;
21
+ export {};
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
14
  if (k2 === undefined) k2 = k;
4
15
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -84,18 +95,21 @@ var magicast_1 = require("magicast");
84
95
  var helpers_1 = require("magicast/helpers");
85
96
  var templates_1 = require("./templates");
86
97
  var clack_utils_1 = require("../utils/clack-utils");
98
+ var debug_1 = require("../utils/debug");
99
+ var ast_utils_1 = require("../utils/ast-utils");
87
100
  var SVELTE_CONFIG_FILE = 'svelte.config.js';
88
- function createOrMergeSvelteKitFiles(dsn, svelteConfig) {
101
+ function createOrMergeSvelteKitFiles(projectInfo, svelteConfig) {
89
102
  return __awaiter(this, void 0, void 0, function () {
90
- var _a, clientHooksPath, serverHooksPath, originalClientHooksFile, originalServerHooksFile, viteConfig, fileEnding;
103
+ var _a, clientHooksPath, serverHooksPath, originalClientHooksFile, originalServerHooksFile, viteConfig, fileEnding, dsn;
91
104
  return __generator(this, function (_b) {
92
105
  switch (_b.label) {
93
106
  case 0:
94
107
  _a = getHooksConfigDirs(svelteConfig), clientHooksPath = _a.clientHooksPath, serverHooksPath = _a.serverHooksPath;
95
- originalClientHooksFile = findHooksFile(clientHooksPath);
96
- originalServerHooksFile = findHooksFile(serverHooksPath);
97
- viteConfig = findHooksFile(path.resolve(process.cwd(), 'vite.config'));
108
+ originalClientHooksFile = (0, ast_utils_1.findScriptFile)(clientHooksPath);
109
+ originalServerHooksFile = (0, ast_utils_1.findScriptFile)(serverHooksPath);
110
+ viteConfig = (0, ast_utils_1.findScriptFile)(path.resolve(process.cwd(), 'vite.config'));
98
111
  fileEnding = (0, clack_utils_1.isUsingTypeScript)() ? 'ts' : 'js';
112
+ dsn = projectInfo.dsn;
99
113
  if (!!originalClientHooksFile) return [3 /*break*/, 2];
100
114
  prompts_1.default.log.info('No client hooks file found, creating a new one.');
101
115
  return [4 /*yield*/, createNewHooksFile("".concat(clientHooksPath, ".").concat(fileEnding), 'client', dsn)];
@@ -123,7 +137,7 @@ function createOrMergeSvelteKitFiles(dsn, svelteConfig) {
123
137
  _b.label = 8;
124
138
  case 8:
125
139
  if (!viteConfig) return [3 /*break*/, 10];
126
- return [4 /*yield*/, modifyViteConfig(viteConfig)];
140
+ return [4 /*yield*/, modifyViteConfig(viteConfig, projectInfo)];
127
141
  case 9:
128
142
  _b.sent();
129
143
  _b.label = 10;
@@ -153,15 +167,6 @@ function getHooksConfigDirs(svelteConfig) {
153
167
  serverHooksPath: userServerHooksPath || defaultServerHooksPath,
154
168
  };
155
169
  }
156
- /**
157
- * Checks if a hooks file exists and returns the full path to the file with the correct file type.
158
- */
159
- function findHooksFile(hooksFile) {
160
- var possibleFileTypes = ['.js', '.ts', '.mjs'];
161
- return possibleFileTypes
162
- .map(function (type) { return "".concat(hooksFile).concat(type); })
163
- .find(function (file) { return fs.existsSync(file); });
164
- }
165
170
  /**
166
171
  * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest
167
172
  */
@@ -205,9 +210,10 @@ function mergeHooksFile(hooksFile, hookType, dsn) {
205
210
  case 0: return [4 /*yield*/, (0, magicast_1.loadFile)(hooksFile)];
206
211
  case 1:
207
212
  originalHooksMod = _a.sent();
208
- if (hasSentryContent(path.basename(hooksFile), originalHooksMod.$code)) {
213
+ if ((0, ast_utils_1.hasSentryContent)(originalHooksMod)) {
209
214
  // We don't want to mess with files that already have Sentry content.
210
215
  // Let's just bail out at this point.
216
+ prompts_1.default.log.warn("File ".concat(chalk_1.default.cyan(path.basename(hooksFile)), " already contains Sentry code.\nSkipping adding Sentry functionality to."));
211
217
  return [2 /*return*/];
212
218
  }
213
219
  originalHooksMod.imports.$add({
@@ -369,14 +375,6 @@ function wrapHandle(mod) {
369
375
  // It's possible sequence is already imported. in this case, magicast throws but that's fine.
370
376
  }
371
377
  }
372
- /** Checks if the Sentry SvelteKit SDK is already mentioned in the file */
373
- function hasSentryContent(fileName, fileContent) {
374
- if (fileContent.includes('@sentry/sveltekit')) {
375
- prompts_1.default.log.warn("File ".concat(chalk_1.default.cyan(path.basename(fileName)), " already contains Sentry code.\nSkipping adding Sentry functionality to ").concat(chalk_1.default.cyan(path.basename(fileName)), "."));
376
- return true;
377
- }
378
- return false;
379
- }
380
378
  function loadSvelteConfig() {
381
379
  return __awaiter(this, void 0, void 0, function () {
382
380
  var configFilePath, configUrl, svelteConfigModule, e_1;
@@ -410,33 +408,79 @@ function loadSvelteConfig() {
410
408
  });
411
409
  }
412
410
  exports.loadSvelteConfig = loadSvelteConfig;
413
- function modifyViteConfig(viteConfigPath) {
411
+ function modifyViteConfig(viteConfigPath, projectInfo) {
414
412
  return __awaiter(this, void 0, void 0, function () {
415
- var viteConfigContent, viteModule, code;
413
+ var viteConfigContent, org, project, url, selfHosted, viteModule, code, e_2;
416
414
  return __generator(this, function (_a) {
417
415
  switch (_a.label) {
418
416
  case 0: return [4 /*yield*/, fs.promises.readFile(viteConfigPath, 'utf-8')];
419
417
  case 1:
420
418
  viteConfigContent = (_a.sent()).toString();
421
- if (hasSentryContent(viteConfigPath, viteConfigContent)) {
419
+ org = projectInfo.org, project = projectInfo.project, url = projectInfo.url, selfHosted = projectInfo.selfHosted;
420
+ _a.label = 2;
421
+ case 2:
422
+ _a.trys.push([2, 4, , 6]);
423
+ viteModule = (0, magicast_1.parseModule)(viteConfigContent);
424
+ if ((0, ast_utils_1.hasSentryContent)(viteModule)) {
425
+ prompts_1.default.log.warn("File ".concat(chalk_1.default.cyan(path.basename(viteConfigPath)), " already contains Sentry code.\nSkipping adding Sentry functionality to."));
422
426
  return [2 /*return*/];
423
427
  }
424
- viteModule = (0, magicast_1.parseModule)(viteConfigContent);
425
428
  (0, helpers_1.addVitePlugin)(viteModule, {
426
429
  imported: 'sentrySvelteKit',
427
430
  from: '@sentry/sveltekit',
428
431
  constructor: 'sentrySvelteKit',
432
+ options: {
433
+ sourceMapsUploadOptions: __assign({ org: org, project: project }, (selfHosted && { url: url })),
434
+ },
429
435
  index: 0,
430
436
  });
431
437
  code = (0, magicast_1.generateCode)(viteModule.$ast).code;
432
438
  return [4 /*yield*/, fs.promises.writeFile(viteConfigPath, code)];
433
- case 2:
439
+ case 3:
440
+ _a.sent();
441
+ return [3 /*break*/, 6];
442
+ case 4:
443
+ e_2 = _a.sent();
444
+ (0, debug_1.debug)(e_2);
445
+ return [4 /*yield*/, showFallbackViteCopyPasteSnippet(viteConfigPath, getViteConfigCodeSnippet(org, project, selfHosted, url))];
446
+ case 5:
447
+ _a.sent();
448
+ return [3 /*break*/, 6];
449
+ case 6: return [2 /*return*/];
450
+ }
451
+ });
452
+ });
453
+ }
454
+ function showFallbackViteCopyPasteSnippet(viteConfigPath, codeSnippet) {
455
+ return __awaiter(this, void 0, void 0, function () {
456
+ var viteConfigFilename;
457
+ return __generator(this, function (_a) {
458
+ switch (_a.label) {
459
+ case 0:
460
+ viteConfigFilename = path.basename(viteConfigPath);
461
+ prompts_1.default.log.warning("Couldn't automatically modify your ".concat(chalk_1.default.cyan(viteConfigFilename), "\n").concat(chalk_1.default.dim("This sometimes happens when we encounter more complex vite configs.\nIt may not seem like it but sometimes our magical powers are limited ;)")));
462
+ prompts_1.default.log.info("But don't worry - it's super easy to do this yourself!");
463
+ prompts_1.default.log.step("Add the following code to your ".concat(chalk_1.default.cyan(viteConfigFilename), ":"));
464
+ // Intentionally logging to console here for easier copy/pasting
465
+ // eslint-disable-next-line no-console
466
+ console.log(codeSnippet);
467
+ return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)(prompts_1.default.select({
468
+ message: 'Did you copy the snippet above?',
469
+ options: [
470
+ { label: 'Yes!', value: true, hint: "Great, that's already it!" },
471
+ ],
472
+ initialValue: true,
473
+ }))];
474
+ case 1:
434
475
  _a.sent();
435
476
  return [2 /*return*/];
436
477
  }
437
478
  });
438
479
  });
439
480
  }
481
+ var getViteConfigCodeSnippet = function (org, project, selfHosted, url) {
482
+ return chalk_1.default.gray("\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n".concat(chalk_1.default.greenBright("import { sentrySvelteKit } from '@sentry/sveltekit'"), "\n\nexport default defineConfig({\n plugins: [\n // Make sure `sentrySvelteKit` is registered before `sveltekit`\n ").concat(chalk_1.default.greenBright("sentrySvelteKit({\n sourceMapsUploadOptions: {\n org: '".concat(org, "',\n project: '").concat(project, "',").concat(selfHosted ? "\n url: '".concat(url, "',") : '', "\n } \n }),")), "\n sveltekit(),\n ]\n});\n"));
483
+ };
440
484
  /**
441
485
  * We want to insert the init call on top of the file but after all import statements
442
486
  */
@@ -1 +1 @@
1
- {"version":3,"file":"sdk-setup.js","sourceRoot":"","sources":["../../../src/sveltekit/sdk-setup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,qCAAyB;AACzB,yCAA6B;AAC7B,uCAA2B;AAC3B,gDAA0B;AAE1B,yEAAyE;AACzE,2DAAmC;AAGnC,4EAA4E;AAC5E,qCAAyE;AACzE,4EAA4E;AAC5E,4CAAiD;AACjD,yCAA6E;AAC7E,oDAAyD;AAEzD,IAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAc9C,SAAsB,2BAA2B,CAC/C,GAAW,EACX,YAAiC;;;;;;oBAE3B,KAAuC,kBAAkB,CAAC,YAAY,CAAC,EAArE,eAAe,qBAAA,EAAE,eAAe,qBAAA,CAAsC;oBAGxE,uBAAuB,GAAG,aAAa,CAAC,eAAe,CAAC,CAAC;oBACzD,uBAAuB,GAAG,aAAa,CAAC,eAAe,CAAC,CAAC;oBAEzD,UAAU,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,aAAa,CAAC,CAAC,CAAC;oBAEvE,UAAU,GAAG,IAAA,+BAAiB,GAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;yBAEjD,CAAC,uBAAuB,EAAxB,wBAAwB;oBAC1B,iBAAK,CAAC,GAAG,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C,CAAC,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,CAAC;QAC7D,CAAC,CAAC,CAAC,CAAC;IACN,OAAO,sBAAsB,CAAC;AAChC,CAAC","sourcesContent":["import type { ExportNamedDeclaration, Program } from '@babel/types';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as url from 'url';\nimport chalk from 'chalk';\n\n// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport type { ProxifiedModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { builders, generateCode, loadFile, parseModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { addVitePlugin } from 'magicast/helpers';\nimport { getClientHooksTemplate, getServerHooksTemplate } from './templates';\nimport { isUsingTypeScript } from '../utils/clack-utils';\n\nconst SVELTE_CONFIG_FILE = 'svelte.config.js';\n\nexport type PartialSvelteConfig = {\n kit?: {\n files?: {\n hooks?: {\n client?: string;\n server?: string;\n };\n routes?: string;\n };\n };\n};\n\nexport async function createOrMergeSvelteKitFiles(\n dsn: string,\n svelteConfig: PartialSvelteConfig,\n): Promise<void> {\n const { clientHooksPath, serverHooksPath } = getHooksConfigDirs(svelteConfig);\n\n // full file paths with correct file ending (or undefined if not found)\n const originalClientHooksFile = findHooksFile(clientHooksPath);\n const originalServerHooksFile = findHooksFile(serverHooksPath);\n\n const viteConfig = findHooksFile(path.resolve(process.cwd(), 'vite.config'));\n\n const fileEnding = isUsingTypeScript() ? 'ts' : 'js';\n\n if (!originalClientHooksFile) {\n clack.log.info('No client hooks file found, creating a new one.');\n await createNewHooksFile(`${clientHooksPath}.${fileEnding}`, 'client', dsn);\n }\n if (!originalServerHooksFile) {\n clack.log.info('No server hooks file found, creating a new one.');\n await createNewHooksFile(`${serverHooksPath}.${fileEnding}`, 'server', dsn);\n }\n\n if (originalClientHooksFile) {\n await mergeHooksFile(originalClientHooksFile, 'client', dsn);\n }\n if (originalServerHooksFile) {\n await mergeHooksFile(originalServerHooksFile, 'server', dsn);\n }\n\n if (viteConfig) {\n await modifyViteConfig(viteConfig);\n }\n}\n\n/**\n * Attempts to read the svelte.config.js file to find the location of the hooks files.\n * If users specified a custom location, we'll use that. Otherwise, we'll use the default.\n */\nfunction getHooksConfigDirs(svelteConfig: PartialSvelteConfig): {\n clientHooksPath: string;\n serverHooksPath: string;\n} {\n const relativeUserClientHooksPath = svelteConfig?.kit?.files?.hooks?.client;\n const relativeUserServerHooksPath = svelteConfig?.kit?.files?.hooks?.server;\n const userClientHooksPath =\n relativeUserClientHooksPath &&\n path.resolve(process.cwd(), relativeUserClientHooksPath);\n const userServerHooksPath =\n relativeUserServerHooksPath &&\n path.resolve(process.cwd(), relativeUserServerHooksPath);\n\n const defaulHooksDir = path.resolve(process.cwd(), 'src');\n const defaultClientHooksPath = path.resolve(defaulHooksDir, 'hooks.client'); // file ending missing on purpose\n const defaultServerHooksPath = path.resolve(defaulHooksDir, 'hooks.server'); // same here\n\n return {\n clientHooksPath: userClientHooksPath || defaultClientHooksPath,\n serverHooksPath: userServerHooksPath || defaultServerHooksPath,\n };\n}\n\n/**\n * Checks if a hooks file exists and returns the full path to the file with the correct file type.\n */\nfunction findHooksFile(hooksFile: string): string | undefined {\n const possibleFileTypes = ['.js', '.ts', '.mjs'];\n return possibleFileTypes\n .map((type) => `${hooksFile}${type}`)\n .find((file) => fs.existsSync(file));\n}\n\n/**\n * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest\n */\nasync function createNewHooksFile(\n hooksFileDest: string,\n hooktype: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const filledTemplate =\n hooktype === 'client'\n ? getClientHooksTemplate(dsn)\n : getServerHooksTemplate(dsn);\n\n await fs.promises.mkdir(path.dirname(hooksFileDest), { recursive: true });\n await fs.promises.writeFile(hooksFileDest, filledTemplate);\n\n clack.log.success(`Created ${hooksFileDest}`);\n}\n\n/**\n * Merges the users' hooks file with Sentry-related code.\n *\n * Both hooks:\n * - add import * as Sentry\n * - add Sentry.init\n * - add handleError hook wrapper\n *\n * Additionally in Server hook:\n * - add handle hook handler\n */\nasync function mergeHooksFile(\n hooksFile: string,\n hookType: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const originalHooksMod = await loadFile(hooksFile);\n if (hasSentryContent(path.basename(hooksFile), originalHooksMod.$code)) {\n // We don't want to mess with files that already have Sentry content.\n // Let's just bail out at this point.\n return;\n }\n\n originalHooksMod.imports.$add({\n from: '@sentry/sveltekit',\n imported: '*',\n local: 'Sentry',\n });\n\n if (hookType === 'client') {\n insertClientInitCall(dsn, originalHooksMod);\n } else {\n insertServerInitCall(dsn, originalHooksMod);\n }\n\n wrapHandleError(originalHooksMod);\n\n if (hookType === 'server') {\n wrapHandle(originalHooksMod);\n }\n\n const modifiedCode = originalHooksMod.generate().code;\n\n await fs.promises.writeFile(hooksFile, modifiedCode);\n\n clack.log.success(`Added Sentry code to ${hooksFile}`);\n}\n\nfunction insertClientInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n const initCallComment = `\n // If you don't want to use Session Replay, remove the \\`Replay\\` integration, \n // \\`replaysSessionSampleRate\\` and \\`replaysOnErrorSampleRate\\` options.`;\n\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n integrations: [builders.newExpression('Sentry.Replay')],\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCallWithComment = builders.raw(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n `${initCallComment}\\n${generateCode(initCall).code}`,\n );\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCallWithComment).code,\n );\n}\n\nfunction insertServerInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n });\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCall).code,\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandleError(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandleError = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.raw(\n `Sentry.handleErrorWithSentry(${userCode.replace(\n 'handleError',\n '_handleError',\n )})`,\n );\n // because magicast doesn't overwrite the original function export, we need to remove it manually\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `Sentry.handleErrorWithSentry(${stringifiedUserCode})`;\n });\n }\n });\n\n if (!foundHandleError) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.functionCall(\n 'Sentry.handleErrorWithSentry',\n );\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandle(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandle = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n foundHandle = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw(\n `sequence(Sentry.sentryHandle(), ${userCode.replace(\n 'handle',\n '_handle',\n )})`,\n );\n // because of an issue with magicast, we need to remove the original export\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `sequence(Sentry.sentryHandle(), ${stringifiedUserCode})`;\n foundHandle = true;\n });\n }\n });\n\n if (!foundHandle) {\n // can't use builders.functionCall here because it doesn't yet\n // support member expressions (Sentry.sentryHandle()) in args\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw('sequence(Sentry.sentryHandle())');\n }\n\n try {\n mod.imports.$add({\n from: '@sveltejs/kit/hooks',\n imported: 'sequence',\n local: 'sequence',\n });\n } catch (_) {\n // It's possible sequence is already imported. in this case, magicast throws but that's fine.\n }\n}\n\n/** Checks if the Sentry SvelteKit SDK is already mentioned in the file */\nfunction hasSentryContent(fileName: string, fileContent: string): boolean {\n if (fileContent.includes('@sentry/sveltekit')) {\n clack.log.warn(\n `File ${chalk.cyan(path.basename(fileName))} already contains Sentry code.\nSkipping adding Sentry functionality to ${chalk.cyan(\n path.basename(fileName),\n )}.`,\n );\n return true;\n }\n return false;\n}\n\nexport async function loadSvelteConfig(): Promise<PartialSvelteConfig> {\n const configFilePath = path.join(process.cwd(), SVELTE_CONFIG_FILE);\n\n try {\n if (!fs.existsSync(configFilePath)) {\n return {};\n }\n\n const configUrl = url.pathToFileURL(configFilePath).href;\n const svelteConfigModule = (await import(configUrl)) as {\n default: PartialSvelteConfig;\n };\n\n return svelteConfigModule?.default || {};\n } catch (e: unknown) {\n clack.log.error(`Couldn't load ${SVELTE_CONFIG_FILE}.\nPlease make sure, you're running this wizard with Node 16 or newer`);\n clack.log.info(\n chalk.dim(\n typeof e === 'object' && e != null && 'toString' in e\n ? e.toString()\n : typeof e === 'string'\n ? e\n : 'Unknown error',\n ),\n );\n\n return {};\n }\n}\n\nasync function modifyViteConfig(viteConfigPath: string): Promise<void> {\n const viteConfigContent = (\n await fs.promises.readFile(viteConfigPath, 'utf-8')\n ).toString();\n\n if (hasSentryContent(viteConfigPath, viteConfigContent)) {\n return;\n }\n\n const viteModule = parseModule(viteConfigContent);\n\n addVitePlugin(viteModule, {\n imported: 'sentrySvelteKit',\n from: '@sentry/sveltekit',\n constructor: 'sentrySvelteKit',\n index: 0,\n });\n\n const code = generateCode(viteModule.$ast).code;\n await fs.promises.writeFile(viteConfigPath, code);\n}\n\n/**\n * We want to insert the init call on top of the file but after all import statements\n */\nfunction getInitCallInsertionIndex(originalHooksModAST: Program): number {\n // We need to deep-copy here because reverse mutates in place\n const copiedBodyNodes = [...originalHooksModAST.body];\n const lastImportDeclaration = copiedBodyNodes\n .reverse()\n .find((node) => node.type === 'ImportDeclaration');\n\n const initCallInsertionIndex = lastImportDeclaration\n ? originalHooksModAST.body.indexOf(lastImportDeclaration) + 1\n : 0;\n return initCallInsertionIndex;\n}\n"]}
1
+ {"version":3,"file":"sdk-setup.js","sourceRoot":"","sources":["../../../src/sveltekit/sdk-setup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,qCAAyB;AACzB,yCAA6B;AAC7B,uCAA2B;AAC3B,gDAA0B;AAE1B,yEAAyE;AACzE,2DAAmC;AAGnC,4EAA4E;AAC5E,qCAAyE;AACzE,4EAA4E;AAC5E,4CAAiD;AACjD,yCAA6E;AAC7E,oDAA2E;AAC3E,wCAAuC;AACvC,gDAAsE;AAEtE,IAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAsB9C,SAAsB,2BAA2B,CAC/C,WAAwB,EACxB,YAAiC;;;;;;oBAE3B,KAAuC,kBAAkB,CAAC,YAAY,CAAC,EAArE,eAAe,qBAAA,EAAE,eAAe,qBAAA,CAAsC;oBAGxE,uBAAuB,GAAG,IAAA,0BAAc,EAAC,eAAe,CAAC,CAAC;oBAC1D,uBAAuB,GAAG,IAAA,0BAAc,EAAC,eAAe,CAAC,CAAC;oBAE1D,UAAU,GAAG,IAAA,0BAAc,EAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,aAAa,CAAC,CAAC,CAAC;oBAExE,UAAU,GAAG,IAAA,+BAAiB,GAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;oBAE7C,GAAG,GAAK,WAAW,IAAhB,CAAiB;yBAExB,CAAC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;QAC7D,CAAC,CAAC,CAAC,CAAC;IACN,OAAO,sBAAsB,CAAC;AAChC,CAAC","sourcesContent":["import type { ExportNamedDeclaration, Program } from '@babel/types';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as url from 'url';\nimport chalk from 'chalk';\n\n// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport type { ProxifiedModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { builders, generateCode, loadFile, parseModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { addVitePlugin } from 'magicast/helpers';\nimport { getClientHooksTemplate, getServerHooksTemplate } from './templates';\nimport { abortIfCancelled, isUsingTypeScript } from '../utils/clack-utils';\nimport { debug } from '../utils/debug';\nimport { findScriptFile, hasSentryContent } from '../utils/ast-utils';\n\nconst SVELTE_CONFIG_FILE = 'svelte.config.js';\n\nexport type PartialSvelteConfig = {\n kit?: {\n files?: {\n hooks?: {\n client?: string;\n server?: string;\n };\n routes?: string;\n };\n };\n};\n\ntype ProjectInfo = {\n dsn: string;\n org: string;\n project: string;\n selfHosted: boolean;\n url: string;\n};\n\nexport async function createOrMergeSvelteKitFiles(\n projectInfo: ProjectInfo,\n svelteConfig: PartialSvelteConfig,\n): Promise<void> {\n const { clientHooksPath, serverHooksPath } = getHooksConfigDirs(svelteConfig);\n\n // full file paths with correct file ending (or undefined if not found)\n const originalClientHooksFile = findScriptFile(clientHooksPath);\n const originalServerHooksFile = findScriptFile(serverHooksPath);\n\n const viteConfig = findScriptFile(path.resolve(process.cwd(), 'vite.config'));\n\n const fileEnding = isUsingTypeScript() ? 'ts' : 'js';\n\n const { dsn } = projectInfo;\n\n if (!originalClientHooksFile) {\n clack.log.info('No client hooks file found, creating a new one.');\n await createNewHooksFile(`${clientHooksPath}.${fileEnding}`, 'client', dsn);\n }\n if (!originalServerHooksFile) {\n clack.log.info('No server hooks file found, creating a new one.');\n await createNewHooksFile(`${serverHooksPath}.${fileEnding}`, 'server', dsn);\n }\n\n if (originalClientHooksFile) {\n await mergeHooksFile(originalClientHooksFile, 'client', dsn);\n }\n if (originalServerHooksFile) {\n await mergeHooksFile(originalServerHooksFile, 'server', dsn);\n }\n\n if (viteConfig) {\n await modifyViteConfig(viteConfig, projectInfo);\n }\n}\n\n/**\n * Attempts to read the svelte.config.js file to find the location of the hooks files.\n * If users specified a custom location, we'll use that. Otherwise, we'll use the default.\n */\nfunction getHooksConfigDirs(svelteConfig: PartialSvelteConfig): {\n clientHooksPath: string;\n serverHooksPath: string;\n} {\n const relativeUserClientHooksPath = svelteConfig?.kit?.files?.hooks?.client;\n const relativeUserServerHooksPath = svelteConfig?.kit?.files?.hooks?.server;\n const userClientHooksPath =\n relativeUserClientHooksPath &&\n path.resolve(process.cwd(), relativeUserClientHooksPath);\n const userServerHooksPath =\n relativeUserServerHooksPath &&\n path.resolve(process.cwd(), relativeUserServerHooksPath);\n\n const defaulHooksDir = path.resolve(process.cwd(), 'src');\n const defaultClientHooksPath = path.resolve(defaulHooksDir, 'hooks.client'); // file ending missing on purpose\n const defaultServerHooksPath = path.resolve(defaulHooksDir, 'hooks.server'); // same here\n\n return {\n clientHooksPath: userClientHooksPath || defaultClientHooksPath,\n serverHooksPath: userServerHooksPath || defaultServerHooksPath,\n };\n}\n\n/**\n * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest\n */\nasync function createNewHooksFile(\n hooksFileDest: string,\n hooktype: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const filledTemplate =\n hooktype === 'client'\n ? getClientHooksTemplate(dsn)\n : getServerHooksTemplate(dsn);\n\n await fs.promises.mkdir(path.dirname(hooksFileDest), { recursive: true });\n await fs.promises.writeFile(hooksFileDest, filledTemplate);\n\n clack.log.success(`Created ${hooksFileDest}`);\n}\n\n/**\n * Merges the users' hooks file with Sentry-related code.\n *\n * Both hooks:\n * - add import * as Sentry\n * - add Sentry.init\n * - add handleError hook wrapper\n *\n * Additionally in Server hook:\n * - add handle hook handler\n */\nasync function mergeHooksFile(\n hooksFile: string,\n hookType: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const originalHooksMod = await loadFile(hooksFile);\n if (hasSentryContent(originalHooksMod)) {\n // We don't want to mess with files that already have Sentry content.\n // Let's just bail out at this point.\n clack.log.warn(\n `File ${chalk.cyan(\n path.basename(hooksFile),\n )} already contains Sentry code.\nSkipping adding Sentry functionality to.`,\n );\n return;\n }\n\n originalHooksMod.imports.$add({\n from: '@sentry/sveltekit',\n imported: '*',\n local: 'Sentry',\n });\n\n if (hookType === 'client') {\n insertClientInitCall(dsn, originalHooksMod);\n } else {\n insertServerInitCall(dsn, originalHooksMod);\n }\n\n wrapHandleError(originalHooksMod);\n\n if (hookType === 'server') {\n wrapHandle(originalHooksMod);\n }\n\n const modifiedCode = originalHooksMod.generate().code;\n\n await fs.promises.writeFile(hooksFile, modifiedCode);\n\n clack.log.success(`Added Sentry code to ${hooksFile}`);\n}\n\nfunction insertClientInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n const initCallComment = `\n // If you don't want to use Session Replay, remove the \\`Replay\\` integration, \n // \\`replaysSessionSampleRate\\` and \\`replaysOnErrorSampleRate\\` options.`;\n\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n integrations: [builders.newExpression('Sentry.Replay')],\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCallWithComment = builders.raw(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n `${initCallComment}\\n${generateCode(initCall).code}`,\n );\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCallWithComment).code,\n );\n}\n\nfunction insertServerInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n });\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCall).code,\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandleError(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandleError = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.raw(\n `Sentry.handleErrorWithSentry(${userCode.replace(\n 'handleError',\n '_handleError',\n )})`,\n );\n // because magicast doesn't overwrite the original function export, we need to remove it manually\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `Sentry.handleErrorWithSentry(${stringifiedUserCode})`;\n });\n }\n });\n\n if (!foundHandleError) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.functionCall(\n 'Sentry.handleErrorWithSentry',\n );\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandle(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandle = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n foundHandle = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw(\n `sequence(Sentry.sentryHandle(), ${userCode.replace(\n 'handle',\n '_handle',\n )})`,\n );\n // because of an issue with magicast, we need to remove the original export\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `sequence(Sentry.sentryHandle(), ${stringifiedUserCode})`;\n foundHandle = true;\n });\n }\n });\n\n if (!foundHandle) {\n // can't use builders.functionCall here because it doesn't yet\n // support member expressions (Sentry.sentryHandle()) in args\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw('sequence(Sentry.sentryHandle())');\n }\n\n try {\n mod.imports.$add({\n from: '@sveltejs/kit/hooks',\n imported: 'sequence',\n local: 'sequence',\n });\n } catch (_) {\n // It's possible sequence is already imported. in this case, magicast throws but that's fine.\n }\n}\n\nexport async function loadSvelteConfig(): Promise<PartialSvelteConfig> {\n const configFilePath = path.join(process.cwd(), SVELTE_CONFIG_FILE);\n\n try {\n if (!fs.existsSync(configFilePath)) {\n return {};\n }\n\n const configUrl = url.pathToFileURL(configFilePath).href;\n const svelteConfigModule = (await import(configUrl)) as {\n default: PartialSvelteConfig;\n };\n\n return svelteConfigModule?.default || {};\n } catch (e: unknown) {\n clack.log.error(`Couldn't load ${SVELTE_CONFIG_FILE}.\nPlease make sure, you're running this wizard with Node 16 or newer`);\n clack.log.info(\n chalk.dim(\n typeof e === 'object' && e != null && 'toString' in e\n ? e.toString()\n : typeof e === 'string'\n ? e\n : 'Unknown error',\n ),\n );\n\n return {};\n }\n}\n\nasync function modifyViteConfig(\n viteConfigPath: string,\n projectInfo: ProjectInfo,\n): Promise<void> {\n const viteConfigContent = (\n await fs.promises.readFile(viteConfigPath, 'utf-8')\n ).toString();\n\n const { org, project, url, selfHosted } = projectInfo;\n\n try {\n const viteModule = parseModule(viteConfigContent);\n\n if (hasSentryContent(viteModule)) {\n clack.log.warn(\n `File ${chalk.cyan(\n path.basename(viteConfigPath),\n )} already contains Sentry code.\nSkipping adding Sentry functionality to.`,\n );\n return;\n }\n\n addVitePlugin(viteModule, {\n imported: 'sentrySvelteKit',\n from: '@sentry/sveltekit',\n constructor: 'sentrySvelteKit',\n options: {\n sourceMapsUploadOptions: {\n org,\n project,\n ...(selfHosted && { url }),\n },\n },\n index: 0,\n });\n\n const code = generateCode(viteModule.$ast).code;\n\n await fs.promises.writeFile(viteConfigPath, code);\n } catch (e) {\n debug(e);\n await showFallbackViteCopyPasteSnippet(\n viteConfigPath,\n getViteConfigCodeSnippet(org, project, selfHosted, url),\n );\n }\n}\n\nasync function showFallbackViteCopyPasteSnippet(\n viteConfigPath: string,\n codeSnippet: string,\n) {\n const viteConfigFilename = path.basename(viteConfigPath);\n\n clack.log.warning(\n `Couldn't automatically modify your ${chalk.cyan(viteConfigFilename)}\n${chalk.dim(`This sometimes happens when we encounter more complex vite configs.\nIt may not seem like it but sometimes our magical powers are limited ;)`)}`,\n );\n\n clack.log.info(\"But don't worry - it's super easy to do this yourself!\");\n\n clack.log.step(\n `Add the following code to your ${chalk.cyan(viteConfigFilename)}:`,\n );\n\n // Intentionally logging to console here for easier copy/pasting\n // eslint-disable-next-line no-console\n console.log(codeSnippet);\n\n await abortIfCancelled(\n clack.select({\n message: 'Did you copy the snippet above?',\n options: [\n { label: 'Yes!', value: true, hint: \"Great, that's already it!\" },\n ],\n initialValue: true,\n }),\n );\n}\n\nconst getViteConfigCodeSnippet = (\n org: string,\n project: string,\n selfHosted: boolean,\n url: string,\n) =>\n chalk.gray(`\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n${chalk.greenBright(\"import { sentrySvelteKit } from '@sentry/sveltekit'\")}\n\nexport default defineConfig({\n plugins: [\n // Make sure \\`sentrySvelteKit\\` is registered before \\`sveltekit\\`\n ${chalk.greenBright(`sentrySvelteKit({\n sourceMapsUploadOptions: {\n org: '${org}',\n project: '${project}',${selfHosted ? `\\n url: '${url}',` : ''}\n } \n }),`)}\n sveltekit(),\n ]\n});\n`);\n\n/**\n * We want to insert the init call on top of the file but after all import statements\n */\nfunction getInitCallInsertionIndex(originalHooksModAST: Program): number {\n // We need to deep-copy here because reverse mutates in place\n const copiedBodyNodes = [...originalHooksModAST.body];\n const lastImportDeclaration = copiedBodyNodes\n .reverse()\n .find((node) => node.type === 'ImportDeclaration');\n\n const initCallInsertionIndex = lastImportDeclaration\n ? originalHooksModAST.body.indexOf(lastImportDeclaration) + 1\n : 0;\n return initCallInsertionIndex;\n}\n"]}
@@ -47,10 +47,9 @@ var clack_utils_1 = require("../utils/clack-utils");
47
47
  var package_json_1 = require("../utils/package-json");
48
48
  var sdk_example_1 = require("./sdk-example");
49
49
  var sdk_setup_1 = require("./sdk-setup");
50
- var sentry_cli_setup_1 = require("./sentry-cli-setup");
51
50
  function runSvelteKitWizard(options) {
52
51
  return __awaiter(this, void 0, void 0, function () {
53
- var packageJson, _a, sentryUrl, selfHosted, _b, projects, apiKeys, selectedProject, dsn, svelteConfig, e_1, e_2;
52
+ var packageJson, _a, sentryUrl, selfHosted, _b, projects, apiKeys, selectedProject, svelteConfig, e_1, e_2;
54
53
  return __generator(this, function (_c) {
55
54
  switch (_c.label) {
56
55
  case 0:
@@ -86,20 +85,25 @@ function runSvelteKitWizard(options) {
86
85
  })];
87
86
  case 7:
88
87
  _c.sent();
89
- return [4 /*yield*/, (0, sentry_cli_setup_1.setupCLIConfig)(apiKeys.token, selectedProject, sentryUrl)];
88
+ return [4 /*yield*/, (0, clack_utils_1.addSentryCliRc)(apiKeys.token)];
90
89
  case 8:
91
90
  _c.sent();
92
- dsn = selectedProject.keys[0].dsn.public;
93
91
  return [4 /*yield*/, (0, sdk_setup_1.loadSvelteConfig)()];
94
92
  case 9:
95
93
  svelteConfig = _c.sent();
96
94
  _c.label = 10;
97
95
  case 10:
98
- _c.trys.push([10, 12, , 13]);
99
- return [4 /*yield*/, (0, sdk_setup_1.createOrMergeSvelteKitFiles)(dsn, svelteConfig)];
96
+ _c.trys.push([10, 12, , 14]);
97
+ return [4 /*yield*/, (0, sdk_setup_1.createOrMergeSvelteKitFiles)({
98
+ dsn: selectedProject.keys[0].dsn.public,
99
+ org: selectedProject.organization.slug,
100
+ project: selectedProject.slug,
101
+ selfHosted: selfHosted,
102
+ url: sentryUrl,
103
+ }, svelteConfig)];
100
104
  case 11:
101
105
  _c.sent();
102
- return [3 /*break*/, 13];
106
+ return [3 /*break*/, 14];
103
107
  case 12:
104
108
  e_1 = _c.sent();
105
109
  prompts_1.default.log.error('Error while setting up the SvelteKit SDK:');
@@ -108,19 +112,22 @@ function runSvelteKitWizard(options) {
108
112
  : typeof e_1 === 'string'
109
113
  ? e_1
110
114
  : 'Unknown error'));
111
- return [2 /*return*/];
115
+ return [4 /*yield*/, (0, clack_utils_1.abort)('Exiting Wizard')];
112
116
  case 13:
113
- _c.trys.push([13, 15, , 16]);
117
+ _c.sent();
118
+ return [2 /*return*/];
119
+ case 14:
120
+ _c.trys.push([14, 16, , 18]);
114
121
  return [4 /*yield*/, (0, sdk_example_1.createExamplePage)(svelteConfig, {
115
122
  selfHosted: selfHosted,
116
123
  url: sentryUrl,
117
124
  orgSlug: selectedProject.organization.slug,
118
125
  projectId: selectedProject.id,
119
126
  })];
120
- case 14:
121
- _c.sent();
122
- return [3 /*break*/, 16];
123
127
  case 15:
128
+ _c.sent();
129
+ return [3 /*break*/, 18];
130
+ case 16:
124
131
  e_2 = _c.sent();
125
132
  prompts_1.default.log.error('Error while creating an example page to test Sentry:');
126
133
  prompts_1.default.log.info(chalk_1.default.dim(typeof e_2 === 'object' && e_2 != null && 'toString' in e_2
@@ -128,8 +135,11 @@ function runSvelteKitWizard(options) {
128
135
  : typeof e_2 === 'string'
129
136
  ? e_2
130
137
  : 'Unknown error'));
138
+ return [4 /*yield*/, (0, clack_utils_1.abort)('Exiting Wizard')];
139
+ case 17:
140
+ _c.sent();
131
141
  return [2 /*return*/];
132
- case 16:
142
+ case 18:
133
143
  prompts_1.default.outro("\n".concat(chalk_1.default.green('Successfully installed the Sentry SvelteKit SDK!'), "\n\n").concat(chalk_1.default.cyan('You can validate your setup by starting your dev environment (`npm run dev`) and visiting "/sentry-example".'), "\n\nCheck out the SDK documentation for further configuration:\nhttps://docs.sentry.io/platforms/javascript/guides/sveltekit/\n "));
134
144
  return [2 /*return*/];
135
145
  }