196 lines
11 KiB
JavaScript
196 lines
11 KiB
JavaScript
#!/usr/bin/env node
|
|
// Lê ou escreve na API REST do Azure DevOps (dev.azure.com) preservando UTF-8, com o token do `az` sem imprimi-lo.
|
|
//
|
|
// Existe porque o `az` (o az.exe do Windows, chamado do PowerShell ou do WSL) corrompe acentuação nos dois
|
|
// sentidos: ao ler o corpo de `--in-file` e argumentos como `--description`, e ao escrever a saída (sai na
|
|
// página de código ANSI do Windows, não em UTF-8). Substitui o `TOKEN=$(az account get-access-token …)` +
|
|
// `curl --data-binary @/tmp/…json`, que só rodava em bash.
|
|
//
|
|
// Uso:
|
|
// node devops-rest.mjs <caminho-da-api> --org <org> --project <projeto> [--method GET|POST|PATCH]
|
|
// [--file <corpo.json>] [--content-type json|json-patch] [--pick <a/b/c> …] [--api-version 7.1] [--dry-run]
|
|
//
|
|
// <caminho-da-api> o que vem depois de /<org>/<projeto>/, ex.: _apis/git/repositories/<repo>/pullrequests
|
|
// --file corpo JSON em UTF-8, gravado pela ferramenta de arquivos do cliente (obrigatório em POST/PATCH)
|
|
// --content-type json (padrão) ou json-patch. A API de work item (POST _apis/wit/workitems/$<Tipo> e PATCH
|
|
// _apis/wit/workitems/<id>) só aceita application/json-patch+json, com o corpo em array JSON Patch;
|
|
// o script escolhe json-patch sozinho nesses dois caminhos, e a flag força um ou outro
|
|
// --pick imprime só esse campo da resposta (caminho separado por /, ex.: fields/System.Title); repetível
|
|
// --dry-run valida o corpo e mostra método, URL e corpo, sem pedir token e sem chamar a API
|
|
//
|
|
// Depois de POST/PATCH, se a resposta trouxer `url`, faz GET nela e compara cada campo de texto de primeiro
|
|
// nível do corpo enviado com o que voltou: o POST/PATCH devolve 200 mesmo com texto corrompido, então só o
|
|
// GET prova que a acentuação chegou. Divergência ou U+FFFD dá código de saída 1. Em corpo JSON Patch o
|
|
// conferido é cada `/fields/<campo>`: texto puro volta idêntico; HTML (Description etc.) o Boards normaliza
|
|
// (aspas, entidades), então só se exige que não haja U+FFFD e que cada caractere acentuado enviado tenha voltado.
|
|
// Corpo com assinatura de IA (Co-Authored-By, Claude-Session, link de sessão, "Generated with Claude", 🤖) é
|
|
// recusado antes de enviar, também no --dry-run: regra 18 do AGENTS.md da raiz.
|
|
// Com `?validateOnly=true` nada é criado: imprime a resposta (ou os campos que a regra do processo exige) e sai.
|
|
// Só módulos nativos do Node 18+.
|
|
|
|
import { readFileSync } from 'node:fs';
|
|
import { azDevOpsToken, isLoginPage, loginPageMessage } from '../../../scripts/az-devops-token.mjs';
|
|
|
|
class Fail extends Error {}
|
|
const fail = (m) => { throw new Fail(m); };
|
|
const USAGE = 'uso: node devops-rest.mjs <caminho-da-api> --org <org> --project <projeto> [--method GET|POST|PATCH] [--file <corpo.json>] [--content-type json|json-patch] [--pick <a/b>] [--api-version 7.1] [--dry-run]';
|
|
const REPLACEMENT = String.fromCharCode(0xfffd);
|
|
const AI_SIGNATURE = /co-authored-by\s*:|claude-session\s*:|claude\.ai\/code\/session|generated (with|by) \[?(claude|ai\b)|\u{1F916}/iu;
|
|
|
|
// --help/-h: uso no stdout e código 0, antes de validar qualquer parâmetro.
|
|
if (process.argv.slice(2).some((a) => a === '--help' || a === '-h')) { console.log(USAGE); process.exit(0); }
|
|
|
|
function parse(argv) {
|
|
const o = { path: null, org: null, project: null, method: 'GET', file: null, contentType: null, pick: [], apiVersion: '7.1', dryRun: false };
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const a = argv[i];
|
|
const next = () => { if (i + 1 >= argv.length) fail(`${a} sem valor`); return argv[++i]; };
|
|
if (a === '--org') o.org = next();
|
|
else if (a === '--project') o.project = next();
|
|
else if (a === '--method') o.method = next().toUpperCase();
|
|
else if (a === '--file') o.file = next();
|
|
else if (a === '--content-type') o.contentType = next();
|
|
else if (a === '--pick') o.pick.push(next());
|
|
else if (a === '--api-version') o.apiVersion = next();
|
|
else if (a === '--dry-run') o.dryRun = true;
|
|
else if (a.startsWith('--')) fail(`opção desconhecida ${a}`);
|
|
else if (o.path === null) o.path = a;
|
|
else fail(`argumento a mais: ${a}`);
|
|
}
|
|
if (!o.path) fail('falta o caminho da API');
|
|
if (!o.org || !o.project) fail('--org e --project são obrigatórios');
|
|
if (!['GET', 'POST', 'PATCH'].includes(o.method)) fail('--method aceita GET, POST ou PATCH');
|
|
if (o.method !== 'GET' && !o.file) fail(`${o.method} exige --file com o corpo JSON`);
|
|
if (o.contentType !== null && !['json', 'json-patch'].includes(o.contentType)) fail('--content-type aceita json ou json-patch');
|
|
if (o.method === 'GET' && o.file) fail('GET não leva --file');
|
|
return o;
|
|
}
|
|
|
|
async function getToken(org) {
|
|
// Pedido no tenant da organização (ver az-devops-token.mjs); a falha já traz o `az login` certo.
|
|
try { return await azDevOpsToken(org); } catch (e) { return fail(e.message); }
|
|
}
|
|
|
|
// O caminho de work item (criar ou editar) exige JSON Patch; sem a flag, o caminho decide.
|
|
const isWorkItemWrite = (method, path) => method !== 'GET' && /(^|\/)_apis\/wit\/workitems(\/|$)/i.test(path);
|
|
|
|
async function call(method, url, token, body, mime = 'application/json') {
|
|
const res = await fetch(url, {
|
|
method,
|
|
headers: { Authorization: 'Bearer ' + token, ...(body ? { 'Content-Type': mime + '; charset=utf-8' } : {}) },
|
|
body,
|
|
});
|
|
// Token de outro tenant: o fetch segue o 302 para a página de login e devolve 203 com ok=true.
|
|
if (isLoginPage(res)) fail(await loginPageMessage(res, String(url), token));
|
|
const text = await res.text();
|
|
if (!res.ok) {
|
|
// 400 de regra do processo: lista os campos obrigatórios em vez de só o texto cru.
|
|
let rules = [];
|
|
try { rules = JSON.parse(text)?.customProperties?.RuleValidationErrors ?? []; } catch { /* corpo não é JSON */ }
|
|
const fields = rules.map((r) => r.fieldReferenceName).filter(Boolean);
|
|
fail(`${method} ${String(url).split('?')[0]} -> HTTP ${res.status}: ${text.slice(0, 800)}` +
|
|
(fields.length ? `\ncampos exigidos pela regra do processo: ${fields.join(', ')}` : ''));
|
|
}
|
|
try { return JSON.parse(text); } catch { return text; }
|
|
}
|
|
|
|
// Confere o que o GET devolveu contra um corpo JSON Patch: só `add`/`replace` em /fields/<ref> com texto.
|
|
function checkPatch(ops, back) {
|
|
const bad = [];
|
|
for (const op of ops) {
|
|
const m = typeof op?.path === 'string' && typeof op.value === 'string' ? /^\/fields\/(.+)$/.exec(op.path) : null;
|
|
if (!m) continue;
|
|
const got = back?.fields?.[m[1]];
|
|
if (typeof got !== 'string') { bad.push(`${m[1]} (ausente)`); continue; }
|
|
const html = /<[a-z!/][^>]*>/i.test(op.value);
|
|
const lost = [...new Set(op.value.match(/[^\x00-\x7f]/g) ?? [])].some((c) => !got.includes(c));
|
|
if (got.includes(REPLACEMENT) || lost || (!html && got !== op.value)) bad.push(m[1]);
|
|
}
|
|
return bad;
|
|
}
|
|
|
|
const pickPath = (obj, p) => p.split('/').reduce((acc, k) => (acc == null ? undefined : acc[k]), obj);
|
|
|
|
function show(data, picks) {
|
|
if (picks.length === 0) { console.log(typeof data === 'string' ? data : JSON.stringify(data, null, 2)); return; }
|
|
for (const p of picks) {
|
|
const v = pickPath(data, p);
|
|
console.log(typeof v === 'string' ? v : JSON.stringify(v));
|
|
}
|
|
}
|
|
|
|
async function main() {
|
|
const o = parse(process.argv.slice(2));
|
|
const org = o.org.replace(/\/+$/, '');
|
|
const orgUrl = org.startsWith('http') ? org : 'https://dev.azure.com/' + org;
|
|
const url = new URL(`${orgUrl}/${encodeURIComponent(o.project)}/${o.path.replace(/^\/+/, '')}`);
|
|
if (!url.searchParams.has('api-version')) url.searchParams.set('api-version', o.apiVersion);
|
|
|
|
let sent = null;
|
|
let body;
|
|
if (o.file) {
|
|
let raw = readFileSync(o.file, 'utf8');
|
|
// BOM: o az.exe quebra com "Unexpected UTF-8 BOM"; aqui ele só é retirado.
|
|
if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1);
|
|
if (raw.includes(REPLACEMENT)) fail(`o arquivo já contém U+FFFD (acento corrompido antes de enviar): ${o.file}`);
|
|
try { sent = JSON.parse(raw); } catch (e) { fail(`corpo não é JSON válido: ${e.message}`); }
|
|
const sig = AI_SIGNATURE.exec(JSON.stringify(sent));
|
|
if (sig) fail(`o corpo tem assinatura de IA ("${sig[0]}"); retire-a antes de enviar (regra 18 do AGENTS.md da raiz): ${o.file}`);
|
|
body = Buffer.from(JSON.stringify(sent), 'utf8');
|
|
}
|
|
const patch = o.contentType ? o.contentType === 'json-patch' : isWorkItemWrite(o.method, o.path);
|
|
if (patch && !Array.isArray(sent)) fail('json-patch exige corpo em array de operações JSON Patch ([{"op":"add","path":"/fields/…","value":…}])');
|
|
const mime = patch ? 'application/json-patch+json' : 'application/json';
|
|
|
|
if (o.dryRun) {
|
|
console.log(`${o.method} ${url}`);
|
|
if (o.file) console.log(`Content-Type: ${mime}; charset=utf-8`);
|
|
if (sent) console.log(JSON.stringify(sent, null, 2));
|
|
console.log('--dry-run: nada foi enviado.');
|
|
return;
|
|
}
|
|
|
|
const token = await getToken(orgUrl);
|
|
const data = await call(o.method, url, token, body, mime);
|
|
if (o.method === 'GET') { show(data, o.pick); return; }
|
|
|
|
if (url.searchParams.get('validateOnly') === 'true') { console.log('validateOnly: regras do processo satisfeitas; nada foi criado.'); return; }
|
|
show(data, o.pick.length ? o.pick : ['id', 'url']);
|
|
let backUrl = null;
|
|
if (data && typeof data === 'object' && data.url) {
|
|
backUrl = new URL(data.url);
|
|
if (!backUrl.searchParams.has('api-version')) backUrl.searchParams.set('api-version', o.apiVersion);
|
|
if (patch) backUrl.searchParams.set('$expand', 'relations');
|
|
}
|
|
const back = backUrl ? await call('GET', backUrl, token) : null;
|
|
if (!back) { console.error('aviso: a resposta não traz `url`; confira com um GET no recurso antes de dar por certo.'); return; }
|
|
const bad = [];
|
|
if (patch) bad.push(...checkPatch(sent, back));
|
|
else for (const [k, v] of Object.entries(sent || {})) {
|
|
if (typeof v !== 'string') continue;
|
|
if (back[k] === undefined) continue;
|
|
if (back[k] !== v || String(back[k]).includes(REPLACEMENT)) bad.push(k);
|
|
}
|
|
if (bad.length) {
|
|
console.error(`GET de conferência: texto diferente do enviado em ${bad.join(', ')} — corrija com PATCH no mesmo recurso.`);
|
|
process.exitCode = 1;
|
|
} else {
|
|
console.log(patch
|
|
? 'GET de conferência: campos acentuados voltaram sem U+FFFD (HTML normalizado pelo Boards é esperado).'
|
|
: 'GET de conferência: campos de texto voltaram idênticos ao enviado (acentuação íntegra).');
|
|
}
|
|
if (patch && Array.isArray(back?.relations)) {
|
|
const parent = back.relations.find((r) => r.rel === 'System.LinkTypes.Hierarchy-Reverse');
|
|
const wantsParent = sent.some((op) => op?.path === '/relations/-' && op?.value?.rel === 'System.LinkTypes.Hierarchy-Reverse');
|
|
console.log('pai: ' + (parent ? parent.url.split('/').pop() : 'nenhum'));
|
|
if (wantsParent && !parent) { console.error('o corpo pedia o pai, mas o item voltou sem relação Hierarchy-Reverse (órfão).'); process.exitCode = 1; }
|
|
}
|
|
}
|
|
|
|
// exitCode, e não process.exit(): no Windows, process.exit() logo depois de um fetch derruba o Node (assert do libuv).
|
|
try { await main(); }
|
|
catch (e) {
|
|
if (e instanceof Fail) { console.error('erro: ' + e.message); if (/obrigat|falta|opção|argumento|aceita|exige|leva/.test(e.message)) console.error(USAGE); process.exitCode = e.message.includes('HTTP') ? 1 : 2; }
|
|
else throw e;
|
|
}
|