← back to 1980swallpaper

server.js

207 lines

/**
 * 1980s WALLPAPER — DW family vertical
 * Curated slice from live designerwallcoverings.com Shopify catalog.
 * Static-JSON server (data/products.json). Vendor identity is scrubbed at the
 * API boundary by the fleet-standard _shared/api-vendor-redact middleware — the
 * same layer the 60+ sister microsites use — so no vendor name reaches the client.
 */
const express = require('express');
const helmet = require('helmet');
const path = require('path');
const fs = require('fs');
const vendorRedact = require('../_shared/api-vendor-redact');
const { redactVendorText } = require('../_shared/vendor-text-redact');

const PORT = process.env.PORT || 9840;
const DW_SHOPIFY = 'https://designerwallcoverings.com';
const DATA_RAW = JSON.parse(fs.readFileSync(path.join(__dirname, 'data', 'products.json'), 'utf8'));

function isJunk(p) {
  if (!p.image_url || !p.image_url.trim()) return true;
  if (!p.handle && !p.sku) return true;
  const t = p.title || '';
  if (/lamp|rug|pillow|throw|tripod|frame|mirror|vase|candle|sculpture|figurine/i.test(t)) return true;
  if (/visual.{0,3}merchandiser/i.test(t)) return true;
  if (/(?:^|\W)image[ _-]?4(?:\W|$)/i.test(t)) return true;
  if (/bh.?90210|beverly.?hills.?90210|iconic.{0,4}bh/i.test(t)) return true;
  return false;
}

const PRODUCTS = DATA_RAW.filter(p => !isJunk(p));
const DROPPED = DATA_RAW.length - PRODUCTS.length;
console.log(`Loaded ${DATA_RAW.length}, kept ${PRODUCTS.length}, dropped ${DROPPED}`);

// DW STANDARD: every product grid is sortable by color/style/sku/title/price/
// light-dark. The frontend #sortSelect drives these server-side (no client-side
// re-sort), so the sort machinery must live here.
const COLOR_RANK = {
  black:0,gray:1,grey:1,silver:2,white:3,ivory:4,cream:5,beige:6,brown:7,tan:8,khaki:9,copper:10,
  red:20,pink:21,coral:22,orange:23,peach:24,salmon:25,
  yellow:30,gold:31,mustard:32,olive:33,
  green:40,lime:41,mint:42,teal:50,aqua:51,turquoise:52,cyan:53,
  blue:60,navy:61,indigo:62,periwinkle:63,
  purple:70,violet:71,lavender:72,plum:73,magenta:74,fuchsia:75,
};
function colorRank(p) {
  const tags = (p.tags || []).map(t => String(t).toLowerCase());
  for (const t of tags) for (const k of Object.keys(COLOR_RANK)) if (t.includes(k)) return COLOR_RANK[k];
  return 999;
}
const STYLE_TAGS = ['traditional','transitional','modern','contemporary','minimalist','art deco','victorian','mid-century','mid century','rustic','industrial','farmhouse','bohemian','boho','geometric','floral','botanical','damask','toile','grasscloth','silk','linen','vinyl','natural'];
function styleKey(p) {
  const tags = (p.tags || []).map(t => String(t).toLowerCase());
  for (const s of STYLE_TAGS) if (tags.some(t => t.includes(s))) return s;
  return 'zzz';
}

const COLOR_HEX = {
  black:'#0a0a0a',charcoal:'#2a2a2a',gray:'#888',grey:'#888',silver:'#c0c0c0',
  white:'#fff',ivory:'#fffff0',cream:'#f5e9c8',champagne:'#f0d8a8',beige:'#e7d6b6',sand:'#dccfa6',blonde:'#e8d8a0',
  brown:'#6b4a2b',chestnut:'#5a3825',umber:'#5a3a1f',tan:'#c9a36a',khaki:'#bda464',honey:'#d6a23c',
  copper:'#b87333',brass:'#b5a642',bronze:'#9c6b30',gold:'#d4af37',amber:'#c98a32',butterscotch:'#d6943c',saffron:'#d6a93c',ochre:'#b88c3a',mustard:'#caa53d',
  red:'#c92a2a',coral:'#e87a6b',pink:'#e6a4b4',salmon:'#e08e7c',rose:'#d68a9a',magenta:'#c5358a',fuchsia:'#d63aaf',
  orange:'#e07a32',peach:'#f0bb96',apricot:'#e0a373',
  yellow:'#e8c84a',butter:'#f0e1a0',
  olive:'#7a7a36','olive ':'#7a7a36',
  green:'#3d8a4f',lime:'#92c84a',mint:'#aedcc1',
  teal:'#2a8a8a',aqua:'#3ab4b4',turquoise:'#3ab8b0',cyan:'#3acac4',aquamarine:'#9ed5c8',
  blue:'#3a5fb8',navy:'#1a2c52',indigo:'#37327a',periwinkle:'#8a93d4',
  purple:'#6a3a8a',violet:'#7a4aa8',lavender:'#b0a3d6',plum:'#693a55',gilver:'#bfb9b3'
};
function rgbOfTag(tag) {
  const k = String(tag||'').toLowerCase().trim();
  for (const name of Object.keys(COLOR_HEX)) if (k.includes(name)) return COLOR_HEX[name];
  return null;
}
function hexToRgb(h){const m=/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(h||'');return m?[parseInt(m[1],16),parseInt(m[2],16),parseInt(m[3],16)]:null;}
function rgbToHsl(r,g,b){r/=255;g/=255;b/=255;const mx=Math.max(r,g,b),mn=Math.min(r,g,b);let h=0,s=0,l=(mx+mn)/2;if(mx!==mn){const d=mx-mn;s=l>.5?d/(2-mx-mn):d/(mx+mn);switch(mx){case r:h=(g-b)/d+(g<b?6:0);break;case g:h=(b-r)/d+2;break;case b:h=(r-g)/d+4;break;}h*=60;}return[h,s,l];}
function dominantHex(p){
  if (p.dominant_hex_real && /^#[\da-f]{6}$/i.test(p.dominant_hex_real)) return p.dominant_hex_real;
  const tags=(p.tags||[]).map(t=>String(t).toLowerCase());
  for (const t of tags){const hx=rgbOfTag(t);if(hx)return hx;}
  return '#888';
}
function luminance(p){const rgb=hexToRgb(dominantHex(p));return rgb?(0.2126*rgb[0]+0.7152*rgb[1]+0.0722*rgb[2]):128;}
function hue(p){const rgb=hexToRgb(dominantHex(p));if(!rgb)return 999;const [h,s]=rgbToHsl(rgb[0],rgb[1],rgb[2]);return s<0.08?999:h;}

function sortProducts(list, mode) {
  if (mode === 'sku') return [...list].sort((a,b) => String(a.sku || a.handle || '').localeCompare(String(b.sku || b.handle || '')));
  if (mode === 'title') return [...list].sort((a,b) => String(a.title || '').localeCompare(String(b.title || '')));
  if (mode === 'color') return [...list].sort((a,b) => colorRank(a) - colorRank(b) || String(a.title || '').localeCompare(String(b.title || '')));
  if (mode === 'style') return [...list].sort((a,b) => styleKey(a).localeCompare(styleKey(b)) || String(a.title || '').localeCompare(String(b.title || '')));
  if (mode === 'light-dark') return [...list].sort((a,b) => luminance(b) - luminance(a)); // bright first
  if (mode === 'dark-light') return [...list].sort((a,b) => luminance(a) - luminance(b)); // dark first
  if (mode === 'wheel') return [...list].sort((a,b) => hue(a) - hue(b));
  if (mode === 'price-asc')  return [...list].sort((a,b) => (Number(a.max_price) || 0) - (Number(b.max_price) || 0));
  if (mode === 'price-desc') return [...list].sort((a,b) => (Number(b.max_price) || 0) - (Number(a.max_price) || 0));
  if (mode === 'title-desc')     return [...list].sort((a,b) => String(b.title || '').localeCompare(String(a.title || '')));
  if (mode === 'sku-desc')       return [...list].sort((a,b) => String(b.sku || b.handle || '').localeCompare(String(a.sku || a.handle || '')));
  if (mode === 'aesthetic')      return [...list].sort((a,b) => String(a.aesthetic || '').localeCompare(String(b.aesthetic || '')) || String(a.title || '').localeCompare(String(b.title || '')));
  if (mode === 'aesthetic-desc') return [...list].sort((a,b) => String(b.aesthetic || '').localeCompare(String(a.aesthetic || '')) || String(a.title || '').localeCompare(String(b.title || '')));
  return list;
}

// Dual-key /sample resolver: the client links with the vendor-scrubbed
// `handle_display` (= redactVendorText(handle), the same value the redact
// middleware injects into API responses). Map that redacted slug back to the
// product so the sample link resolves without the raw vendor-bearing handle
// ever riding in the URL bar.
let SAMPLE_DISPLAY = new Map();
(function buildSampleDisplayMap() {
  const map = new Map();
  const collided = new Set();
  for (const p of PRODUCTS) {
    for (const key of [p.handle, p.sku]) {
      if (!key) continue;
      const d = redactVendorText(String(key));
      if (!d || d === key) continue;           // nothing redacted — raw route already matches
      const prev = map.get(d);
      if (prev && prev !== p) { collided.add(d); continue; }
      map.set(d, p);
    }
  }
  for (const d of collided) map.delete(d);       // ambiguous slug — keep raw-only
  SAMPLE_DISPLAY = map;
  console.log(`[1980swallpaper] /sample dual-key map: ${map.size} display slugs, ${collided.size} collisions (raw-only)`);
})();

const app = express();
// Security headers (contentSecurityPolicy disabled — the storefront inlines styles/scripts).
app.use(helmet({ contentSecurityPolicy: false }));
// Fleet vendor redactor: scrubs vendor/vendors/title/sku/tags from every /api/*
// JSON body, injects handle_display, and serves the vendor-neutral /img/ proxy.
app.use(vendorRedact);
if (typeof vendorRedact.warm === 'function') vendorRedact.warm(PRODUCTS); // pre-warm /img token map (cold-start 404 fix)
app.use(express.static(path.join(__dirname, 'public')));

app.get('/api/products', (req, res) => {
  const { q, aesthetic, page = 1, limit = 24, sort = 'newest' } = req.query;
  let list = PRODUCTS;
  if (q) {
    const needle = q.toLowerCase();
    list = list.filter(p => (p.title || '').toLowerCase().includes(needle) || (p.tags || []).some(t => t.toLowerCase().includes(needle)));
  }
  if (aesthetic && aesthetic !== 'all') list = list.filter(p => p.aesthetic === aesthetic);
  list = sortProducts(list, sort);
  const total = list.length;
  const pageNum = Math.max(1, parseInt(page, 10) || 1);
  const lim = Math.min(60, parseInt(limit, 10) || 24);
  const start = (pageNum - 1) * lim;
  res.json({ total, page: pageNum, limit: lim, pages: Math.ceil(total / lim), sort, items: list.slice(start, start + lim) });
});

app.get('/api/sliders', (req, res) => {
  // Data-driven: feature the aesthetics that actually exist in the catalog,
  // most-populous first, each with >=4 items. Avoids a hardcoded list drifting
  // out of sync with the data (the old list carried dead memphis/neon/pop values).
  const counts = {};
  for (const p of PRODUCTS) { const a = p.aesthetic; if (a) counts[a] = (counts[a] || 0) + 1; }
  const ordered = Object.keys(counts).sort((a, b) => counts[b] - counts[a]);
  const out = [];
  for (const a of ordered) {
    const items = PRODUCTS.filter(p => p.aesthetic === a).slice(0, 12);
    if (items.length >= 4) out.push({ aesthetic: a, items });
  }
  res.json({ rails: out });
});

app.get('/api/facets', (req, res) => {
  const aesthetics = {}; const vendors = {};
  for (const p of PRODUCTS) {
    aesthetics[p.aesthetic] = (aesthetics[p.aesthetic] || 0) + 1;
    vendors[p.vendor] = (vendors[p.vendor] || 0) + 1;
  }
  // `vendors` is dropped by the redact middleware before it reaches the client.
  res.json({ aesthetics, vendors, total: PRODUCTS.length });
});

app.get('/api/health', (req, res) => res.json({ status: 'ok', count: PRODUCTS.length, dropped: DROPPED }));

app.get('/sample/:handle', (req, res) => {
  const key = req.params.handle;
  const p = PRODUCTS.find(x => x.handle === key || x.sku === key) // raw first — old bookmarks + buy path
    || SAMPLE_DISPLAY.get(key);                                   // then the redacted display slug
  if (!p) return res.status(404).send('Not found');
  res.redirect(302, p.product_url || `${DW_SHOPIFY}/products/${encodeURIComponent(p.handle)}#sample`);
});

// sitemap.xml + robots.txt for SEO
app.get('/robots.txt', (req, res) => {
  res.type('text/plain').send(`User-agent: *
Allow: /
Sitemap: https://retrowalls.com/sitemap.xml
`);
});
app.get('/sitemap.xml', (req, res) => {
  const urls = ['/'];
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls.map(u => `  <url><loc>https://retrowalls.com${u}</loc><changefreq>weekly</changefreq></url>`).join('\n')}
</urlset>`;
  res.type('application/xml').send(xml);
});

app.listen(PORT, '127.0.0.1', () => {
  console.log(`1980swallpaper listening on http://127.0.0.1:${PORT}`);
});