Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/cli/src/lib/wizard/cloudflare/cloudflare-wizard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,10 @@ async function runCloudflareWizardWithTelemetry(
binding: "CF_VERSION_METADATA",
},
},
{ removeCompatibilityFlags: ["nodejs_als"] },
{
removeCompatibilityFlags: ["nodejs_als"],
keepCompatibilityDate: true,
},
),
);

Expand Down
89 changes: 37 additions & 52 deletions packages/cli/src/lib/wizard/cloudflare/sdk-setup.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/**
* Write the Sentry initialization into the worker entry point: wrap an
* existing handler, or create an entry point when the Wrangler config names
* none.
* Write the Sentry initialization into the worker entry point: wrap the
* existing handler, or create a starter worker and wrap that.
*/

import chalk from "chalk";
Expand All @@ -21,8 +20,10 @@ import {
import { wrapWorkerWithSentry } from "./wrap-worker.js";

/**
* Creates or updates the main worker file with Sentry initialization.
* Currently focused on Cloudflare Workers
* Wraps the worker entry point with Sentry initialization. When the entry
* point the Wrangler config names, or the default one, doesn't exist yet, it
* creates a starter worker there first, so every path ends with a wrapped
* worker.
*/
export async function createSentryInitFile(
dsn: string,
Expand All @@ -31,65 +32,49 @@ export async function createSentryInitFile(
},
reduceDataCollection: boolean,
): Promise<void> {
const entryPointFromConfig = getEntryPointFromWranglerConfig();
const entryPoint = getEntryPointFromWranglerConfig() ?? defaultEntryPoint;
const entryPointPath = path.join(process.cwd(), entryPoint);

if (!entryPointFromConfig) {
if (existsSync(entryPointPath)) {
clack.log.info(`Found existing entry point: ${chalk.cyan(entryPoint)}`);
} else {
clack.log.info(
"No entry point found in wrangler config, creating a new one.",
`No worker found at ${chalk.cyan(entryPoint)}, creating a new one.`,
);

const cloudflareWorkerTemplate = getCloudflareWorkerTemplateWithHandler();

await promises.mkdir(
path.join(process.cwd(), path.dirname(defaultEntryPoint)),
{
recursive: true,
},
);
await promises.mkdir(path.dirname(entryPointPath), { recursive: true });
await promises.writeFile(
path.join(process.cwd(), defaultEntryPoint),
cloudflareWorkerTemplate,
entryPointPath,
getCloudflareWorkerTemplateWithHandler(/\.[cm]?tsx?$/.test(entryPoint)),
{ encoding: "utf-8", flag: "w" },
);

clack.log.success(`Created ${chalk.cyan(defaultEntryPoint)}.`);

return;
clack.log.success(`Created ${chalk.cyan(entryPoint)}.`);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

const entryPointPath = path.join(process.cwd(), entryPointFromConfig);

if (existsSync(entryPointPath)) {
clack.log.info(
`Found existing entry point: ${chalk.cyan(entryPointFromConfig)}`,
try {
await wrapWorkerWithSentry(
entryPointPath,
dsn,
selectedFeatures,
reduceDataCollection,
);
clack.log.success(
`Wrapped ${chalk.cyan(entryPoint)} with Sentry initialization.`,
);
} catch (error) {
debug(error);
clack.log.warn("Failed to wrap worker automatically.");
clack.log.step("Please wrap your handler with Sentry initialization:");

try {
await wrapWorkerWithSentry(
entryPointPath,
dsn,
selectedFeatures,
reduceDataCollection,
);
clack.log.success(
`Wrapped ${chalk.cyan(
entryPointFromConfig,
)} with Sentry initialization.`,
);
} catch (error) {
debug(error);
clack.log.warn("Failed to wrap worker automatically.");
clack.log.step("Please wrap your handler with Sentry initialization:");

clack.note(
chalk.cyan(
getCloudflareWorkerTemplate(
dsn,
selectedFeatures,
reduceDataCollection,
),
clack.note(
chalk.cyan(
getCloudflareWorkerTemplate(
dsn,
selectedFeatures,
reduceDataCollection,
),
);
}
),
);
}
}
12 changes: 9 additions & 3 deletions packages/cli/src/lib/wizard/cloudflare/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,15 @@ export default Sentry.withSentry(
`;
}

export function getCloudflareWorkerTemplateWithHandler(): string {
/**
* A starter worker. With `typescript` unset, it leaves out the type
* annotations, for a `.js` or `.mjs` entry point.
*/
export function getCloudflareWorkerTemplateWithHandler(
typescript: boolean,
): string {
return `export default {
async fetch(request, env, ctx): Promise<Response> {
async fetch(request, env, ctx)${typescript ? ": Promise<Response>" : ""} {
const url = new URL(request.url);
switch (url.pathname) {
case '/message':
Expand All @@ -52,6 +58,6 @@ export function getCloudflareWorkerTemplateWithHandler(): string {
return new Response('Not Found', { status: 404 });
}
},
} satisfies ExportedHandler<Env>;
}${typescript ? " satisfies ExportedHandler<Env>" : ""};
`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { findWranglerConfig } from "./find-wrangler-config.js";
const b = recast.types.builders;

type WranglerConfigUpdates = {
main?: string;
compatibility_date?: string;
compatibility_flags?: string[];
version_metadata?: {
Expand All @@ -39,10 +40,19 @@ type WranglerConfigUpdateOptions = {
* e.g. flags superseded by one of the flags being added.
*/
removeCompatibilityFlags?: string[] | undefined;
/**
* Set `compatibility_date` only when the config doesn't have one yet: the
* date pins the Worker's runtime behaviour.
*/
keepCompatibilityDate?: boolean | undefined;
};

const getTomlConfigSnippet = (options: WranglerConfigUpdateOptions) => {
const getTomlConfigSnippet = (
updates: WranglerConfigUpdates,
options: WranglerConfigUpdateOptions,
) => {
const superseded = options.removeCompatibilityFlags ?? [];
const { main } = updates;

return makeCodeSnippet(true, (_unchanged, plus) =>
plus(
Expand All @@ -52,8 +62,10 @@ const getTomlConfigSnippet = (options: WranglerConfigUpdateOptions) => {
.map((flag) => `"${flag}"`)
.join(", ")} from compatibility_flags if present\n`
: ""
}compatibility_flags = ["nodejs_compat"]
compatibility_date = "${new Date().toISOString().slice(0, 10)}"
}${main ? `main = "${main}"\n` : ""}compatibility_flags = ["nodejs_compat"]
compatibility_date = "${new Date().toISOString().slice(0, 10)}"${
options.keepCompatibilityDate ? " # only if not set yet" : ""
}

[version_metadata]
binding = "CF_VERSION_METADATA"`,
Expand Down Expand Up @@ -98,7 +110,7 @@ export async function updateWranglerConfig(
case ".toml":
await showCopyPasteInstructions({
filename: configFile,
codeSnippet: getTomlConfigSnippet(options),
codeSnippet: getTomlConfigSnippet(updates, options),
});
break;
}
Expand Down Expand Up @@ -208,7 +220,13 @@ function updateJsoncObject(
options: WranglerConfigUpdateOptions = {},
): void {
for (const [key, value] of Object.entries(updates)) {
if (value === null || value === undefined) {
if (
value === null ||
value === undefined ||
(key === "compatibility_date" &&
options.keepCompatibilityDate &&
getObjectProperty(jsonObject, key))
) {
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/lib/wizard/sourcemaps/ci.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ async function configureCI(
return;
}

// Wrangler's `post<deploy>` script already runs `sentry:sourcemaps`
// The Wrangler deploy script already runs `sentry:sourcemaps` afterwards
if (isCliBasedFlowTool && selectedTool !== "wrangler") {
await traceStep("ci-npm-script-setup", setupNpmScriptInCI);
}
Expand Down
24 changes: 21 additions & 3 deletions packages/cli/src/lib/wizard/sourcemaps/tools/webpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

import type { namedTypes as t } from "ast-types";
import type { ExpressionKind } from "ast-types/lib/gen/kinds.js";
import chalk from "chalk";
import { promises } from "node:fs";
import path from "node:path";
Expand Down Expand Up @@ -255,10 +256,18 @@ function addSentryWebpackPlugin(
);

if (pluginsProp) {
if (pluginsProp.value.type === "ArrayExpression") {
pluginsProp.value.elements.push(sentryPluginCall);
} else {
const plugins = pluginsProp.value;
if (plugins.type === "ArrayExpression") {
plugins.elements.push(sentryPluginCall);
} else if (isNullish(plugins)) {
pluginsProp.value = b.arrayExpression([sentryPluginCall]);
} else {
// A variable or call such as `getPlugins()`: keep its plugins and add
// Sentry after them.
pluginsProp.value = b.arrayExpression([
b.spreadElement(plugins as ExpressionKind),
sentryPluginCall,
]);
}
return true;
}
Expand All @@ -273,6 +282,15 @@ function addSentryWebpackPlugin(
return true;
}

/** `undefined` or `null`, which leaves no plugins to keep. */
function isNullish(node: t.Property["value"]): boolean {
return (
(node.type === "Identifier" && node.name === "undefined") ||
node.type === "NullLiteral" ||
(node.type === "Literal" && node.value === null)
);
}

function addSentryWebpackPluginImport(program: t.Program, importPath: string) {
const b = recast.types.builders;

Expand Down
Loading
Loading