Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 26x 26x 26x 26x 26x 26x 27x 27x 27x 27x 27x 18x 17x 17x 1x 1x 18x 27x 27x 27x 27x 27x 27x 27x 27x 27x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 5x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 3x 3x 3x 5x 27x 27x 27x 27x 27x 27x 27x 27x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 27x 27x 27x 27x 27x 27x 27x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 4x 3x 3x 2x 2x 1x 1x 4x 27x 27x 1x 1x 1x 1x 1x 27x 27x 5x 5x 5x 3x 3x 2x 2x 5x 27x 27x 27x 27x 27x 27x 27x 27x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 27x 27x 27x 27x 27x 27x 27x 27x 8x 8x 8x 8x 8x 7x 7x 7x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 8x 8x 8x 8x 1x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 6x 4x 4x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 6x 6x 6x 6x 6x 2x 2x 6x 6x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 2x 2x 2x 2x 2x 8x 27x 27x 27x 27x 27x 27x 27x 7x 7x 7x 7x 7x 5x 7x 3x 3x 3x 3x 4x 4x 4x 7x 7x 7x 7x 7x 7x 7x 7x 7x 4x 4x 4x 4x 7x 27x 27x 27x 27x 27x 27x 27x 27x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 27x 27x 27x 27x 27x 27x 27x 27x 5x 2x 2x 5x 5x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 5x 27x 27x 27x 27x 27x 27x 106x 106x 1x 1x 1x 106x 106x 106x 106x 27x 27x 27x 27x 27x 27x 2x 2x 2x 2x 2x 2x 27x 27x 27x 27x 27x 27x 27x 27x 14x 9x 9x 5x 8x 1x 1x 4x 8x 1x 1x 3x 8x 2x 2x 1x 1x 14x 27x 27x 27x 27x 27x 27x 27x 5x 1x 1x 4x 4x 4x 4x 4x 5x 27x 27x 27x 27x 27x 27x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 3x 27x 27x 27x | /**
* Servicio para manejar work items específicamente para generación de PDFs
* Capa sobre AzureDevOpsService con funcionalidad adicional
*/
const { AzureDevOpsService } = require("./azureDevOps");
const path = require("path");
class WorkItemService {
// Subdirectorios por defecto de SharePoint
static DEFAULT_SUBDIRECTORIES = [
"Planificacion",
"Presentaciones",
"Vistos_Buenos_DB",
"Vistos_Buenos_CRT",
"Pruebas_Usuario",
"Pruebas_Preprod",
];
// Profundidad máxima de recursión para child items
static MAX_CHILD_DEPTH = 3;
// Cache LRU limitado (100 entradas máximo)
static MAX_CACHE_SIZE = 100;
/**
* @param {string} organization - Organización de Azure DevOps
* @param {string} pat - Personal Access Token
* @param {Function} logCallback - Función para logging
*/
constructor(organization, pat, logCallback = null) {
this.azureService = new AzureDevOpsService(organization, pat, logCallback);
this.logCallback = logCallback;
// Caché para colores de estado (optimización performance)
this.stateColorCache = new Map();
this.cacheAccessOrder = []; // Para LRU tracking
}
/**
* Log interno
*/
log(message) {
if (this.logCallback) {
this.logCallback(message);
} else {
console.log(message);
}
}
/**
* Obtener work items del pase actual basado en número de pase
* @param {string} passNumber - Número de pase (ej: "7501")
* @param {string} organization - Organización de Azure DevOps
* @param {string} pat - PAT de Azure DevOps
* @returns {Promise<Array>} Work items formateados para el modal
*/
async getWorkItemsForPass(passNumber, organization, pat) {
try {
// Validar passNumber antes de usarlo en consulta WIQL (SQL injection prevention)
if (!passNumber || typeof passNumber !== "string") {
throw new Error("Pass number inválido");
}
// Validar formato: alfanuméricos, guiones, espacios, puntos, guión bajo
// Azure DevOps permite una variedad más amplia de caracteres en tags
// Limitamos caracteres peligrosos para SQL injection
const sanitizedPassNumber = passNumber.trim();
if (!/^[A-Z0-9\s._-]{1,50}$/i.test(sanitizedPassNumber)) {
throw new Error(
"Pass number contiene caracteres no permitidos o excede longitud máxima (50 caracteres)",
);
}
// ⚠️ NOTA CRÍTICA DE SEGURIDAD: SQL INJECTION PREVENTION
// WIQL (Work Item Query Language) NO soporta parámetros preparados como SQL estándar.
// La API de Azure DevOps requiere interpolación de strings directa en la query.
//
// REGLA OBLIGATORIA: TODAS las variables interpoladas en WIQL DEBEN ser validadas
// con regex whitelist estricta ANTES de usarse en la query.
//
// La validación anterior (líneas 64-70) asegura que SOLO caracteres seguros
// [A-Z0-9\s._-] son permitidos, bloqueando caracteres SQL como ', ", --, ;, etc.
//
// ⚠️ NO REMOVER O RELAJAR esta validación sin implementar sanitización alternativa.
// ⚠️ SI agregan más variables interpoladas, DEBEN validarse con regex similar.
// Construir query WIQL con passNumber validado (solo caracteres seguros)
const wiql = `
SELECT [System.Id], [System.Title], [System.State],
[System.WorkItemType], [System.AssignedTo],
[System.AreaPath], [System.IterationPath], [System.Tags]
FROM WorkItems
WHERE [System.Title] CONTAINS '${sanitizedPassNumber}'
OR [System.Tags] CONTAINS '${sanitizedPassNumber}'
ORDER BY [System.Id] DESC
`;
const workItems = await this.azureService.queryWorkItems(
wiql,
organization,
pat,
);
if (workItems.length === 0) {
this.log(`No se encontraron work items para el pase ${passNumber}`);
return [];
}
// Formatear work items para el modal
const formattedItems = workItems.map((wi) =>
this._formatWorkItemForModal(wi),
);
this.log(`${formattedItems.length} work item(s) formateados`);
return formattedItems;
} catch (error) {
this.log(`Error obteniendo work items: ${error.message}`);
throw error;
}
}
/**
* Formatear work item para display en el modal
* @param {Object} workItem - Work item de Azure DevOps API
* @returns {Object} Work item formateado
* @private
*/
_formatWorkItemForModal(workItem) {
const fields = workItem.fields || {};
return {
id: workItem.id,
title: fields["System.Title"] || "Sin título",
state: fields["System.State"] || "Unknown",
type: fields["System.WorkItemType"] || "Unknown",
project: fields["System.TeamProject"] || "Unknown",
iteration: fields["System.IterationPath"] || "Sin asignar",
assignedTo: this._extractDisplayName(fields["System.AssignedTo"]),
area: fields["System.AreaPath"] || "Sin área",
tags: fields["System.Tags"] || "",
};
}
/**
* Obtener un resumen ligero de un work item
* @param {number|string} workItemId - ID del work item
* @returns {Promise<Object>} Resumen del work item
*/
async getWorkItemSummary(workItemId) {
const normalizedId = Number(workItemId);
if (!Number.isFinite(normalizedId)) {
throw new Error("Work item ID invalido");
}
const fields = [
"System.Title",
"System.Description",
"System.AcceptanceCriteria",
"Microsoft.VSTS.Common.AcceptanceCriteria",
"System.AssignedTo",
"System.AreaPath",
"System.IterationPath",
"System.State",
"System.Tags",
"System.TeamProject",
"System.CreatedDate",
"System.CreatedBy",
"System.ChangedDate",
"System.ChangedBy",
"System.WorkItemType",
];
let remainingFields = [...fields];
let lastError = null;
let workItem = null;
while (remainingFields.length > 0) {
try {
workItem = await this._fetchWorkItemSummary(
normalizedId,
remainingFields,
);
break;
} catch (error) {
lastError = error;
const missingField = this._extractMissingField(error);
if (!missingField || !remainingFields.includes(missingField)) {
break;
}
remainingFields = remainingFields.filter(
(field) => field !== missingField,
);
}
}
if (!workItem) {
throw lastError || new Error("No se pudo obtener el work item");
}
return this._formatWorkItemSummary(workItem);
}
async _fetchWorkItemSummary(workItemId, fields) {
const fieldsParam = fields.join(",");
const url = `https://dev.azure.com/${this.azureService.organization}/_apis/wit/workitems/${workItemId}?api-version=7.0&fields=${fieldsParam}`;
const response = await this.azureService.client.get(url);
return response.data;
}
_extractMissingField(error) {
const message = error?.response?.data?.message || error?.message || "";
const match = message.match(/Cannot find field\s+'?([A-Za-z0-9_.]+)'?/i);
if (!match) {
return "";
}
return match[1].replace(/[\s.]+$/g, "").trim();
}
/**
* Formatear un work item para RFC/subtareas
* @param {Object} workItem - Work item de Azure DevOps API
* @returns {Object} Resumen formateado
* @private
*/
_formatWorkItemSummary(workItem) {
const fields = workItem.fields || {};
return {
id: workItem.id,
title: fields["System.Title"] || "",
description: fields["System.Description"] || "",
acceptanceCriteria:
fields["System.AcceptanceCriteria"] ||
fields["Microsoft.VSTS.Common.AcceptanceCriteria"] ||
"",
assignedTo: this._extractDisplayName(fields["System.AssignedTo"]),
areaPath: fields["System.AreaPath"] || "",
iterationPath: fields["System.IterationPath"] || "",
state: fields["System.State"] || "",
tags: fields["System.Tags"] || "",
project: fields["System.TeamProject"] || "",
createdDate: fields["System.CreatedDate"] || "",
changedDate: fields["System.ChangedDate"] || "",
workItemType: fields["System.WorkItemType"] || "",
};
}
/**
* Obtener detalles completos de un work item para generación de PDF
* @param {number} workItemId - ID del work item
* @param {Array<string>} selectedFields - Campos seleccionados para incluir en el PDF
* @returns {Promise<Object>} Work item con detalles completos en formato Azure DevOps API
*/
async getWorkItemDetails(workItemId, selectedFields = []) {
try {
// Usar la organización configurada en el constructor (this.azureService.organization)
const url = `https://dev.azure.com/${this.azureService.organization}/_apis/wit/workitems/${workItemId}?api-version=7.0&$expand=all`;
const response = await this.azureService.client.get(url);
const workItem = response.data;
if (!workItem) {
throw new Error(`Work item ${workItemId} no encontrado`);
}
// CRÍTICO: Validar tamaño máximo de contenido HTML para prevenir DoS
//
// ⚠️ LIMITACIÓN CONOCIDA: El truncamiento ocurre DESPUÉS de cargar
// el contenido en memoria. Esto es una limitación de la API de Azure DevOps
// que no provee streaming ni headers Content-Length antes del fetch.
//
// MITIGACIÓN PARCIAL implementada:
// 1. Límite de 20 work items por operación (línea 397)
// 2. Límite de 1MB por campo individual
// 3. Throttling de requests concurrentes (implementado en WorkItemPDFModal)
//
// Para mitigación completa se requeriría:
// - Rate limiting a nivel de extensión (fuera del alcance actual)
// - Usar Azure DevOps Batch API (no disponible para Work Items)
const MAX_HTML_SIZE = 1024 * 1024; // 1MB
const descriptionSize = (workItem.fields?.["System.Description"] || "")
.length;
const acceptanceCriteriaSize = (
workItem.fields?.["System.AcceptanceCriteria"] ||
workItem.fields?.["Microsoft.VSTS.Common.AcceptanceCriteria"] ||
""
).length;
if (descriptionSize > MAX_HTML_SIZE) {
this.log(
`Advertencia: Descripción del work item ${workItemId} excede ${MAX_HTML_SIZE} bytes (${descriptionSize})`,
);
workItem.fields["System.Description"] =
workItem.fields["System.Description"].substring(0, MAX_HTML_SIZE) +
"\n\n[Contenido truncado por exceder tamaño máximo]";
}
if (acceptanceCriteriaSize > MAX_HTML_SIZE) {
const field = workItem.fields?.["System.AcceptanceCriteria"]
? "System.AcceptanceCriteria"
: "Microsoft.VSTS.Common.AcceptanceCriteria";
this.log(
`Advertencia: Criterios de aceptación del work item ${workItemId} exceden ${MAX_HTML_SIZE} bytes (${acceptanceCriteriaSize})`,
);
workItem.fields[field] =
workItem.fields[field].substring(0, MAX_HTML_SIZE) +
"\n\n[Contenido truncado por exceder tamaño máximo]";
}
// OPTIMIZACIÓN: Solo obtener datos si los campos están seleccionados
const parallelCalls = [];
// Llamada 1: Obtener comentarios solo si se necesitan (siempre se incluyen por ahora)
parallelCalls.push(
this.azureService.getWorkItemComments(
workItemId,
this.azureService.organization,
this.azureService.pat,
),
);
// Llamada 2: Obtener comentarios del historial (siempre se incluyen)
parallelCalls.push(
this.azureService.getWorkItemUpdates(
workItemId,
this.azureService.organization,
this.azureService.pat,
),
);
// Llamada 3: Obtener child items si están seleccionados
if (selectedFields.includes("childItems")) {
parallelCalls.push(
this._getChildItems(
workItemId,
this.azureService.organization,
this.azureService.pat,
),
);
} else {
parallelCalls.push(Promise.resolve([]));
}
// Ejecutar todas las llamadas en paralelo
const [comments, historyComments, childItems] =
await Promise.all(parallelCalls);
// Combinar ambos tipos de comentarios y eliminar duplicados
const allComments = [...comments, ...historyComments];
// Ordenar por fecha de creación (más antiguos primero)
allComments.sort((a, b) => {
const dateA = new Date(a.createdDate || 0);
const dateB = new Date(b.createdDate || 0);
return dateA - dateB;
});
// Agregar comentarios y child items al work item
workItem.comments = allComments;
if (selectedFields.includes("childItems")) {
workItem.childItems = childItems;
}
// Obtener color del estado desde Azure DevOps (con caché)
const project = workItem.fields?.["System.TeamProject"];
const workItemType = workItem.fields?.["System.WorkItemType"];
const state = workItem.fields?.["System.State"];
if (project && workItemType && state) {
// Usar caché para evitar N+1 queries
const cacheKey = `${project}_${workItemType}_${state}`;
let stateColor = this.stateColorCache.get(cacheKey);
if (!stateColor) {
// No está en caché, consultarlo
stateColor = await this.azureService.getWorkItemStateColor(
project,
workItemType,
state,
this.azureService.organization,
this.azureService.pat,
);
if (stateColor) {
// Implementar LRU cache con límite
this._addToCache(cacheKey, stateColor);
}
} else {
// Actualizar orden de acceso en LRU
this._updateCacheAccess(cacheKey);
}
if (stateColor) {
workItem.stateColor = stateColor;
}
}
// Devolver el work item en formato Azure DevOps API original
// (con estructura fields: { "System.Title": "...", ... })
// más los comentarios agregados
return workItem;
} catch (error) {
this.log(
`Error obteniendo detalles del work item ${workItemId}: ${error.message}`,
);
throw error;
}
}
/**
* Obtener adjuntos de un work item
* @param {number} workItemId - ID del work item
* @returns {Promise<Array>} Lista de adjuntos
*/
async getWorkItemAttachments(workItemId) {
try {
if (
!workItemId ||
typeof workItemId !== "number" ||
workItemId <= 0 ||
!Number.isInteger(workItemId)
) {
throw new Error(
"Work item ID inválido: debe ser un número entero positivo",
);
}
const url = `https://dev.azure.com/${this.azureService.organization}/_apis/wit/workitems/${workItemId}?$expand=relations&api-version=7.0`;
const response = await this.azureService.client.get(url);
const relations = response.data?.relations || [];
const attachments = relations
.filter((relation) => relation?.rel === "AttachedFile")
.map((relation) => this._formatAttachment(relation))
.filter((attachment) => attachment.url);
return attachments;
} catch (error) {
const errorMessage = `Error obteniendo adjuntos del work item ${workItemId}: ${error.message}`;
this.log(errorMessage);
throw new Error(errorMessage);
}
}
/**
* Formatear adjunto desde relation de Azure DevOps
* @param {Object} relation
* @returns {Object}
* @private
*/
_formatAttachment(relation) {
const name = relation?.attributes?.name || "adjunto";
const url = relation?.url || "";
const size = relation?.attributes?.resourceSize ?? null;
const comment = relation?.attributes?.comment || "";
const extension = path.extname(name).toLowerCase();
return {
id: this._extractAttachmentId(url),
name,
url,
size,
comment,
extension,
};
}
/**
* Extraer ID de adjunto desde URL
* @param {string} url
* @returns {string|null}
* @private
*/
_extractAttachmentId(url) {
if (!url || typeof url !== "string") return null;
const match = url.match(/attachments\/([^/?]+)/i);
return match ? match[1] : null;
}
/**
* Obtener child items de un work item
* @param {number} workItemId - ID del work item padre
* @param {string} organization - Organización de Azure DevOps
* @param {string} pat - PAT de Azure DevOps
* @param {number} depth - Profundidad actual (interno)
* @param {number} maxDepth - Profundidad máxima permitida
* @returns {Promise<Array>} Lista de child items
* @private
*/
async _getChildItems(
workItemId,
organization,
pat,
depth = 0,
maxDepth = WorkItemService.MAX_CHILD_DEPTH,
) {
try {
// CRÍTICO: Limitar profundidad de recursión para evitar problemas de performance
if (depth >= maxDepth) {
this.log(
`Límite de profundidad alcanzado (${maxDepth}) para work item ${workItemId}`,
);
return [];
}
// Query WIQL para obtener child items (solo nivel directo, no recursivo)
const wiql = `
SELECT [System.Id], [System.Title], [System.State],
[System.WorkItemType], [System.AssignedTo]
FROM WorkItemLinks
WHERE (Source.[System.Id] = ${workItemId})
AND (Target.[System.WorkItemType] <> '')
AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward')
MODE (MustContain)
`;
const workItems = await this.azureService.queryWorkItems(
wiql,
organization,
pat,
);
return workItems.map((wi) => {
const fields = wi.fields || {};
return {
id: wi.id,
type: fields["System.WorkItemType"] || "Unknown",
title: fields["System.Title"] || "Sin título",
state: fields["System.State"] || "Unknown",
assignedTo: this._extractDisplayName(fields["System.AssignedTo"]),
};
});
} catch (error) {
// Logging del error para debugging
this.log(
`Error obteniendo child items para ${workItemId}: ${error.message}`,
);
return [];
}
}
/**
* Agregar entrada al cache LRU
* @private
*/
_addToCache(key, value) {
// Si el cache está lleno, eliminar la entrada menos usada
if (this.stateColorCache.size >= WorkItemService.MAX_CACHE_SIZE) {
const oldestKey = this.cacheAccessOrder.shift();
this.stateColorCache.delete(oldestKey);
}
this.stateColorCache.set(key, value);
this.cacheAccessOrder.push(key);
}
/**
* Actualizar orden de acceso en LRU
* @private
*/
_updateCacheAccess(key) {
const index = this.cacheAccessOrder.indexOf(key);
if (index > -1) {
this.cacheAccessOrder.splice(index, 1);
this.cacheAccessOrder.push(key);
}
}
/**
* Extraer nombre para display de objeto AssignedTo
* @param {Object|string} assignedToField - Campo AssignedTo de Azure DevOps
* @returns {string} Nombre para display
* @private
*/
_extractDisplayName(assignedToField) {
if (!assignedToField) {
return "Sin asignar";
}
if (typeof assignedToField === "string") {
return assignedToField;
}
if (assignedToField.displayName) {
return assignedToField.displayName;
}
if (assignedToField.uniqueName) {
return assignedToField.uniqueName;
}
return "Sin asignar";
}
/**
* Validar que el número de pase sea válido
* @param {string} passNumber - Número de pase (formato flexible)
* @returns {boolean} True si es válido
*/
static isValidPassNumber(passNumber) {
if (!passNumber || typeof passNumber !== "string") {
return false;
}
// Validar formato flexible: alfanuméricos, espacios, guiones, puntos, guión bajo
// Máximo 50 caracteres
const trimmed = passNumber.trim();
return /^[A-Z0-9\s._-]{1,50}$/i.test(trimmed);
}
/**
* Obtener subdirectorios configurados de SharePoint
* @returns {Promise<Array<string>>} Lista de subdirectorios
*/
static async getConfiguredSubdirectories() {
const vscode = require("vscode");
const path = require("path");
const fs = require("fs").promises;
try {
const workspaceFolder =
vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
if (!workspaceFolder) {
throw new Error("No hay carpeta de workspace abierta");
}
const configPath = path.join(workspaceFolder, "config.json");
const configContent = await fs.readFile(configPath, "utf8");
const config = JSON.parse(configContent);
const subdirectories = config.sharepoint?.subdirectories;
if (!subdirectories) {
throw new Error(
"No se encontró configuración de subdirectorios en config.json",
);
}
// Parsear subdirectorios (separados por coma)
return subdirectories
.split(",")
.map((dir) => dir.trim())
.filter((dir) => dir.length > 0);
} catch (error) {
console.error("Error obteniendo subdirectorios:", error);
return WorkItemService.DEFAULT_SUBDIRECTORIES;
}
}
}
module.exports = WorkItemService;
|