Redesign an existing website to make it better. Built on top of impeccable.
88%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Low
Low-risk findings worth noting
#!/usr/bin/env node
/**
* skills/deploy/scripts/martech-scaffold.mjs — martech contract → scripts/martech.js (reference/martech.md).
*
* Writes scripts/martech.js from the enabled parts of stardust/martech-contract.json and hooks it in:
* loadConsent() the CMP, first thing in loadEager() of scripts/scripts.js
* loadTags() each enabled route, from scripts/consented.js (the boilerplate's consent phase), else
* scripts/delayed.js, else loadDelayed() in scripts/scripts.js; a route with a `category`
* waits until the CMP grants that consent group
* hasConsent() with consented.js, the boilerplate's placeholder hasConsent() in scripts/consent-check.js
* (declines by default) is replaced by one that asks martech.js; each route keeps its own
* category gate, and a loadTags() hook left in loadDelayed() / delayed.js by an older run is
* removed. Only the placeholder, matched token for token, is replaced: any other hasConsent()
* is a conflict until it calls martech.js hasConsent() (--force does not override it)
* aemMartech when enabled, the Web SDK through the aem-martech plugin (plugins/martech, installed by the
* owner): initMartech + martechEager from loadConsent(), martechLazy from loadAnalytics()
* (hooked into loadLazy() after loadFooter, so page views go out without the delayed wait),
* martechDelayed (which loads `launchUrls`) from loadTags(); a `category` makes the Web SDK
* start `pending` whatever the source value, and sets `collect` once the CMP grants it
* Nothing loads off the production hosts unless the URL has `?martech=on`; `&consent=accept` then grants
* every category. Off production, `?consent=` decides consented.js as in the boilerplate (accept loads it,
* decline keeps it and the tags unloaded), else `?martech=on` does. A scripts/martech.js the scaffold did not
* write is a conflict unless --force.
* Re-running on the same contract changes nothing.
*
* node skills/deploy/scripts/martech-scaffold.mjs [--contract stardust/martech-contract.json] [--root .]
* [--dry-run] [--force]
*
* Exit 0 written or unchanged; 1 usage error, invalid contract, conflict, missing plugin, or no hook point.
*/
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
if (process.argv.includes('--help') || process.argv.includes('-h')) {
const header = readFileSync(new URL(import.meta.url), 'utf8').match(/\/\*\*[\s\S]*?\*\//)[0];
console.log(header.replace(/^\/\*\*\s*|\s*\*\/$/g, '').replace(/^\s*\* ?/gm, '').trim());
process.exit(0);
}
const argv = process.argv.slice(2);
const arg = (name, dflt) => { const i = argv.indexOf(`--${name}`); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : dflt; };
const fail = (msg) => { console.error(`martech-scaffold: ${msg}`); process.exit(1); };
const ROOT = resolve(arg('root', '.'));
const CONTRACT = arg('contract', 'stardust/martech-contract.json');
const DRY = argv.includes('--dry-run');
const FORCE = argv.includes('--force');
const MARK = '// Generated by stardust deploy/martech-scaffold.mjs from the martech contract; re-run it.';
const CONSENT_HOOK = "import('./martech.js').then((m) => m.loadConsent());";
const TAGS_HOOK = "import('./martech.js').then((m) => m.loadTags());";
const LAZY_HOOK = "import('./martech.js').then((m) => m.loadAnalytics());";
const CHECK_IMPORT = "import { hasConsent as martechConsent } from './martech.js';";
const CHECK_FN = `// Generated by stardust deploy/martech-scaffold.mjs: martech.js decides; re-run it.
// True on the production hosts, where the CMP gates each tag (its category in martech.js loadTags())
// and anything else in consented.js runs ungated. Off production: ?consent=accept|decline, else ?martech=on.
function hasConsent() {
return martechConsent();
}`;
// aem-boilerplate's placeholder (scripts/consent-check.js since d966eff9), the only hasConsent() the scaffold replaces.
const PLACEHOLDER = `function hasConsent() {
const consent = new URLSearchParams(window.location.search).get('consent');
if (consent !== null) {
return ['accept', 'true', '1', 'yes'].includes(consent.toLowerCase());
}
// default: decline
return false;
}`;
const at = (p) => join(ROOT, p);
const read = (p) => (existsSync(at(p)) ? readFileSync(at(p), 'utf8') : null);
const str = (s) => `'${JSON.stringify(s).slice(1, -1).replace(/\\"/g, '"').replace(/'/g, "\\'")}'`;
function literal(v, pad = '') {
if (typeof v === 'string') return str(v);
if (v === null || typeof v !== 'object') return String(v);
const inner = `${pad} `;
const items = Array.isArray(v)
? v.map((x) => literal(x, inner))
: Object.entries(v).map(([k, x]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : str(k)}: ${literal(x, inner)}`);
const [open, close] = Array.isArray(v) ? ['[', ']'] : ['{', '}'];
return items.length ? `${open}\n${items.map((i) => `${inner}${i},\n`).join('')}${pad}${close}` : `${open}${close}`;
}
const pluginDir = (am) => am.plugin?.path || 'plugins/martech';
function configOf(contract) {
const cmp = contract.consent?.cmp || null;
const routes = (contract.routes || []).filter((r) => r.enabled);
const missing = cmp?.enabled && Object.entries(cmp.attrs || {}).find(([, v]) => !v);
if (missing) fail(`consent.cmp is enabled but \`${missing[0]}\` is empty — copy the id from the CMP admin into the contract`);
const gated = routes.find((r) => r.category && !(cmp?.groups && cmp?.event));
if (gated) fail(`route \`${gated.id}\` has a category but the CMP exposes no consent groups — clear the category or set consent.cmp.groups/event`);
const am = contract.aemMartech?.enabled ? contract.aemMartech : null;
if (am) {
const k = am.config || {};
const plugin = `${pluginDir(am)}/src/index.js`;
if (!existsSync(at(plugin))) fail(`aemMartech is enabled but ${plugin} is missing — install it: git subtree add --squash --prefix ${pluginDir(am)} ${am.plugin?.repo || 'https://github.com/adobe-rnd/aem-martech.git'} main`);
const unset = ['orgId', 'datastreamId', 'defaultConsent'].find((f) => !k[f]);
if (unset) fail(`aemMartech is enabled but config.${unset} is empty — fill it from the hand-off`);
const twice = routes.find((r) => (k.launchUrls || []).includes(r.src));
if (twice) fail(`route \`${twice.id}\` is enabled and also in aemMartech.config.launchUrls — disable the route; the plugin loads it`);
if (am.category && !(cmp?.groups && cmp?.event)) fail('aemMartech has a category but the CMP exposes no consent groups — clear the category or set consent.cmp.groups/event');
if (k.defaultConsent === 'pending' && !am.category) fail('aemMartech.config.defaultConsent is `pending` with no category — nothing would ever be sent');
}
const target = contract.target?.enabled ? contract.target : null;
if (target && !am) fail('target is enabled but aemMartech is not — switch the Web SDK on first; the plugin renders Target only through it');
if (target && !target.webSdk) fail('target is enabled but the source renders no Target decisions through the Web SDK — move the at.js activities to the Web SDK first');
return {
productionHosts: contract.productionHosts || [],
cmp: cmp && {
enabled: !!cmp.enabled, src: cmp.src, attrs: cmp.attrs || {}, groups: cmp.groups || null, event: cmp.event || null,
},
routes: routes.map(({ src, boot, category }) => ({ src, boot: boot || null, category: category || null })),
...(am && {
aemMartech: {
module: `../${pluginDir(am)}/src/index.js`,
// a category gates collection on the CMP: the SDK must not collect before it is granted
webSdk: Object.fromEntries(['orgId', 'datastreamId', 'edgeDomain', 'defaultConsent'].filter((f) => am.config[f])
.map((f) => [f, f === 'defaultConsent' && am.category ? 'pending' : am.config[f]])),
options: { alloyInstanceName: am.config.alloyInstanceName || 'alloy', launchUrls: am.config.launchUrls || [], personalization: !!target },
category: am.category || null,
},
}),
};
}
const AM_CONSENT = `
let webSdk = null;
async function startWebSdk() {
const martech = await import(CONFIG.aemMartech.module);
await martech.initMartech(CONFIG.aemMartech.webSdk, CONFIG.aemMartech.options);
await martech.martechEager();
return martech;
}
export function loadConsent() {
if (!on) return;
if (CONFIG.cmp?.enabled) load(CONFIG.cmp.src, CONFIG.cmp.attrs);
webSdk = startWebSdk();
}
let analytics = null;
export function loadAnalytics() {
analytics = analytics || webSdk?.then(async (martech) => {
if (CONFIG.aemMartech.category) whenGranted(CONFIG.aemMartech.category, () => martech.updateUserConsent({ collect: true }));
await martech.martechLazy();
return martech;
}) || null;
return analytics;
}
`;
const AM_TAGS = `
loadAnalytics()?.then((martech) => martech.martechDelayed());`;
const runtime = (config) => `${MARK}
const CONFIG = ${literal(config)};
const params = new URLSearchParams(window.location.search);
const production = CONFIG.productionHosts.includes(window.location.host);
const on = production || params.get('martech') === 'on';
const acceptAll = !production && params.get('consent') === 'accept';
function load(src, attrs = {}) {
const script = document.createElement('script');
script.src = src;
script.async = true;
Object.entries(attrs).forEach(([name, value]) => script.setAttribute(name, value));
document.head.append(script);
}
const BOOT = {
gtm: () => window.dataLayer.push({ 'gtm.start': Date.now(), event: 'gtm.js' }),
gtag: (src) => {
window.gtag = window.gtag || function gtag() {
// eslint-disable-next-line prefer-rest-params
window.dataLayer.push(arguments);
};
window.gtag('js', new Date());
window.gtag('config', new URL(src).searchParams.get('id'));
},
};
const granted = (category) => acceptAll
|| String(window[CONFIG.cmp.groups] || '').split(',').includes(category);
function whenGranted(category, run) {
if (!category || granted(category)) {
run();
return;
}
const retry = () => {
if (!granted(category)) return;
window.removeEventListener(CONFIG.cmp.event, retry);
run();
};
window.addEventListener(CONFIG.cmp.event, retry);
}
// consent-check.js loads consented.js (the loadTags hook) only when this is true.
export function hasConsent() {
if (production) return true;
const consent = params.get('consent');
if (consent !== null) return ['accept', 'true', '1', 'yes'].includes(consent.toLowerCase());
return on;
}
${config.aemMartech ? AM_CONSENT.slice(1) : `export function loadConsent() {
if (!on || !CONFIG.cmp?.enabled) return;
load(CONFIG.cmp.src, CONFIG.cmp.attrs);
}
export function loadAnalytics() {}
`}
export function loadTags() {
if (!on) return;
CONFIG.routes.forEach(({ src, boot, category }) => whenGranted(category, () => {
if (boot) {
window.dataLayer = window.dataLayer || [];
BOOT[boot](src);
}
load(src);
}));${config.aemMartech ? AM_TAGS : ''}
}
`;
/** Inserts `line` first in `fn`, or after the first statement of `fn` matching `after` when there is one. */
function hook(text, fn, line, after = null) {
if (text.includes(line)) return text;
const open = new RegExp(`((?:async\\s+)?function ${fn}\\([^)]*\\)\\s*\\{\\n)`);
const m = open.exec(text);
if (!m) return null;
const start = m.index + m[0].length;
const end = text.indexOf('\n}', start);
const body = text.slice(start, end < 0 ? undefined : end);
const anchor = after && new RegExp(`^([ \\t]*)${after}.*$`, 'm').exec(body);
if (anchor) {
const at = start + anchor.index + anchor[0].length;
return `${text.slice(0, at)}\n${anchor[1]}${line}${text.slice(at)}`;
}
return `${text.slice(0, start)} ${line}\n${text.slice(start)}`;
}
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const PLACEHOLDER_RE = new RegExp(PLACEHOLDER.split(/\s+/).map(escape).join('\\s+'));
/** Removes every line that is only `line` (an older run's hook). */
const unhook = (text, line) => text.replace(new RegExp(`^[ \\t]*${escape(line)}[ \\t]*\\r?\\n`, 'gm'), '');
/**
* consent-check.js wired to martech.js: unchanged when its hasConsent() already calls martechConsent(), else
* the boilerplate placeholder (and the JSDoc right above it) replaced by CHECK_FN. Anything else fails.
*/
function patchConsentCheck(text) {
if (/\bmartechConsent\s*\(/.test(text)) {
if (!/from\s+['"]\.\/martech\.js['"]/.test(text)) fail(`scripts/consent-check.js calls martechConsent() but imports nothing from ./martech.js — add \`${CHECK_IMPORT}\``);
return text;
}
const m = PLACEHOLDER_RE.exec(text);
const before = m && text.slice(0, m.index);
if (!m || /\b(?:async|export)\s*$/.test(before)) {
const what = /\bhasConsent\b/.test(text)
? 'has a hasConsent() that is not the boilerplate placeholder (your CMP wiring, or a placeholder reworded upstream)'
: 'has no hasConsent()';
fail(`scripts/consent-check.js ${what} — add \`${CHECK_IMPORT}\` and make hasConsent() return true when martechConsent() does, then re-run`);
}
const doc = /\/\*\*(?:(?!\*\/)[\s\S])*\*\/\s*$/.exec(before);
const start = doc ? doc.index : m.index;
const body = `${text.slice(0, start)}${CHECK_FN}${text.slice(m.index + m[0].length)}`;
return `${CHECK_IMPORT}\n\n${body}`;
}
const contractPath = at(CONTRACT);
if (!existsSync(contractPath)) fail(`no contract at ${contractPath} — run dynamics-plan.mjs --martech first`);
const config = configOf(JSON.parse(readFileSync(contractPath, 'utf8')));
const scripts = read('scripts/scripts.js');
if (scripts === null) fail('no scripts/scripts.js under --root');
const delayed = read('scripts/delayed.js');
const withEager = hook(scripts, 'loadEager', CONSENT_HOOK);
if (withEager === null) fail(`no loadEager() in scripts/scripts.js — add \`${CONSENT_HOOK}\` where the page starts loading`);
const withConsent = config.aemMartech ? hook(withEager, 'loadLazy', LAZY_HOOK, 'loadFooter\\(') : withEager;
if (withConsent === null) fail(`aemMartech is enabled but there is no loadLazy() in scripts/scripts.js — add \`${LAZY_HOOK}\` after the footer loads`);
const edits = { 'scripts/martech.js': runtime(config) };
const consented = read('scripts/consented.js');
const consentCheck = read('scripts/consent-check.js');
if (consented !== null && consentCheck !== null) {
edits['scripts/consent-check.js'] = patchConsentCheck(consentCheck);
// an older run hooked loadTags() into loadDelayed() or delayed.js: left there, the tags would load twice
edits['scripts/scripts.js'] = unhook(withConsent, TAGS_HOOK);
if (delayed !== null) edits['scripts/delayed.js'] = unhook(delayed, TAGS_HOOK);
edits['scripts/consented.js'] = consented.includes(TAGS_HOOK) ? consented : `${consented.replace(/\n*$/, '\n')}${TAGS_HOOK}\n`;
} else if (delayed !== null) {
edits['scripts/scripts.js'] = withConsent;
edits['scripts/delayed.js'] = delayed.includes(TAGS_HOOK) ? delayed : `${delayed.replace(/\n*$/, '\n')}${TAGS_HOOK}\n`;
} else {
const withTags = hook(withConsent, 'loadDelayed', TAGS_HOOK);
if (withTags === null) fail(`no scripts/delayed.js and no loadDelayed() in scripts/scripts.js — add \`${TAGS_HOOK}\` after the page has loaded`);
edits['scripts/scripts.js'] = withTags;
}
const current = read('scripts/martech.js');
if (current !== null && !current.startsWith(MARK) && !FORCE) fail('scripts/martech.js exists and was not written by this scaffold — move it or pass --force');
const changed = Object.entries(edits).filter(([p, text]) => read(p) !== text);
const enabled = `${config.cmp?.enabled ? `CMP ${config.cmp.src}` : 'no CMP'} · ${config.routes.length} route(s) enabled${config.aemMartech ? ' · Web SDK via aem-martech' : ''}`;
if (!changed.length) {
console.log(`martech-scaffold: unchanged (${enabled})`);
process.exit(0);
}
changed.forEach(([p]) => console.log(`${DRY ? 'would write' : 'write'} ${p}`));
console.log(`martech-scaffold: ${enabled}`);
if (!DRY) changed.forEach(([p, text]) => writeFileSync(at(p), text));.tessl-plugin
skills
audit
reference
deploy
reference
scripts
test
diff
direct
dynamics
extract
migrate
prepare-migration
prototype
assets
motion
fixtures
reference
qa
replica
reference
scripts
test
reskin
rollout
spec
stardust
uplift
reference