Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
131 changes: 122 additions & 9 deletions src/actions/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,121 @@ export async function syncStyles() {
}
}

function pageFileName(page) {
const base =
page.name ||
(page.path && page.path !== '/'
? page.path.replace(/^\//, '').replace(/\//g, '-')
: 'home');
return `${base.replace(/[^a-zA-Z0-9._-]/g, '_')}.json`;
function pagePathBase(page) {
return page.path && page.path !== '/'
? page.path.replace(/^\//, '').replace(/\//g, '-')
: 'home';
}

/**
* Compute a unique local file name for every page in a campaign.
*
* `page.name` is only unique for template pages — every custom
* (page-builder) page shares the name "legacy", so naming files by
* `page.name` alone makes all custom pages overwrite each other into a
* single legacy.json. Whenever a name is shared by more than one page,
* fall back to the page's path instead.
*
* @param {Array<object>} pages Pages belonging to one campaign
* @returns {string[]} File name for each page, in the same order
*/
export function pageFileNames(pages) {
const nameCounts = new Map();
for (const page of pages) {
if (page.name) {
nameCounts.set(page.name, (nameCounts.get(page.name) || 0) + 1);
}
}

const sanitize = (base) => `${base.replace(/[^a-zA-Z0-9._-]/g, '_')}.json`;

// Compare names case-insensitively: on macOS and Windows, magicLink.json
// and magiclink.json are the same file.
const used = new Set();
const isUsed = (fileName) => used.has(fileName.toLowerCase());
const markUsed = (fileName) => used.add(fileName.toLowerCase());

// First pass: pages with a unique name keep their name-based file.
// Reserving these up front keeps template filenames stable regardless
// of API order (a custom page at e.g. /profile must never take
// profile.json from the profile template page).
const fileNames = pages.map((page) => {
if (page.name && nameCounts.get(page.name) === 1) {
const fileName = sanitize(page.name);
if (!isUsed(fileName)) {
markUsed(fileName);
return fileName;
}
}
return null;
});

// Second pass: pages with a shared or missing name fall back to their
// path, with a short uuid suffix on any residual collision.
return fileNames.map((fileName, index) => {
if (fileName) {
return fileName;
}
const page = pages[index];
let candidate = sanitize(pagePathBase(page));
if (isUsed(candidate) && page.uuid) {
candidate = candidate.replace(
/\.json$/,
`-${page.uuid.slice(0, 8)}.json`
);
}
markUsed(candidate);
return candidate;
});
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

/**
* Delete page files left behind under an old name.
*
* A file is removed only when its uuid was part of this sync and the page
* was written under a different file name. Files for pages that weren't
* synced, and files that aren't valid JSON, are kept.
*
* @param {string} pagesDir Directory holding the campaign's page files
* @param {Map<string, string>} fileNameByUuid File name written for each synced page uuid
* @returns {string[]} File names that were removed
*/
export function removeStalePageFiles(pagesDir, fileNameByUuid) {
const removed = [];
for (const entry of fs.readdirSync(pagesDir, { withFileTypes: true })) {
if (!entry.isFile() || !entry.name.endsWith('.json')) continue;

const filePath = path.join(pagesDir, entry.name);
let uuid;
try {
uuid = JSON.parse(fs.readFileSync(filePath, 'utf8'))?.uuid;
} catch {
continue;
}

const current = fileNameByUuid.get(uuid);
if (
current &&
current !== entry.name &&
!isSameFile(filePath, path.join(pagesDir, current))
) {
fs.unlinkSync(filePath);
removed.push(entry.name);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
}
return removed;
}

// On case-insensitive filesystems, writing profile.json can land in an
// existing Profile.json, so the names differ but the file is the same.
function isSameFile(a, b) {
try {
const statA = fs.statSync(a);
const statB = fs.statSync(b);
return statA.dev === statB.dev && statA.ino === statB.ino;
} catch {
return false;
}
}

export async function syncPages() {
Expand All @@ -87,7 +195,9 @@ export async function syncPages() {
path: `/campaigns/${uuid}/pages?private=1&includeBody=1&limit=999`,
});

for (const page of pages.data) {
const fileNames = pageFileNames(pages.data);
const fileNameByUuid = new Map();
for (const [index, page] of pages.data.entries()) {
const out = {
uuid: page.uuid,
path: page.path,
Expand All @@ -107,10 +217,13 @@ export async function syncPages() {
};

fs.writeFileSync(
path.join(pagesDir, pageFileName(page)),
path.join(pagesDir, fileNames[index]),
Comment thread
KeinerM marked this conversation as resolved.
Resolved
JSON.stringify(out, null, 4)
);
fileNameByUuid.set(page.uuid, fileNames[index]);
}

removeStalePageFiles(pagesDir, fileNameByUuid);
}
loader.succeed();
} catch (e) {
Expand Down
Loading
Loading