← back to Designer Wallcoverings
TK-135: multi-label normalizer — strip Style:/Motif:/Material:/Collection:/Colorway: to bare (hardened, timestamped, gated)
9fceefa707613b760037a909395a70820f420c21 · 2026-07-28 06:57:09 -0700 · Steve
Files touched
A shopify/scripts/tk135-label-normalize.js
Diff
commit 9fceefa707613b760037a909395a70820f420c21
Author: Steve <steve@designerwallcoverings.com>
Date: Tue Jul 28 06:57:09 2026 -0700
TK-135: multi-label normalizer — strip Style:/Motif:/Material:/Collection:/Colorway: to bare (hardened, timestamped, gated)
---
shopify/scripts/tk135-label-normalize.js | 110 +++++++++++++++++++++++++++++++
1 file changed, 110 insertions(+)
diff --git a/shopify/scripts/tk135-label-normalize.js b/shopify/scripts/tk135-label-normalize.js
new file mode 100644
index 00000000..0ff84f62
--- /dev/null
+++ b/shopify/scripts/tk135-label-normalize.js
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+/**
+ * TK-00135 — Multi-label tag normalizer (GATED live write, Shopify-authoritative).
+ * Strips the descriptor label prefixes Style: / Motif: / Material: / Collection: / Colorway:
+ * to BARE values, catalog-wide (same idea as the color normalize). Per product:
+ * tagsRemove(all prefixed label tags) + tagsAdd(their bare values) + stamp custom.labels_normalized_at.
+ *
+ * Input : data/tk135/label-prefixed.tsv (gid\ttags) — active products carrying any of the labels.
+ * DRY-RUN by default; --apply required. Idempotent, resumable (progress log), never flips status,
+ * only touches the listed label prefixes. Hardened: retries 502/gateway/network, never crashes.
+ *
+ * node tk135-label-normalize.js # DRY-RUN
+ * node tk135-label-normalize.js --apply --limit 20 # canary (gated)
+ * node tk135-label-normalize.js --apply --report data/tk135/label-run.json
+ */
+const https = require('https'), fs = require('fs'), os = require('os'), path = require('path');
+const args = process.argv.slice(2);
+const APPLY = args.includes('--apply');
+const arg = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
+const LIMIT = parseInt(arg('--limit', '0'), 10) || Infinity;
+const IN = arg('--in', path.join(__dirname, 'data/tk135/label-prefixed.tsv'));
+const REPORT = arg('--report', null);
+const PROGRESS = arg('--progress', path.join(__dirname, 'data/tk135/label-normalize-progress.log'));
+
+const env = fs.readFileSync(os.homedir() + '/Projects/secrets-manager/.env', 'utf8');
+const TOKEN = (env.match(/^SHOPIFY_ADMIN_TOKEN=(.*)$/m) || [])[1].replace(/['"]/g, '').trim();
+const STORE = 'designer-laboratory-sandbox.myshopify.com', API = '2024-10';
+const NOW = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
+const sleep = ms => new Promise(r => setTimeout(r, ms));
+process.on('unhandledRejection', e => console.error('⚠ unhandledRejection (continuing):', String(e).slice(0, 120)));
+
+const LABEL_RE = /^\s*(style|motif|material|collection|colorway)\s*:\s*/i;
+
+function gql(query, variables = {}) {
+ return new Promise((resolve, reject) => {
+ const body = JSON.stringify({ query, variables });
+ const req = https.request({ host: STORE, path: `/admin/api/${API}/graphql.json`, method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': TOKEN, 'Content-Length': Buffer.byteLength(body) } },
+ r => { let d = ''; r.on('data', c => d += c); r.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(d); } }); });
+ req.on('error', reject); req.write(body); req.end();
+ });
+}
+async function gqlR(q, v, tries = 8) {
+ for (let i = 0; i < tries; i++) {
+ try {
+ const r = await gql(q, v);
+ if (r && !r.errors) return r;
+ if (!(r.errors || []).some(e => /throttl/i.test(JSON.stringify(e)))) return r;
+ } catch (e) { /* 502/gateway/network — retry */ }
+ await sleep(2000 * (i + 1));
+ }
+ return null;
+}
+const M_MF = `mutation($mf:[MetafieldsSetInput!]!){metafieldsSet(metafields:$mf){userErrors{field message}}}`;
+const M_ADD = `mutation($id:ID!,$tags:[String!]!){tagsAdd(id:$id,tags:$tags){userErrors{field message}}}`;
+const M_DEL = `mutation($id:ID!,$tags:[String!]!){tagsRemove(id:$id,tags:$tags){userErrors{field message}}}`;
+
+function load() {
+ const out = [];
+ for (const l of fs.readFileSync(IN, 'utf8').trim().split('\n')) {
+ const i = l.indexOf('\t'); if (i < 0) continue;
+ const gid = l.slice(0, i);
+ const tags = l.slice(i + 1).split(',').map(s => s.trim()).filter(Boolean);
+ const prefixed = tags.filter(t => LABEL_RE.test(t));
+ if (!prefixed.length) continue;
+ const existingBare = new Set(tags.filter(t => !LABEL_RE.test(t)));
+ const remove = [...new Set(prefixed)];
+ const add = [...new Set(prefixed.map(t => t.replace(LABEL_RE, '').trim()).filter(Boolean))].filter(b => !existingBare.has(b));
+ out.push({ gid, remove, add });
+ }
+ return out;
+}
+
+(async () => {
+ let rows = load();
+ if (fs.existsSync(PROGRESS)) {
+ const done = new Set(fs.readFileSync(PROGRESS, 'utf8').split('\n').filter(Boolean));
+ const b = rows.length; rows = rows.filter(r => !done.has(r.gid));
+ if (b !== rows.length) console.log(`resume: skipping ${b - rows.length} already-done\n`);
+ }
+ if (LIMIT !== Infinity) rows = rows.slice(0, LIMIT);
+ const totRm = rows.reduce((a, r) => a + r.remove.length, 0), totAdd = rows.reduce((a, r) => a + r.add.length, 0);
+ console.log(`tk135-label-normalize — ${rows.length} products (${totRm} prefixed→remove, ${totAdd} bare→add) — ${APPLY ? '🔴 LIVE' : 'DRY-RUN'}\n in: ${IN} (Shopify-authoritative; mirror re-syncs)\n`);
+ const report = { ticket: 'TK-135', op: 'label-normalize', started: NOW, apply: APPLY, updated: [], failed: [] };
+
+ if (!APPLY) {
+ rows.slice(0, 10).forEach(r => console.log(` · ${r.gid.split('/').pop()} -[${r.remove.join(', ')}] +[${r.add.join(', ')}]`));
+ console.log(`\n (dry-run) ${rows.length} products would be normalized. No writes.`);
+ if (REPORT) { fs.mkdirSync(path.dirname(REPORT), { recursive: true }); fs.writeFileSync(REPORT, JSON.stringify({ ...report, totals: { would_update: rows.length, remove: totRm, add: totAdd } }, null, 2)); }
+ return;
+ }
+
+ for (const r of rows) {
+ try {
+ let errs = [];
+ const mf = await gqlR(M_MF, { mf: [{ ownerId: r.gid, namespace: 'custom', key: 'labels_normalized_at', type: 'date_time', value: NOW }] });
+ if (!mf) errs.push({ message: 'metafield: no response' }); else errs = errs.concat(mf.data?.metafieldsSet?.userErrors || []);
+ if (r.remove.length) { const d = await gqlR(M_DEL, { id: r.gid, tags: r.remove }); if (!d) errs.push({ message: 'tagsRemove: no response' }); else errs = errs.concat(d.data?.tagsRemove?.userErrors || []); }
+ if (r.add.length) { const a = await gqlR(M_ADD, { id: r.gid, tags: r.add }); if (!a) errs.push({ message: 'tagsAdd: no response' }); else errs = errs.concat(a.data?.tagsAdd?.userErrors || []); }
+ if (errs.length) { report.failed.push({ gid: r.gid, errs }); console.log(` ❌ ${r.gid.split('/').pop()} ${JSON.stringify(errs)}`); }
+ else { report.updated.push(r.gid); fs.appendFileSync(PROGRESS, r.gid + '\n'); }
+ } catch (e) { report.failed.push({ gid: r.gid, errs: [String(e.message || e).slice(0, 140)] }); console.log(` ⚠ ${r.gid.split('/').pop()} ${String(e.message || e).slice(0, 80)}`); }
+ if (report.updated.length % 500 === 0 && report.updated.length) console.log(` …${report.updated.length} normalized`);
+ await sleep(150);
+ }
+ report.finished = new Date().toISOString();
+ report.totals = { updated: report.updated.length, failed: report.failed.length };
+ console.log(`\n=== SUMMARY ===\nnormalized=${report.totals.updated} failed=${report.totals.failed}`);
+ if (REPORT) { fs.mkdirSync(path.dirname(REPORT), { recursive: true }); fs.writeFileSync(REPORT, JSON.stringify(report, null, 2)); console.log(`report -> ${REPORT}`); }
+})();
← a35d3f5d auto-save: 2026-07-28T06:27:56 (1 files) — shopify/scripts/d
·
back to Designer Wallcoverings
·
auto-save: 2026-07-28T06:58:06 (3 files) — shopify/scripts/d f722f343 →