// deno-lint-ignore-file no-console /** * TEMPORARY: rebrand this repo from Fresh (`@fresh/*`) to Sweet * (`@paulaboks/*`). * * deno run -A tools/rebrand.ts --dry-run # show what would change * deno run -A tools/rebrand.ts # apply * * Safe to re-run: every step skips what is already done. * * What it does: * 1. Hand edits: branding text, the update check, init templates, a * `sweet` alias for the Vite plugin, and the init test's local links. * Each edit must match exactly once, or the script stops and changes * nothing. * 2. Scope rename in all tracked files: `@fresh/` -> `@paulaboks/...`. * 3. Bare import name: `"fresh"` -> `"sweet"`, only where it is a module * specifier (`from`/`import`/`import()`) or an import-map key. Other * `"fresh"` strings stay as they are: lint rule tags, the * `packages/fresh` folder, the search index name, the OTel tracer and * the Vite plugin's internal name. * * Kept as is: internal identifiers (`frsh:` markers, `_fresh/` build * output, `FRESH_*` env vars, `X-Fresh-Id`, `f-*` attributes, `fresh:*` * Vite modules), the `fresh()` Vite plugin export (now also exported as * `sweet`), prose in docs, and `tools/release.ts`. * * `packages/update` is left out entirely: it migrates Fresh 1 projects to * Fresh 2, its tests expect `"fresh"` output, and it won't be published. * References to `jsr:@fresh/update` keep pointing at the upstream tool. */ import * as path from "@std/path"; const DRY_RUN = Deno.args.includes("--dry-run"); const ROOT = path.join(import.meta.dirname!, ".."); const SCOPE = "@paulaboks"; const NAME = "sweet"; /** Old package name -> new package name. */ const PACKAGES: Record = { "@fresh/core": `${SCOPE}/${NAME}`, "@fresh/build-id": `${SCOPE}/${NAME}-build-id`, "@fresh/plugin-vite": `${SCOPE}/${NAME}-vite`, "@fresh/plugin-tailwind": `${SCOPE}/${NAME}-tailwind`, "@fresh/plugin-tailwind-v3": `${SCOPE}/${NAME}-tailwind-v3`, "@fresh/init": `${SCOPE}/${NAME}-init`, "@fresh/examples": `${SCOPE}/${NAME}-examples`, }; const TEXT_EXTENSIONS = /\.(ts|tsx|js|jsx|mjs|cjs|json|jsonc|md|mdx|yml|yaml|toml|txt)$/; const SKIP_PATHS = /^(vendor\/|packages\/update\/|tools\/rebrand\.ts$)|node_modules\/|(^|\/)deno\.lock$/; // --------------------------------------------------------------------------- // 1. Hand edits (applied to the original text, before the generic renames) // --------------------------------------------------------------------------- type Edit = | { file: string; from: string; to: string } | { file: string; append: string }; const EDITS: Edit[] = [ // Branding { file: "packages/fresh/src/app.ts", from: `" 🍋 Fresh ready "`, to: `" 🍬 Sweet ready "`, }, { file: "packages/fresh/src/runtime/client/dev_hmr.ts", from: "`%c Fresh %c Connection closed. Trying to reconnect...`", to: "`%c Sweet %c Connection closed. Trying to reconnect...`", }, { file: "packages/fresh/src/runtime/client/dev_hmr.ts", from: "`%c Fresh %c Connected to development server.`", to: "`%c Sweet %c Connected to development server.`", }, { file: "packages/fresh/src/runtime/client/reviver.ts", from: "`Fresh hydration error: ", to: "`Sweet hydration error: ", }, // Update check: own cache dir, JSR as the version source, no @fresh/update { file: "packages/fresh/src/dev/update_check.ts", from: `path.join(home, "fresh")`, to: `path.join(home, "${NAME}")`, }, { file: "packages/fresh/src/dev/update_check.ts", from: ` const res = await fetch("https://dl.deno.land/fresh/release-latest.txt"); if (res.ok) { return (await res.text()).trim().replace(/^v/, ""); }`, to: ` const res = await fetch("https://jsr.io/${SCOPE}/${NAME}/meta.json"); if (res.ok) { const meta = (await res.json()) as { latest: string | null }; if (meta.latest) return meta.latest; }`, }, { file: "packages/fresh/src/dev/update_check.ts", from: "` Fresh ${latest} is available. You're on ${current}`", to: "` Sweet ${latest} is available. You're on ${current}`", }, { file: "packages/fresh/src/dev/update_check.ts", from: "` To upgrade, run: deno run -A -r jsr:@fresh/update`", to: '` To upgrade, bump the "sweet" version in your deno.json`', }, // Init: banner, help, templates, no update task, sweet() in vite config { file: "packages/init/src/init.ts", from: "Initialize a new Fresh project.", to: "Initialize a new Sweet project.", }, { file: "packages/init/src/init.ts", from: `" 🍋 Fresh: The next-gen web framework. "`, to: `" 🍬 Sweet: The next-gen web framework. "`, }, { file: "packages/init/src/init.ts", from: "# Fresh build directory", to: "# Sweet build directory", }, { file: "packages/init/src/init.ts", from: "Fresh counter", to: "Sweet counter", }, { file: "packages/init/src/init.ts", from: `alt="the Fresh logo: a sliced lemon dripping with juice"`, to: `alt="the Sweet logo"`, }, { file: "packages/init/src/init.ts", from: "Welcome to Fresh", to: "Welcome to Sweet", }, { file: "packages/init/src/init.ts", from: `const README_MD = \`# Fresh project Your new Fresh project is ready to go. You can follow the Fresh "Getting Started" guide here: https://usefresh.dev/docs/getting-started `, to: `const README_MD = \`# Sweet project Your new Sweet project is ready to go. `, }, { file: "packages/init/src/init.ts", from: ` update: "deno run -A -r jsr:@fresh/update .",\n`, to: "", }, { file: "packages/init/src/init.ts", from: `import { fresh } from "@fresh/plugin-vite";\\n\`;`, to: `import { ${NAME} } from "@fresh/plugin-vite";\\n\`;`, }, { file: "packages/init/src/init.ts", from: "plugins: [fresh()${", to: `plugins: [${NAME}()\${`, }, // Reads the bare import-map key as a property { file: "packages/fresh/tests/fresh_versions_test.ts", from: "rootConfig.imports.fresh;", to: `rootConfig.imports.${NAME};`, }, // Vite plugin: export `sweet` next to `fresh` { file: "packages/plugin-vite/src/mod.ts", append: ` /** Alias of {@linkcode fresh}: the Vite plugin for Sweet. */ export { fresh as ${NAME} }; `, }, // Init tests: the renamed Tailwind plugin isn't on JSR until you publish // it, so link the local copy (like core and build-id already are). { file: "packages/init/src/init_test.ts", from: ` await copyRecursive( path.join(import.meta.dirname!, "..", "..", "build-id"), path.join(linkedDir, "build-id"), ignore, ); `, to: ` await copyRecursive( path.join(import.meta.dirname!, "..", "..", "build-id"), path.join(linkedDir, "build-id"), ignore, ); if (json.imports?.["@fresh/plugin-tailwind"]) { await copyRecursive( path.join(import.meta.dirname!, "..", "..", "plugin-tailwindcss"), path.join(linkedDir, "plugin-tailwindcss"), ignore, ); } `, }, ]; // --------------------------------------------------------------------------- // 2 + 3. Generic renames // --------------------------------------------------------------------------- function escapeRegExp(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } const SCOPE_RULES = Object.entries(PACKAGES).flatMap(([from, to]) => [ // Not followed by a name character, so `@fresh/plugin-tailwind` doesn't // eat `@fresh/plugin-tailwind-v3`. Subpaths (`@fresh/core/x`) still match. { re: new RegExp(`${escapeRegExp(from)}(?![\\w-])`, "g"), to }, // Same name inside a regex literal, e.g. /^(jsr:)?@fresh\/build-id/ in the // build-id resolvers. Missing these gives client and server different // build IDs, and islands never boot. { re: new RegExp(`${escapeRegExp(from.replace("/", "\\/"))}(?![\\w-])`, "g"), to: to.replace("/", "\\/"), }, ]); /** `from "fresh"`, `import "fresh/x"`, `import("fresh")`, `export ... from`. */ const BARE_IMPORT = /(\b(?:from|import)\s*\(?\s*)(["'])fresh((?:\/[\w-]+)*)\2/g; /** Import-map key at the start of a line: `"fresh": ...`, `"fresh/": ...`. */ const BARE_MAP_KEY = /^(\s*)"fresh((?:\/[\w-]*)*)"(\s*:)/gm; function renameGeneric(text: string): { text: string; count: number } { let count = 0; const count1 = (fn: (...a: string[]) => string) => (...a: string[]) => { count++; return fn(...a); }; for (const { re, to } of SCOPE_RULES) { text = text.replace(re, count1(() => to)); } text = text.replace( BARE_IMPORT, count1((_m, pre, q, sub) => `${pre}${q}${NAME}${sub}${q}`), ); text = text.replace( BARE_MAP_KEY, count1((_m, indent, sub, colon) => `${indent}"${NAME}${sub}"${colon}`), ); return { text, count }; } // --------------------------------------------------------------------------- // Run // --------------------------------------------------------------------------- async function trackedFiles(): Promise { const out = await new Deno.Command("git", { args: ["ls-files", "-z"], cwd: ROOT, stdout: "piped", }).output(); if (!out.success) throw new Error("git ls-files failed"); return new TextDecoder().decode(out.stdout).split("\0").filter((f) => f && TEXT_EXTENSIONS.test(f) && !SKIP_PATHS.test(f) ); } const files = new Map(); async function load(file: string) { let entry = files.get(file); if (!entry) { const text = await Deno.readTextFile(path.join(ROOT, file)); entry = { original: text, text }; files.set(file, entry); } return entry; } function countOf(haystack: string, needle: string): number { return needle === "" ? 0 : haystack.split(needle).length - 1; } // 1. Hand edits. Check them all before writing anything. const problems: string[] = []; let editsApplied = 0; let editsSkipped = 0; for (const edit of EDITS) { const entry = await load(edit.file); if ("append" in edit) { if (entry.text.includes(edit.append.trim())) { editsSkipped++; } else { entry.text = entry.text.trimEnd() + "\n" + edit.append; editsApplied++; } continue; } const n = countOf(entry.text, edit.from); if (n === 1) { entry.text = entry.text.replace(edit.from, () => edit.to); editsApplied++; } else if (n === 0) { // Already applied? The replacement may since have been renamed by the // generic step, so check against that form too. const renamed = renameGeneric(edit.to).text; if ( edit.to === "" || entry.text.includes(edit.to) || entry.text.includes(renamed) ) { editsSkipped++; } else { problems.push( `${edit.file}: text not found:\n ${edit.from.split("\n")[0]}`, ); } } else { problems.push( `${edit.file}: text found ${n} times, expected 1:\n ${ edit.from.split("\n")[0] }`, ); } } if (problems.length > 0) { console.error( "Stopped: these hand edits don't match the code any more (no files were changed):\n", ); for (const p of problems) console.error(" - " + p); console.error( "\nUpdate the matching entry in EDITS in tools/rebrand.ts and run again.", ); Deno.exit(1); } // 2 + 3. Generic renames across all tracked text files. const perFile: { file: string; count: number }[] = []; for (const file of await trackedFiles()) { const entry = await load(file); const { text, count } = renameGeneric(entry.text); entry.text = text; if (count > 0) perFile.push({ file, count }); } // Write. const changed = [...files].filter(([, e]) => e.text !== e.original); if (!DRY_RUN) { for (const [file, e] of changed) { await Deno.writeTextFile(path.join(ROOT, file), e.text); } // Longer names change line wrapping (Markdown) and line lengths (code). if (changed.length > 0) { const fmt = await new Deno.Command(Deno.execPath(), { args: ["fmt", "--quiet", ...changed.map(([file]) => file)], cwd: ROOT, }).output(); if (!fmt.success) { console.error(new TextDecoder().decode(fmt.stderr)); console.error("deno fmt failed on the changed files (see above)."); } } } // Report. console.log(DRY_RUN ? "DRY RUN: nothing written.\n" : ""); console.log( `Hand edits: ${editsApplied} applied, ${editsSkipped} already done.`, ); console.log( `Renames: ${ perFile.reduce((a, b) => a + b.count, 0) } in ${perFile.length} files.`, ); console.log( `Files ${DRY_RUN ? "that would change" : "changed"}: ${changed.length}\n`, ); // Leftovers worth a look. const leftovers: string[] = []; for (const [file, e] of files) { if (!/\.(ts|tsx|json|jsonc)$/.test(file)) continue; e.text.split("\n").forEach((line, i) => { if (/@fresh\\?\//.test(line) || /(["'`])fresh(\/[\w-]+)*\1/.test(line)) { leftovers.push(` ${file}:${i + 1}: ${line.trim().slice(0, 100)}`); } }); } if (leftovers.length > 0) { console.log( `Still mentions @fresh/ or a quoted "fresh" (code files only). Most of these are on purpose (lint tags, folder paths, internal names); check the rest:`, ); console.log(leftovers.join("\n")); console.log(); } if (!DRY_RUN && changed.length > 0) { console.log(`Next: deno install # refresh workspace links; deno.lock will change deno task ok # fmt, lint, type check, tests git diff --stat # review; \`git checkout .\` undoes everything`); }