/** * Custom field names (aliases) and value lists in .mpp files, ported from * MPXJ's CustomFieldReader12, CustomFieldReader14, CustomFieldValueReader, * CustomFieldValueReader9, CustomFieldValueReader12, CustomFieldValueReader14, * VarDataFieldReader and MPP9Reader.processFieldNameAliases (LGPL-2.1, * https://github.com/joniles/mpxj). * * Project 2007 and later keep each renamed field in the task and resource * folders' Props (a list of field number + name), with a table that ties * each field to its value list; the values themselves (with their * descriptions and, for outline codes, their parents) are records in * TBkndOutlCode. A task's value picked from a list is stored as a reference * to one of those records. Project 2000-2003 lists the names in the project * Props by position, and the value lists of ordinary fields in one block. */ import { FixedData, FixedMeta, Props, Var2Data, VarMeta } from './blocks'; import { Calendar, adjustedDuration, durationUnits, f64, guid, i32, timestamp, u16, unicode } from './bytes'; import { FieldClass, Value, fieldFor } from './fieldmap'; import { CustomField, TimeUnit } from './model'; /** PropsKey.CUSTOM_FIELDS, TASK_FIELD_NAME_ALIASES, RESOURCE_FIELD_NAME_ALIASES, TASK_FIELD_ATTRIBUTES. */ export const CF_KEY = { CUSTOM_FIELDS: 71303169, TASK_FIELD_NAME_ALIASES: 1048577, RESOURCE_FIELD_NAME_ALIASES: 1048578, TASK_FIELD_ATTRIBUTES: 37753744 }; /** One entry of a value list (MPXJ's CustomFieldValueItem). */ interface ValueItem { uid: number; guid: string; value: Value; description: string; parent: number; } type CalendarWithUnits = Calendar & { defaultUnits: TimeUnit }; /** "Text1", "Outline Code3": how Project names a field. */ const FIELD_RE = /^(TEXT|NUMBER|FLAG|DATE|START|FINISH|DURATION|COST|OUTLINE_CODE)(\d+)$/; /** * The plan's custom fields as read so far: names, value lists, and the * values by unique ID and GUID that task fields refer to. */ export class CustomFields { private readonly fields = new Map(); private readonly byUid = new Map(); private readonly byGuid = new Map(); constructor(private readonly cal: CalendarWithUnits) {} private getOrCreate(cls: FieldClass, field: string) { const key = `${cls}:${field}`; let f = this.fields.get(key); if (!f) this.fields.set(key, (f = { cls, field, alias: '', items: [] })); return f; } setAlias(cls: FieldClass, field: string, alias: string): void { if (!FIELD_RE.test(field) || cls === 'assignment') return; this.getOrCreate(cls, field).alias = alias; } /* ── Project 2007 and later ─────────────────────────────────────────── */ /** The names block of a folder's Props (CustomFieldReader12/14.process: only the aliases are used). */ readAliases(props: Props, mpp14: boolean): void { const data = props.bytes(CF_KEY.CUSTOM_FIELDS); if (!data || data.length < 12) return; const blockSize = i32(data, 0); const count = i32(data, 8); let offset = 12; for (let index = 0; index < count && offset < blockSize && offset + 8 <= data.length; index++) { const fieldId = i32(data, offset); const aliasOffset = i32(data, offset + 4) + 4; offset += 8; if (aliasOffset < 0 || aliasOffset >= data.length) continue; const alias = unicode(data, aliasOffset); const f = fieldFor(fieldId, mpp14); if (alias && f) this.setAlias(f.cls, f.def[0], alias); } } /** * Value list GUID -> field, from a folder's Props (MPP14Reader and * MPP12Reader.populateLookupTableMap): 88-byte records in 2010 and later, * records of their own length in 2007. */ lookupTables(props: Props, mpp14: boolean, into: Map): void { const data = props.bytes(CF_KEY.CUSTOM_FIELDS); if (!data || data.length < 4) return; const add = (fieldId: number, at: number) => { const f = fieldFor(fieldId, mpp14); const g = guid(data, at); if (f && g) into.set(g, { cls: f.cls, field: f.def[0] }); }; let index = i32(data, 0) + 36; if (mpp14) { for (; index >= 0 && index + 52 <= data.length; index += 88) add(i32(data, index), index + 36); return; } if (index < 0 || index + 4 > data.length) return; index += 4 + 8 * i32(data, index); while (index >= 0 && index + 176 <= data.length) { const blockLength = i32(data, index); if (blockLength <= 0 || index + blockLength > data.length) break; add(i32(data, index + 4), index + 160); index += blockLength; } } /** * The value records in TBkndOutlCode (CustomFieldValueReader.process). * Offsets inside the records moved between versions: 2007 (12), 2010 and * 2013 or later. */ readValues(o: { varMeta: VarMeta; varData: Var2Data; fixed: FixedData; fixed2: FixedData; tables: Map; version: 12 | 14 | 15 }): void { const [parentOffset, typeOffset, fieldOffset] = o.version === 12 ? [8, 48, 32] : o.version === 14 ? [8, 32, 16] : [10, 16, 18]; for (let loop = 0; loop < o.fixed.count; loop++) { const fixed = o.fixed.item(loop); if (!fixed || fixed.length < 6) continue; const id = u16(fixed, 4); if (!o.varMeta.has(id)) continue; const raw = o.varData.bytes(id, 22); if (!raw) continue; const fixed2 = o.fixed2.item(loop); const item: ValueItem = { uid: id, guid: guid(fixed2, 0), value: null, description: o.varData.string(id, 8) ?? '', parent: fixed.length >= parentOffset + 2 ? u16(fixed, parentOffset) : 0, }; const type = fixed2 && fixed2.length >= typeOffset + 2 ? u16(fixed2, typeOffset) : -1; item.value = this.typedValue(type, raw); this.register(item); const table = o.tables.get(guid(fixed2, fieldOffset)); if (!table) continue; const f = this.getOrCreate(table.cls, table.field); const at = f.items.findIndex((i) => i.uid === item.uid); if (at === -1) f.items.push(item); else f.items[at] = item; } } private register(item: ValueItem): void { this.byUid.set(item.uid, item); if (item.guid) this.byGuid.set(item.guid, item); } /** CustomFieldValueReader.getTypedValue: CustomFieldValueDataType numbers 4 date, 6 duration, 9 cost, 15 number, 21 text, 27 finish date. */ private typedValue(type: number, v: Uint8Array): Value { switch (type) { case 4: case 27: return timestamp(v, 0); case 6: return adjustedDuration(this.cal, i32(v, 0), durationUnits(u16(v, 4), this.cal.defaultUnits)); case 9: return f64(v, 0) / 100; case 15: return f64(v, 0); default: return unicode(v, 0); } } /** * A field's value picked from a value list (VarDataFieldReader.getValueByID): * a two-byte flag, the value's unique ID, then its GUID. */ pick(b: Uint8Array | null): Value { if (!b || b.length < 6) return null; const uid = i32(b, 2); const g = guid(b, 6); const item = (uid !== -1 ? this.byUid.get(uid) : undefined) ?? (g ? this.byGuid.get(g) : undefined); return item ? item.value : null; } /** * An outline code's value (MPP14Reader.getCustomFieldOutlineCodeValue): * either a string in TBkndOutlCode, or a reference to a value whose * parents make up the code, "A.B.C". */ outlineCode(b: Uint8Array | null, outlineVar: Var2Data): string | null { if (!b || b.length < 6) return null; if ((u16(b, 0) & 0xff00) !== 0x0700) return outlineVar.string(i32(b, 2), 22); return this.codePath(i32(b, 2)); } /** An outline code's value and its parents' as "A.B.C": a loop, stopping at a repeated or missing parent. */ private codePath(uid: number): string | null { if (uid === 0) return ''; const parts: string[] = []; const seen = new Set(); for (let id = uid; id !== 0 && !seen.has(id) && parts.length < 100; ) { seen.add(id); const item = this.byUid.get(id); if (!item || typeof item.value !== 'string') { if (id === uid) return null; break; } parts.unshift(item.value); id = item.parent; } return parts.join('.'); } /* ── Project 2000-2003 ──────────────────────────────────────────────── */ /** MPP9Reader.processFieldNameAliases: names one after another, by position. */ readAliases9(cls: 'task' | 'resource', data: Uint8Array | null): void { if (!data) return; const map = cls === 'task' ? MPP9_TASK_ALIASES : MPP9_RESOURCE_ALIASES; let offset = 0; for (let index = 0; offset < data.length; index++) { const alias = unicode(data, offset); const field = map.get(index); if (alias && field) this.setAlias(cls, field, alias); offset += (alias.length + 1) * 2; } } /** CustomFieldValueReader9.processCustomFieldValues: the value lists of ordinary fields. */ readValueLists9(data: Uint8Array | null): void { if (!data || data.length < 8) return; const length = i32(data, 0); const count = i32(data, 4); let offset = 8; for (let index = 0; index < count && offset < length && offset + 8 <= data.length; index++) { const f = fieldFor(i32(data, offset), false); const listOffset = i32(data, offset + 4); offset += 8; if (!f || listOffset < 0 || listOffset + 20 > data.length) continue; const dataOffset = i32(data, listOffset + 8) + listOffset; const endData = i32(data, listOffset + 12) + listOffset; const endDescription = i32(data, listOffset + 16) + listOffset; if (dataOffset < 0 || endData < dataOffset || endDescription < endData || endDescription > data.length) continue; const values = this.convert(f.def[1], data.subarray(dataOffset, endData)); const descriptions = this.convert('STRING', data.subarray(endData, endDescription)) as string[]; const target = this.getOrCreate(f.cls, f.def[0]); descriptions.forEach((d, i) => { const item: ValueItem = { uid: 0, guid: '', value: i < values.length ? values[i] : null, description: d, parent: 0 }; target.items.push(item); }); } } /** CustomFieldValueReader9.convertType. */ private convert(dataType: string, d: Uint8Array): Value[] { const out: Value[] = []; let i = 0; while (i < d.length) { switch (dataType) { case 'STRING': { const s = unicode(d, i); out.push(s); i += (s.length + 1) * 2; break; } case 'CURRENCY': out.push(f64(d, i) / 100); i += 8; break; case 'NUMERIC': out.push(f64(d, i)); i += 8; break; case 'DATE': out.push(timestamp(d, i)); i += 4; break; case 'DURATION': out.push(adjustedDuration(this.cal, i32(d, i), durationUnits(u16(d, i + 4), this.cal.defaultUnits))); i += 6; break; case 'BOOLEAN': out.push(u16(d, i) === 1); i += 2; break; default: i = d.length; } } return out; } /** CustomFieldValueReader9.processOutlineCodeValues: outline code value lists in TBkndOutlCode. */ readOutlineCodes9(fixedMeta: FixedMeta, fixed: FixedData, varMeta: VarMeta, varData: Var2Data): void { const byIndex = new Map(); for (let loop = 0; loop < fixedMeta.adjustedCount; loop++) { const d = fixed.item(loop); if (!d || d.length < 18) continue; const f = fieldFor(i32(d, 12), false); if (f && !f.def[0].includes('_FIELD_')) byIndex.set(u16(d, 0), { cls: f.cls, field: f.def[0] }); } for (const id of varMeta.ids()) { const f = byIndex.get(id); if (!f) continue; this.getOrCreate(f.cls, f.field).items.push({ uid: 0, guid: '', value: varData.string(id, 1) ?? '', description: varData.string(id, 2) ?? '', parent: 0 }); } } /** The fields that were renamed or have a value list, in Project's order (Text1, Text2, ... then Cost, Date...). */ list(): CustomField[] { const out: CustomField[] = []; for (const f of this.fields.values()) { if (!f.alias && !f.items.length) continue; const outline = f.field.startsWith('OUTLINE_CODE'); out.push({ cls: f.cls as 'task' | 'resource', field: f.field, alias: f.alias, values: f.items.map((i) => ({ value: outline && i.uid ? this.codePath(i.uid) ?? plainValue(f.field, i.value) : plainValue(f.field, i.value), description: i.description })), formula: '', }); } return sortFields(out); } } /** Fields in a stable, readable order: tasks then resources, then by kind and number. */ export function sortFields(list: CustomField[]): CustomField[] { const rank = (f: CustomField) => { const m = FIELD_RE.exec(f.field); return m ? [f.cls === 'task' ? 0 : 1, m[1], Number(m[2])] as const : [f.cls === 'task' ? 0 : 1, f.field, 0] as const; }; return list.sort((a, b) => { const x = rank(a), y = rank(b); return x[0] - y[0] || (x[1] < y[1] ? -1 : x[1] > y[1] ? 1 : 0) || x[2] - y[2]; }); } /** * A value as the page shows it in Task.extra: dates as "2026-03-02 08:00" * (wall clock), durations as "3d", flags as true/false, the rest as they are. * Value lists use the same form, so a task's value can be matched to its * description. */ export function plainValue(field: string, v: Value): string { if (v === null || v === undefined) return ''; if (typeof v === 'object') return `${Math.round(v.value * 100) / 100}${v.units}`; if (typeof v === 'number' && /DATE|START|FINISH|CREATED|DEADLINE/.test(field)) return new Date(v).toISOString().slice(0, 16).replace('T', ' '); if (typeof v === 'boolean') return v ? 'Yes' : 'No'; return String(v); } /* MPP9Reader.TASK_FIELD_ALIASES and RESOURCE_FIELD_ALIASES: position in the alias block -> field. */ type Run = [first: number, prefix: string, from: number, to: number, step?: number]; function runs(list: Run[]): Map { const m = new Map(); for (const [first, prefix, from, to, step = 1] of list) for (let n = from, i = first; n <= to; n++, i += step) m.set(i, `${prefix}${n}`); return m; } const MPP9_TASK_ALIASES = runs([ [118, 'TEXT', 1, 10], [128, 'START', 1, 10, 2], [129, 'FINISH', 1, 10, 2], [149, 'NUMBER', 1, 10], [159, 'DURATION', 1, 10, 2], [184, 'DATE', 1, 10], [194, 'TEXT', 11, 30], [214, 'NUMBER', 11, 20], [227, 'OUTLINE_CODE', 1, 10], [237, 'FLAG', 1, 20], [278, 'COST', 1, 10], ]); const MPP9_RESOURCE_ALIASES = runs([ [52, 'TEXT', 1, 30], [82, 'START', 1, 10], [92, 'FINISH', 1, 10], [102, 'NUMBER', 1, 20], [122, 'DURATION', 1, 10], [145, 'DATE', 1, 10], [155, 'OUTLINE_CODE', 1, 10], [165, 'FLAG', 10, 10], [166, 'FLAG', 1, 9], [175, 'FLAG', 11, 20], [207, 'COST', 1, 10], ]);