AbiirSkincare/Hydrogen/web/scripts/sanity-seed-all.mjs

582 lines
18 KiB
JavaScript

/**
* Push bundled storefront copy (Hydrogen mocks) into Sanity singletons + static pages.
*
* From Hydrogen/web:
* node --experimental-strip-types ./scripts/build-cms-seed-json.mjs
* node --env-file=.env ./scripts/sanity-seed-all.mjs
*
* Optional — also run PDP seed after CMS:
* node --env-file=.env ./scripts/sanity-seed-all.mjs -- --with-pdp scripts/pdp-seed.example.json
*
* Requires SANITY_API_WRITE_TOKEN. Re-run `build-cms-seed-json` when mocks change.
*/
import {readFileSync, existsSync} from 'node:fs';
import {dirname, join} from 'node:path';
import {fileURLToPath} from 'node:url';
import {spawnSync} from 'node:child_process';
import {createClient} from '@sanity/client';
const __dirname = dirname(fileURLToPath(import.meta.url));
const WEB_ROOT = join(__dirname, '..');
const MIN_PNG = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64',
);
function req(name) {
const v = process.env[name];
if (!v || !String(v).trim()) {
console.error(`Missing required env: ${name}`);
process.exit(1);
}
return String(v).trim();
}
const projectId = req('SANITY_PROJECT_ID');
const dataset = req('SANITY_DATASET');
const token = req('SANITY_API_WRITE_TOKEN');
const apiVersion = process.env.SANITY_API_VERSION?.trim() || '2026-04-16';
const client = createClient({
projectId,
dataset,
apiVersion,
token,
useCdn: false,
});
function readSeed() {
const p = join(__dirname, 'seed-data', 'cms-seed.json');
if (!existsSync(p)) {
console.error(`Missing ${p}`);
console.error('Run: node --experimental-strip-types ./scripts/build-cms-seed-json.mjs');
process.exit(1);
}
return JSON.parse(readFileSync(p, 'utf8'));
}
async function uploadImageRel(rel, label) {
const abs = join(WEB_ROOT, rel);
const buf = existsSync(abs) ? readFileSync(abs) : MIN_PNG;
if (!existsSync(abs)) {
console.warn(` (placeholder image — missing file: ${rel})`);
}
const filename = rel.split('/').pop() || label || 'image.png';
return client.assets.upload('image', buf, {filename, label});
}
function imgField(assetDoc, alt) {
return {
_type: 'image',
alt: alt ?? '',
asset: {_type: 'reference', _ref: assetDoc._id},
};
}
function seo(title, description) {
return {title, description};
}
function mapLegalPage(src) {
return {
title: src.title,
heroEyebrow: src.heroEyebrow,
lastUpdatedLine: src.lastUpdatedLine,
lead: src.lead,
sections: (src.sections || []).map((s) => {
const o = {_type: 'legalSection', title: s.title};
if (s.paragraphs?.length) o.paragraphs = s.paragraphs;
if (s.listItems?.length) o.listItems = s.listItems;
if (s.trailingParagraphs?.length) o.trailingParagraphs = s.trailingParagraphs;
return o;
}),
seo: seo(src.seoTitle, src.seoDescription),
};
}
function mapInfoPage(src) {
return {
title: src.title,
intro: src.intro ?? '',
paragraphs: src.paragraphs ?? [],
seo: seo(src.seoTitle, src.seoDescription),
};
}
function mapFaq(src) {
return {
title: src.title,
subtitle: src.subtitle ?? '',
sections: (src.sections || []).map((sec) => ({
_type: 'faqSection',
sectionTitle: sec.sectionTitle,
items: (sec.items || []).map((it) => ({
_type: 'faqQa',
question: it.question,
answer: it.answer,
})),
})),
seo: seo(src.seoTitle, src.seoDescription),
};
}
function mapShipping(src) {
return {
title: src.title,
intro: src.intro ?? '',
shippingOptions: (src.shippingOptions || []).map((o) => ({
_type: 'shippingOptionRow',
title: o.title,
leadTime: o.leadTime,
priceLine: o.priceLine,
detail: o.detail,
})),
returnsPolicy: (src.returnsPolicy || []).map((o) => ({
_type: 'returnPolicyRow',
title: o.title,
body: o.body,
})),
bannerHeadline: src.bannerHeadline,
supportEmail: src.supportEmail,
bannerTextBeforeEmail: src.bannerTextBeforeEmail,
bannerTextAfterEmail: src.bannerTextAfterEmail,
seo: seo(src.seoTitle, src.seoDescription),
};
}
function mapContact(src) {
const out = {
title: src.title,
heroEyebrow: src.heroEyebrow,
intro: src.intro,
howToReachHeading: src.howToReachHeading,
followUsLabel: src.followUsLabel,
reachRows: (src.reachRows || []).map((r) => ({
_type: 'contactReachRow',
label: r.label,
primary: r.primary,
note: r.note,
icon: r.icon,
})),
socialLinks: (src.socialLinks || []).map((r) => ({
_type: 'contactSocial',
label: r.label,
href: r.href,
network: r.network,
})),
formPlaceholders: src.formPlaceholders,
formSubmitLabel: src.formSubmitLabel,
email: src.email,
showContactForm: src.showContactForm,
formHeadline: src.formHeadline ?? '',
formSuccessText: src.formSuccessText,
seo: seo(src.seoTitle, src.seoDescription),
};
if (src.phone?.trim()) out.phone = src.phone.trim();
if (src.address?.trim()) out.address = src.address.trim();
if (src.businessHours?.trim()) out.businessHours = src.businessHours.trim();
if (src.mapEmbedUrl?.trim()) out.mapEmbedUrl = src.mapEmbedUrl.trim();
return out;
}
function mapPress(src, tileImage) {
return {
title: src.title,
intro: src.intro,
items: (src.items || []).map((it) => ({
_type: 'pressItem',
title: it.title,
listCaption: it.listCaption ?? '',
modalDescription: it.modalDescription ?? '',
image: tileImage,
})),
seo: seo(src.seoTitle, src.seoDescription),
};
}
async function ensureDoc(id, type) {
await client.createIfNotExists({_id: id, _type: type});
}
async function main() {
const seed = readSeed();
const ap = seed.settings?.assetPaths ?? {};
console.log('Uploading images…');
const headerLogo = await uploadImageRel(ap.headerLogo, 'header-logo');
const heroImg = await uploadImageRel(ap.hero, 'home-hero');
let springAsset = null;
for (const rel of [ap.springBundle, ap.springBundleFallback].filter(Boolean)) {
if (existsSync(join(WEB_ROOT, rel))) {
springAsset = await uploadImageRel(rel, 'spring-bundle');
break;
}
}
if (!springAsset) springAsset = await uploadImageRel(ap.springBundleFallback, 'spring-bundle');
const lifestyleAssets = [];
for (const rel of ap.lifestyleTiles || []) {
lifestyleAssets.push(await uploadImageRel(rel, 'lifestyle'));
}
const emblem = await uploadImageRel(ap.footerEmblem, 'footer-emblem');
const wordmark = await uploadImageRel(ap.footerWordmark, 'footer-wordmark');
const badges = await uploadImageRel(ap.footerCertificationBadges, 'footer-badges');
let ingredientsHeroAsset = null;
if (ap.ingredientsHero && existsSync(join(WEB_ROOT, ap.ingredientsHero))) {
ingredientsHeroAsset = await uploadImageRel(ap.ingredientsHero, 'ingredients');
}
const pressTile = await uploadImageRel(ap.pressTile, 'press-tile');
const aboutPaths = seed.aboutPage?.imagePaths ?? {};
const aboutHeroImg = await uploadImageRel(aboutPaths.heroImage, 'about-hero');
const aboutBeginningImg = await uploadImageRel(aboutPaths.beginningImage, 'about-beginning');
const aboutPhilosophyImg = await uploadImageRel(aboutPaths.philosophyImage, 'about-philosophy');
const aboutFounderImg = await uploadImageRel(aboutPaths.founderImage, 'about-founder');
const heroImage = imgField(heroImg, 'ABiiR — home hero');
const springImage = imgField(springAsset, 'Spring Glow bundle');
const pressImageField = imgField(pressTile, 'Press');
const h = seed.home.hero;
const hero = {
_type: 'abiirHomeHero',
eyebrow: h.eyebrow,
headlineLine1Prefix: h.headlineLine1Prefix,
headlineLine1Italic: h.headlineLine1Italic,
headlineLine2Prefix: h.headlineLine2Prefix,
headlineLine2Accent: h.headlineLine2Accent,
body: h.body,
primaryCtaLabel: h.primaryCtaLabel,
primaryCtaHref: h.primaryCtaHref,
secondaryCtaLabel: h.secondaryCtaLabel,
secondaryCtaHref: h.secondaryCtaHref,
gradientStart: h.gradientStart,
gradientEnd: h.gradientEnd,
accentBurgundy: h.accentBurgundy,
marqueeText: h.marqueeText,
image: heroImage,
};
const s = seed.home.springGlowBanner;
const springGlowBanner = {
_type: 'abiirSpringGlowBanner',
eyebrow: s.eyebrow,
titleLine1Before: s.titleLine1Before,
titleLine1Italic: s.titleLine1Italic,
titleLine2: s.titleLine2,
body: s.body,
whatsIncludedLabel: s.whatsIncludedLabel,
includedItems: s.includedItems,
ratingScoreText: s.ratingScoreText,
ratingReviewsText: s.ratingReviewsText,
priceMain: s.priceMain,
compareAtLine: s.compareAtLine,
saveLine: s.saveLine,
badgeLabel: s.badgeLabel,
badgeAmount: s.badgeAmount,
primaryCtaLabel: s.primaryCtaLabel,
secondaryCtaLabel: s.secondaryCtaLabel,
secondaryCtaHref: s.secondaryCtaHref,
bundleProductHandle: s.bundleProductHandle,
sectionBackground: s.sectionBackground,
gold: s.gold,
creamText: s.creamText,
saveGreen: s.saveGreen,
badgeBackground: s.badgeBackground,
image: springImage,
};
const bv = seed.home.brandValues;
const brandValues = {
_type: 'abiirBrandValues',
...bv,
values: (bv.values || []).map((v) => ({
iconKey: v.iconKey,
title: v.title,
description: v.description,
})),
};
const fp = seed.home.featuredProducts;
const featuredProducts = {
_type: 'abiirFeaturedProducts',
...fp,
filterPills: (fp.filterPills || []).map((p) => ({
_type: 'filterPill',
label: p.label,
href: p.href,
})),
items: (fp.items || []).map((row) => {
const o = {_type: 'featuredProductSlot', productHandle: row.productHandle};
if (row.hideBadge != null) o.hideBadge = row.hideBadge;
if (row.cardTitle) o.cardTitle = row.cardTitle;
if (row.subtitle) o.subtitle = row.subtitle;
if (row.benefitChips?.length) o.benefitChips = row.benefitChips;
if (row.rating != null) o.rating = row.rating;
if (row.reviewCount != null) o.reviewCount = row.reviewCount;
return o;
}),
};
const ing = seed.home.ingredientsSection;
const ingredientsSection = {
_type: 'abiirIngredientsSection',
eyebrow: ing.eyebrow,
headlineLine1Before: ing.headlineLine1Before,
headlineLine1Accent: ing.headlineLine1Accent,
headlineLine2: ing.headlineLine2,
body: ing.body,
badgePercent: ing.badgePercent,
badgeCaption: ing.badgeCaption,
primaryCtaLabel: ing.primaryCtaLabel,
primaryCtaHref: ing.primaryCtaHref,
sectionBackground: ing.sectionBackground,
gold: ing.gold,
cream: ing.cream,
creamMuted: ing.creamMuted,
badgeBackground: ing.badgeBackground,
charcoal: ing.charcoal,
ingredients: (ing.ingredients || []).map((r) => ({
iconKey: r.iconKey,
name: r.name,
description: r.description,
})),
};
if (ingredientsHeroAsset) {
ingredientsSection.image = imgField(ingredientsHeroAsset, 'Ingredients');
}
const sr = seed.home.skinRitualSection;
const skinRitualSection = {
_type: 'abiirSkinRitualSection',
eyebrow: sr.eyebrow,
headlinePrefix: sr.headlinePrefix,
headlineItalic: sr.headlineItalic,
intro: sr.intro,
footerText: sr.footerText,
primaryCtaLabel: sr.primaryCtaLabel,
primaryCtaHref: sr.primaryCtaHref,
sectionBackground: sr.sectionBackground,
burgundy: sr.burgundy,
gold: sr.gold,
charcoal: sr.charcoal,
muted: sr.muted,
gridLine: sr.gridLine,
numMuted: sr.numMuted,
steps: (sr.steps || []).map((st) => ({
_type: 'skinRitualStep',
num: st.num,
kicker: st.kicker,
title: st.title,
body: st.body,
duration: st.duration,
})),
};
const te = seed.home.testimonialsSection;
const testimonialsSection = {
_type: 'abiirTestimonialsSection',
title: te.title,
sectionBackground: te.sectionBackground,
cardBackground: te.cardBackground,
gold: te.gold,
charcoal: te.charcoal,
muted: te.muted,
verifiedGreen: te.verifiedGreen,
gridLine: te.gridLine,
dotInactive: te.dotInactive,
stats: (te.stats || []).map((st) => ({
_type: 'testimonialStat',
value: st.value,
label: st.label,
sub: st.sub,
})),
testimonials: (te.testimonials || []).map((t) => ({
_type: 'testimonial',
name: t.name,
location: (t.location && String(t.location).trim()) || ' ',
avatarInitials: t.avatarInitials,
rating: t.rating,
product: t.product,
text: t.text,
verified: Boolean(t.verified),
})),
};
const lg = seed.home.lifestyleGridSection;
const lifestyleGridSection = {
_type: 'abiirLifestyleGridSection',
eyebrow: lg.eyebrow,
headline: lg.headline,
instagramUrl: lg.instagramUrl,
followLabel: lg.followLabel,
sectionBackground: lg.sectionBackground,
footerPrefix: lg.footerPrefix,
hashtag: lg.hashtag,
footerSuffix: lg.footerSuffix,
hashtagColor: lg.hashtagColor,
tiles: (lg.tiles || []).map((t, i) => ({
_type: 'lifestyleTile',
caption: t.caption,
tall: Boolean(t.tall),
image: imgField(
lifestyleAssets[i] ?? lifestyleAssets[lifestyleAssets.length - 1],
t.caption || 'Community',
),
})),
};
const nw = seed.home.newsletterSection;
const newsletterSection = {
_type: 'abiirNewsletterSection',
...nw,
perks: nw.perks || [],
};
console.log('Ensuring documents…');
await ensureDoc('home', 'home');
await ensureDoc('settings', 'settings');
await ensureDoc('aboutPage', 'aboutPage');
await ensureDoc('abiirFaqPage', 'abiirFaqPage');
await ensureDoc('abiirShippingPage', 'abiirShippingPage');
await ensureDoc('abiirTrackOrderPage', 'abiirTrackOrderPage');
await ensureDoc('abiirSkincareQuizPage', 'abiirSkincareQuizPage');
await ensureDoc('abiirContactPage', 'abiirContactPage');
await ensureDoc('abiirPressPage', 'abiirPressPage');
await ensureDoc('abiirPrivacyPolicyPage', 'abiirPrivacyPolicyPage');
await ensureDoc('abiirTermsOfServicePage', 'abiirTermsOfServicePage');
const commitOpts = {autoGenerateArrayKeys: true};
console.log('Patching home…');
await client
.patch('home')
.set({
hero,
springGlowBanner,
brandValues,
featuredProducts,
ingredientsSection,
skinRitualSection,
testimonialsSection,
lifestyleGridSection,
newsletterSection,
})
.commit(commitOpts);
const hdr = seed.settings.header;
const headerPatch = {
_type: 'headerSettings',
...hdr,
logo: imgField(headerLogo, 'ABiiR Skincare'),
navigationItems: (hdr.navigationItems || []).map((n) => ({
_type: 'navItem',
label: n.label,
href: n.href,
})),
accountMenuItems: (hdr.accountMenuItems || []).map((n) => ({
_type: 'accountLink',
label: n.label,
href: n.href,
})),
};
const ft = seed.settings.footer;
const abiirFooter = {
_type: 'abiirFooter',
tagline: ft.tagline,
brandLinkPath: ft.brandLinkPath,
emblem: imgField(emblem, ''),
wordmark: imgField(wordmark, ''),
certificationBadges: imgField(
badges,
'Paraben Free · Recyclable · Cruelty Free · For All Skin Types',
),
socialInstagramUrl: ft.socialInstagramUrl,
socialYoutubeUrl: ft.socialYoutubeUrl,
socialXUrl: ft.socialXUrl,
columnGroups: (ft.columnGroups || []).map((g) => ({
_type: 'footerColumnGroup',
title: g.title,
links: (g.links || []).map((l) => ({
_type: 'footerLinkRow',
label: l.label,
path: l.path,
})),
})),
copyrightLine: ft.copyrightLine,
legalLinks: (ft.legalLinks || []).map((l) => ({
_type: 'footerLinkRow',
label: l.label,
path: l.path,
})),
};
console.log('Patching settings…');
await client
.patch('settings')
.set({header: headerPatch, abiirFooter})
.commit(commitOpts);
const at = seed.aboutPage.text;
const {seoTitle, seoDescription, values, ...aboutRest} = at;
console.log('Patching aboutPage…');
await client
.patch('aboutPage')
.set({
...aboutRest,
values: (values || []).map((v) => ({
_type: 'aboutValue',
title: v.title,
description: v.description,
})),
seo: seo(seoTitle, seoDescription),
heroImage: imgField(aboutHeroImg, 'ABiiR Our Story — banner'),
beginningImage: imgField(aboutBeginningImg, 'ABiiR Our Story — hero'),
philosophyImage: imgField(aboutPhilosophyImg, ''),
founderImage: imgField(aboutFounderImg, 'Bhairavi Desai'),
})
.commit(commitOpts);
console.log('Patching static + legal pages…');
await client.patch('abiirFaqPage').set(mapFaq(seed.static.faq)).commit(commitOpts);
await client.patch('abiirShippingPage').set(mapShipping(seed.static.shipping)).commit(commitOpts);
await client.patch('abiirTrackOrderPage').set(mapInfoPage(seed.static.track)).commit(commitOpts);
await client.patch('abiirSkincareQuizPage').set(mapInfoPage(seed.static.quiz)).commit(commitOpts);
await client.patch('abiirContactPage').set(mapContact(seed.static.contact)).commit(commitOpts);
await client.patch('abiirPressPage').set(mapPress(seed.static.press, pressImageField)).commit(commitOpts);
await client
.patch('abiirPrivacyPolicyPage')
.set(mapLegalPage(seed.legal.privacy))
.commit(commitOpts);
await client
.patch('abiirTermsOfServicePage')
.set(mapLegalPage(seed.legal.terms))
.commit(commitOpts);
console.log('Done. Journal posts / PDP are separate (see README-sanity-rollout.txt).');
const argv = process.argv.slice(2).filter((a) => a !== '--');
const withIdx = argv.indexOf('--with-pdp');
if (withIdx !== -1) {
const jsonPath = argv[withIdx + 1];
if (!jsonPath) {
console.error('Usage: ... --with-pdp scripts/pdp-seed.json');
process.exit(1);
}
const r = spawnSync(
process.execPath,
['--env-file=.env', join(__dirname, 'sanity-seed-pdp.mjs'), jsonPath],
{cwd: WEB_ROOT, stdio: 'inherit'},
);
if (r.status !== 0) process.exit(r.status ?? 1);
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});