@precisa-saude/fhir 0.23.0 → 0.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/biomarkers.cjs +2 -2
- package/dist/biomarkers.js +1 -1
- package/dist/{chunk-HV77ZKP6.cjs → chunk-4EFTM357.cjs} +7 -7
- package/dist/{chunk-HV77ZKP6.cjs.map → chunk-4EFTM357.cjs.map} +1 -1
- package/dist/{chunk-AM2RCUUJ.cjs → chunk-EHMCWZO3.cjs} +15 -5
- package/dist/chunk-EHMCWZO3.cjs.map +1 -0
- package/dist/{chunk-RSKFZ5UB.cjs → chunk-L2LN2X6Y.cjs} +3 -3
- package/dist/{chunk-RSKFZ5UB.cjs.map → chunk-L2LN2X6Y.cjs.map} +1 -1
- package/dist/{chunk-GFT6V5GM.js → chunk-MLH7IZZE.js} +15 -5
- package/dist/chunk-MLH7IZZE.js.map +1 -0
- package/dist/{chunk-J3TAKR4S.js → chunk-ONPF2JAB.js} +2 -2
- package/dist/{chunk-NKA4JGNI.js → chunk-WEA7QFS5.js} +2 -2
- package/dist/cli.js +15 -5
- package/dist/{converter-D3h6dLHm.d.cts → converter-CO7q_s52.d.cts} +1 -1
- package/dist/{converter-BXidLD5t.d.ts → converter-x5Gcw-03.d.ts} +1 -1
- package/dist/converter.cjs +3 -3
- package/dist/converter.d.cts +2 -2
- package/dist/converter.d.ts +2 -2
- package/dist/converter.js +2 -2
- package/dist/{fhir-types-jTJayiwn.d.ts → fhir-types-Bmvac6o0.d.cts} +1 -1
- package/dist/{fhir-types-jTJayiwn.d.cts → fhir-types-Bmvac6o0.d.ts} +1 -1
- package/dist/importer.cjs +3 -3
- package/dist/importer.d.cts +1 -1
- package/dist/importer.d.ts +1 -1
- package/dist/importer.js +2 -2
- package/dist/index.cjs +31 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +46 -5
- package/dist/index.d.ts +46 -5
- package/dist/index.js +27 -3
- package/dist/index.js.map +1 -1
- package/dist/validators.d.cts +1 -1
- package/dist/validators.d.ts +1 -1
- package/package.json +1 -1
- package/dist/chunk-AM2RCUUJ.cjs.map +0 -1
- package/dist/chunk-GFT6V5GM.js.map +0 -1
- /package/dist/{chunk-J3TAKR4S.js.map → chunk-ONPF2JAB.js.map} +0 -0
- /package/dist/{chunk-NKA4JGNI.js.map → chunk-WEA7QFS5.js.map} +0 -0
package/dist/biomarkers.cjs
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
|
|
31
31
|
|
|
32
32
|
|
|
33
|
-
var
|
|
33
|
+
var _chunkEHMCWZO3cjs = require('./chunk-EHMCWZO3.cjs');
|
|
34
34
|
|
|
35
35
|
|
|
36
36
|
|
|
@@ -63,5 +63,5 @@ var _chunkAM2RCUUJcjs = require('./chunk-AM2RCUUJ.cjs');
|
|
|
63
63
|
|
|
64
64
|
|
|
65
65
|
|
|
66
|
-
exports.BIOMARKER_DEFINITIONS =
|
|
66
|
+
exports.BIOMARKER_DEFINITIONS = _chunkEHMCWZO3cjs.BIOMARKER_DEFINITIONS; exports.CAC_INDICATOR_CODES = _chunkEHMCWZO3cjs.CAC_INDICATOR_CODES; exports.DEXA_CATEGORIES = _chunkEHMCWZO3cjs.DEXA_CATEGORIES; exports.DEXA_INDICATOR_CODES = _chunkEHMCWZO3cjs.DEXA_INDICATOR_CODES; exports.codeToLoinc = _chunkEHMCWZO3cjs.codeToLoinc; exports.filterVisibleBiomarkers = _chunkEHMCWZO3cjs.filterVisibleBiomarkers; exports.findCodeByName = _chunkEHMCWZO3cjs.findCodeByName; exports.generateCacFullReference = _chunkEHMCWZO3cjs.generateCacFullReference; exports.generateDexaFullReference = _chunkEHMCWZO3cjs.generateDexaFullReference; exports.generateFilteredLLMReference = _chunkEHMCWZO3cjs.generateFilteredLLMReference; exports.generateLLMReference = _chunkEHMCWZO3cjs.generateLLMReference; exports.getAllCodes = _chunkEHMCWZO3cjs.getAllCodes; exports.getAllDefinitions = _chunkEHMCWZO3cjs.getAllDefinitions; exports.getAllLoincCodes = _chunkEHMCWZO3cjs.getAllLoincCodes; exports.getAllSearchPatterns = _chunkEHMCWZO3cjs.getAllSearchPatterns; exports.getBiomarkersByCategory = _chunkEHMCWZO3cjs.getBiomarkersByCategory; exports.getBiomarkersForCategories = _chunkEHMCWZO3cjs.getBiomarkersForCategories; exports.getDefinitionByCode = _chunkEHMCWZO3cjs.getDefinitionByCode; exports.getDefinitionByLoinc = _chunkEHMCWZO3cjs.getDefinitionByLoinc; exports.getDefinitionsBySex = _chunkEHMCWZO3cjs.getDefinitionsBySex; exports.getSexForCode = _chunkEHMCWZO3cjs.getSexForCode; exports.getVisibleDefinitions = _chunkEHMCWZO3cjs.getVisibleDefinitions; exports.isBiomarkerVisible = _chunkEHMCWZO3cjs.isBiomarkerVisible; exports.isCacDocument = _chunkEHMCWZO3cjs.isCacDocument; exports.isDexaDocument = _chunkEHMCWZO3cjs.isDexaDocument; exports.isValidCode = _chunkEHMCWZO3cjs.isValidCode; exports.isValidLoinc = _chunkEHMCWZO3cjs.isValidLoinc; exports.loincToCode = _chunkEHMCWZO3cjs.loincToCode; exports.normalizeCode = _chunkEHMCWZO3cjs.normalizeCode; exports.toBiomarkerTests = _chunkEHMCWZO3cjs.toBiomarkerTests; exports.validateLoincNameMatch = _chunkEHMCWZO3cjs.validateLoincNameMatch;
|
|
67
67
|
//# sourceMappingURL=biomarkers.cjs.map
|
package/dist/biomarkers.js
CHANGED
|
@@ -8,7 +8,7 @@ var _chunkOR67NJDZcjs = require('./chunk-OR67NJDZ.cjs');
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
var
|
|
11
|
+
var _chunkEHMCWZO3cjs = require('./chunk-EHMCWZO3.cjs');
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
var _chunk3ILBFLVQcjs = require('./chunk-3ILBFLVQ.cjs');
|
|
@@ -33,11 +33,11 @@ function resolveBiomarkerCode(observation) {
|
|
|
33
33
|
} else {
|
|
34
34
|
reason = "No code found in observation coding";
|
|
35
35
|
}
|
|
36
|
-
const fromLoinc = loincCode ?
|
|
36
|
+
const fromLoinc = loincCode ? _chunkEHMCWZO3cjs.loincToCode.call(void 0, loincCode) : void 0;
|
|
37
37
|
if (fromLoinc) return { internalCode: fromLoinc, loincCode, reason };
|
|
38
|
-
if (declaredCode &&
|
|
39
|
-
const canonical =
|
|
40
|
-
return { internalCode: canonical, loincCode:
|
|
38
|
+
if (declaredCode && _chunkEHMCWZO3cjs.isValidCode.call(void 0, declaredCode)) {
|
|
39
|
+
const canonical = _chunkEHMCWZO3cjs.normalizeCode.call(void 0, declaredCode);
|
|
40
|
+
return { internalCode: canonical, loincCode: _chunkEHMCWZO3cjs.codeToLoinc.call(void 0, canonical), reason };
|
|
41
41
|
}
|
|
42
42
|
return { loincCode, reason };
|
|
43
43
|
}
|
|
@@ -74,7 +74,7 @@ function mapFHIRObservationToInternal(observation, index) {
|
|
|
74
74
|
skipped: { index, loincCode, reason, resourceType: "Observation" }
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
|
-
const definition =
|
|
77
|
+
const definition = _chunkEHMCWZO3cjs.getDefinitionByCode.call(void 0, internalCode);
|
|
78
78
|
let value;
|
|
79
79
|
let unit = "";
|
|
80
80
|
let isQualitative = false;
|
|
@@ -162,4 +162,4 @@ function processImportBundle(data) {
|
|
|
162
162
|
|
|
163
163
|
|
|
164
164
|
exports.MAX_OBSERVATIONS = MAX_OBSERVATIONS; exports.MAX_FILE_SIZE = MAX_FILE_SIZE; exports.extractObservationsFromBundle = extractObservationsFromBundle; exports.mapFHIRObservationToInternal = mapFHIRObservationToInternal; exports.processImportBundle = processImportBundle;
|
|
165
|
-
//# sourceMappingURL=chunk-
|
|
165
|
+
//# sourceMappingURL=chunk-4EFTM357.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-HV77ZKP6.cjs","../src/importer.ts"],"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,EAAA;AACV,IAAA;AACwB,MAAA;AAC/B,IAAA;AACF,EAAA;AAEmB,EAAA;AAGf,EAAA;AACO,EAAA;AACS,EAAA;AAEW,EAAA;AACK,IAAA;AACD,IAAA;AACC,EAAA;AACd,IAAA;AACJ,IAAA;AACX,EAAA;AACE,IAAA;AACI,MAAA;AACP,QAAA;AACA,QAAA;AACQ,QAAA;AACM,QAAA;AAChB,MAAA;AACF,IAAA;AACF,EAAA;AAGmC,EAAA;AACd,EAAA;AACZ,IAAA;AACI,MAAA;AACP,QAAA;AACA,QAAA;AACQ,QAAA;AACM,QAAA;AAChB,MAAA;AACF,IAAA;AACF,EAAA;AAGI,EAAA;AACA,EAAA;AACiC,EAAA;AACR,IAAA;AACA,IAAA;AAC7B,EAAA;AAEsC,EAAA;AACrB,IAAA;AAEK,IAAA;AACpB,IAAA;AAC6B,IAAA;AAC7B,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACkC,IAAA;AAClC,IAAA;AACF,EAAA;AAE+B,EAAA;AACjC;AAKqE;AAE1C,EAAA;AACQ,EAAA;AACxB,IAAA;AACG,MAAA;AACG,MAAA;AACD,MAAA;AACM,MAAA;AAClB,IAAA;AACF,EAAA;AAEe,EAAA;AAGmB,EAAA;AAGO,EAAA;AACK,EAAA;AAEb,EAAA;AAChB,IAAA;AAEc,IAAA;AACK,MAAA;AAC3B,IAAA;AACyB,MAAA;AAChC,IAAA;AACF,EAAA;AAEO,EAAA;AACI,IAAA;AACT,IAAA;AACS,IAAA;AACoB,IAAA;AAC/B,EAAA;AACF;ADnIuC;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-HV77ZKP6.cjs","sourcesContent":[null,"/**\n * FHIR Importer\n *\n * Parses FHIR R4 Bundles and extracts Observation resources with known LOINC codes,\n * mapping them to internal biomarker codes for storage as lab results.\n */\n\nimport {\n codeToLoinc,\n getDefinitionByCode,\n isValidCode,\n loincToCode,\n normalizeCode,\n} from './biomarkers';\nimport { BIOMARKER_CODE_SYSTEM, LOINC_SYSTEM } from './code-systems';\nimport type { FHIRBundle, FHIRObservation } from './fhir-types';\nimport { validateFHIRImportBundle } from './validators';\n\nexport interface ImportedObservation {\n biomarkerCode: string;\n biomarkerName: string;\n collectionDate: string;\n flag: 'H' | 'L' | '';\n isQualitative: boolean;\n /** Ausente nos biomarcadores sem LOINC publicado, como composição corporal. */\n loincCode?: string;\n referenceMax?: number;\n referenceMin?: number;\n unit: string;\n value: number | string;\n}\n\nexport interface SkippedEntry {\n index: number;\n loincCode?: string;\n reason: string;\n resourceType?: string;\n}\n\nexport interface ImportError {\n details: string;\n field: string;\n}\n\nexport interface FHIRImportResult {\n errors: ImportError[];\n imported: ImportedObservation[];\n skipped: SkippedEntry[];\n totalProcessed: number;\n}\n\n/**\n * Limites de importação.\n *\n * Uma Observation exportada ocupa cerca de 1,25KB em JSON compacto e 2,75KB\n * quando o arquivo vem indentado, medido sobre um histórico real de 998\n * Observations em 61 laudos. Nesse tamanho, 5000 Observations dão 6,0MB\n * compactos ou 13,1MB indentados, e por isso o teto de arquivo é 15MB: cobre\n * as duas formas com folga.\n *\n * Na densidade desse mesmo histórico (16 Observations por laudo), 5000\n * equivalem a cerca de 300 laudos.\n */\nconst MAX_OBSERVATIONS = 5000;\nconst MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB\n\n/**\n * Resolve o código interno do biomarcador a partir do `code.coding`.\n *\n * LOINC primeiro, que é o vocabulário que arquivos de terceiros usam. Quando\n * não resolve, cai para o coding de códigos internos, presente nos arquivos\n * exportados pela própria plataforma.\n *\n * O fallback cobre dois casos: biomarcadores sem LOINC publicado (composição\n * corporal, densidade óssea, escore de cálcio) e arquivos antigos, exportados\n * quando esses biomarcadores saíam com o placeholder `99999-9`, que não\n * resolve para nada.\n */\nfunction resolveBiomarkerCode(observation: FHIRObservation): {\n internalCode?: string;\n loincCode?: string;\n reason: string;\n} {\n const coding = observation.code?.coding ?? [];\n const loincCode = coding.find((c) => c.system === LOINC_SYSTEM)?.code;\n const declaredCode = coding.find((c) => c.system === BIOMARKER_CODE_SYSTEM)?.code;\n\n const seenCodes = [\n ...(loincCode ? [`LOINC ${loincCode}`] : []),\n ...(declaredCode ? [`biomarker code ${declaredCode}`] : []),\n ];\n\n // Três motivos distintos de descarte, que antes se confundiam num só. Sem\n // essa separação, um arquivo em SNOMED relatava \"nenhum código encontrado\",\n // sugerindo `coding` vazio quando na verdade o código existia e estava num\n // system que não tratamos. Para importação de terceiros, é a diferença entre\n // um diagnóstico acionável e um enigma.\n let reason: string;\n if (seenCodes.length > 0) {\n reason = `Unknown code: ${seenCodes.join(', ')}`;\n } else if (coding.length > 0) {\n const systems = [...new Set(coding.map((c) => c.system ?? '(sem system)'))];\n reason = `No code in a supported system (found: ${systems.join(', ')})`;\n } else {\n reason = 'No code found in observation coding';\n }\n\n const fromLoinc = loincCode ? loincToCode(loincCode) : undefined;\n if (fromLoinc) return { internalCode: fromLoinc, loincCode, reason };\n\n if (declaredCode && isValidCode(declaredCode)) {\n // `isValidCode` aceita alias, mas alias não serve como código armazenado:\n // 49 definições têm um, e tanto `codeToLoinc` quanto as faixas de\n // referência são indexadas só pelo canônico. Sem normalizar, `VLDL_Cholesterol`\n // entraria no lugar de `VLDL` e perderia o LOINC 13458-5 que ele tem.\n // Importar um Bundle é fronteira de dados, que é onde `normalizeCode` deve\n // ser aplicado.\n const canonical = normalizeCode(declaredCode);\n\n // `codeToLoinc` devolve undefined para quem não tem LOINC, que é o caso\n // esperado aqui. O campo fica de fora em vez de receber um valor inventado.\n return { internalCode: canonical, loincCode: codeToLoinc(canonical), reason };\n }\n\n return { loincCode, reason };\n}\n\n/**\n * Extract interpretation flag from Observation\n */\nfunction extractFlag(observation: FHIRObservation): 'H' | 'L' | '' {\n const code = observation.interpretation?.[0]?.coding?.[0]?.code;\n if (code === 'H' || code === 'HH') return 'H';\n if (code === 'L' || code === 'LL') return 'L';\n return '';\n}\n\n/**\n * Extract Observation resources from a FHIR Bundle\n */\nexport function extractObservationsFromBundle(bundle: FHIRBundle): {\n observations: FHIRObservation[];\n skipped: SkippedEntry[];\n} {\n const observations: FHIRObservation[] = [];\n const skipped: SkippedEntry[] = [];\n\n for (let i = 0; i < bundle.entry.length; i++) {\n const entry = bundle.entry[i]!;\n if (!entry.resource) {\n skipped.push({ index: i, reason: 'Entry has no resource' });\n continue;\n }\n\n if (entry.resource.resourceType !== 'Observation') {\n // Non-observation resources are silently skipped (Patient, DiagnosticReport, etc.)\n continue;\n }\n\n if (observations.length >= MAX_OBSERVATIONS) {\n skipped.push({ index: i, reason: `Maximum of ${MAX_OBSERVATIONS} observations exceeded` });\n continue;\n }\n\n observations.push(entry.resource as FHIRObservation);\n }\n\n return { observations, skipped };\n}\n\n/**\n * Map a FHIR Observation to internal format using LOINC→biomarker code lookup\n */\nexport function mapFHIRObservationToInternal(\n observation: FHIRObservation,\n index: number,\n): { observation: ImportedObservation } | { skipped: SkippedEntry } {\n const { internalCode, loincCode, reason } = resolveBiomarkerCode(observation);\n\n if (!internalCode) {\n return {\n skipped: { index, loincCode, reason, resourceType: 'Observation' },\n };\n }\n\n const definition = getDefinitionByCode(internalCode);\n\n // Extract value\n let value: number | string;\n let unit = '';\n let isQualitative = false;\n\n if (observation.valueQuantity?.value !== undefined) {\n value = observation.valueQuantity.value;\n unit = observation.valueQuantity.unit || observation.valueQuantity.code || '';\n } else if (observation.valueString) {\n value = observation.valueString;\n isQualitative = true;\n } else {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no value (valueQuantity or valueString)',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract collection date (effectiveDateTime or effectivePeriod.start)\n const collectionDate = observation.effectiveDateTime || observation.effectivePeriod?.start || '';\n if (!collectionDate) {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no effectiveDateTime or effectivePeriod.start',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract reference ranges\n let referenceMin: number | undefined;\n let referenceMax: number | undefined;\n if (observation.referenceRange?.[0]) {\n referenceMin = observation.referenceRange[0].low?.value;\n referenceMax = observation.referenceRange[0].high?.value;\n }\n\n const imported: ImportedObservation = {\n biomarkerCode: internalCode,\n biomarkerName:\n definition?.names.pt[0] || definition?.names.en[0] || observation.code.text || internalCode,\n collectionDate,\n flag: extractFlag(observation),\n isQualitative,\n loincCode,\n referenceMax,\n referenceMin,\n unit: unit || definition?.unit || '',\n value,\n };\n\n return { observation: imported };\n}\n\n/**\n * Process a complete FHIR Bundle for import\n */\nexport function processImportBundle(data: unknown): FHIRImportResult {\n // Structural validation\n const validationErrors = validateFHIRImportBundle(data);\n if (validationErrors.length > 0) {\n return {\n errors: validationErrors,\n imported: [],\n skipped: [],\n totalProcessed: 0,\n };\n }\n\n const bundle = data as FHIRBundle;\n\n // Extract observations\n const { observations, skipped } = extractObservationsFromBundle(bundle);\n\n // Map each observation to internal format\n const imported: ImportedObservation[] = [];\n const allSkipped: SkippedEntry[] = [...skipped];\n\n for (let i = 0; i < observations.length; i++) {\n const result = mapFHIRObservationToInternal(observations[i]!, i);\n\n if ('observation' in result) {\n imported.push(result.observation);\n } else {\n allSkipped.push(result.skipped);\n }\n }\n\n return {\n errors: [],\n imported,\n skipped: allSkipped,\n totalProcessed: observations.length,\n };\n}\n\nexport { MAX_FILE_SIZE, MAX_OBSERVATIONS };\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-4EFTM357.cjs","../src/importer.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACgDA,IAAM,iBAAA,EAAmB,GAAA;AACzB,IAAM,cAAA,EAAgB,GAAA,EAAK,KAAA,EAAO,IAAA;AAclC,SAAS,oBAAA,CAAqB,WAAA,EAI5B;AACA,EAAA,MAAM,OAAA,mCAAS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AGmC,EAAA;AACd,EAAA;AACZ,IAAA;AACI,MAAA;AACP,QAAA;AACA,QAAA;AACQ,QAAA;AACM,QAAA;AAChB,MAAA;AACF,IAAA;AACF,EAAA;AAGI,EAAA;AACA,EAAA;AACiC,EAAA;AACR,IAAA;AACA,IAAA;AAC7B,EAAA;AAEsC,EAAA;AACrB,IAAA;AAEK,IAAA;AACpB,IAAA;AAC6B,IAAA;AAC7B,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACkC,IAAA;AAClC,IAAA;AACF,EAAA;AAE+B,EAAA;AACjC;AAKqE;AAE1C,EAAA;AACQ,EAAA;AACxB,IAAA;AACG,MAAA;AACG,MAAA;AACD,MAAA;AACM,MAAA;AAClB,IAAA;AACF,EAAA;AAEe,EAAA;AAGmB,EAAA;AAGO,EAAA;AACK,EAAA;AAEb,EAAA;AAChB,IAAA;AAEc,IAAA;AACK,MAAA;AAC3B,IAAA;AACyB,MAAA;AAChC,IAAA;AACF,EAAA;AAEO,EAAA;AACI,IAAA;AACT,IAAA;AACS,IAAA;AACoB,IAAA;AAC/B,EAAA;AACF;ADnIuC;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-4EFTM357.cjs","sourcesContent":[null,"/**\n * FHIR Importer\n *\n * Parses FHIR R4 Bundles and extracts Observation resources with known LOINC codes,\n * mapping them to internal biomarker codes for storage as lab results.\n */\n\nimport {\n codeToLoinc,\n getDefinitionByCode,\n isValidCode,\n loincToCode,\n normalizeCode,\n} from './biomarkers';\nimport { BIOMARKER_CODE_SYSTEM, LOINC_SYSTEM } from './code-systems';\nimport type { FHIRBundle, FHIRObservation } from './fhir-types';\nimport { validateFHIRImportBundle } from './validators';\n\nexport interface ImportedObservation {\n biomarkerCode: string;\n biomarkerName: string;\n collectionDate: string;\n flag: 'H' | 'L' | '';\n isQualitative: boolean;\n /** Ausente nos biomarcadores sem LOINC publicado, como composição corporal. */\n loincCode?: string;\n referenceMax?: number;\n referenceMin?: number;\n unit: string;\n value: number | string;\n}\n\nexport interface SkippedEntry {\n index: number;\n loincCode?: string;\n reason: string;\n resourceType?: string;\n}\n\nexport interface ImportError {\n details: string;\n field: string;\n}\n\nexport interface FHIRImportResult {\n errors: ImportError[];\n imported: ImportedObservation[];\n skipped: SkippedEntry[];\n totalProcessed: number;\n}\n\n/**\n * Limites de importação.\n *\n * Uma Observation exportada ocupa cerca de 1,25KB em JSON compacto e 2,75KB\n * quando o arquivo vem indentado, medido sobre um histórico real de 998\n * Observations em 61 laudos. Nesse tamanho, 5000 Observations dão 6,0MB\n * compactos ou 13,1MB indentados, e por isso o teto de arquivo é 15MB: cobre\n * as duas formas com folga.\n *\n * Na densidade desse mesmo histórico (16 Observations por laudo), 5000\n * equivalem a cerca de 300 laudos.\n */\nconst MAX_OBSERVATIONS = 5000;\nconst MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB\n\n/**\n * Resolve o código interno do biomarcador a partir do `code.coding`.\n *\n * LOINC primeiro, que é o vocabulário que arquivos de terceiros usam. Quando\n * não resolve, cai para o coding de códigos internos, presente nos arquivos\n * exportados pela própria plataforma.\n *\n * O fallback cobre dois casos: biomarcadores sem LOINC publicado (composição\n * corporal, densidade óssea, escore de cálcio) e arquivos antigos, exportados\n * quando esses biomarcadores saíam com o placeholder `99999-9`, que não\n * resolve para nada.\n */\nfunction resolveBiomarkerCode(observation: FHIRObservation): {\n internalCode?: string;\n loincCode?: string;\n reason: string;\n} {\n const coding = observation.code?.coding ?? [];\n const loincCode = coding.find((c) => c.system === LOINC_SYSTEM)?.code;\n const declaredCode = coding.find((c) => c.system === BIOMARKER_CODE_SYSTEM)?.code;\n\n const seenCodes = [\n ...(loincCode ? [`LOINC ${loincCode}`] : []),\n ...(declaredCode ? [`biomarker code ${declaredCode}`] : []),\n ];\n\n // Três motivos distintos de descarte, que antes se confundiam num só. Sem\n // essa separação, um arquivo em SNOMED relatava \"nenhum código encontrado\",\n // sugerindo `coding` vazio quando na verdade o código existia e estava num\n // system que não tratamos. Para importação de terceiros, é a diferença entre\n // um diagnóstico acionável e um enigma.\n let reason: string;\n if (seenCodes.length > 0) {\n reason = `Unknown code: ${seenCodes.join(', ')}`;\n } else if (coding.length > 0) {\n const systems = [...new Set(coding.map((c) => c.system ?? '(sem system)'))];\n reason = `No code in a supported system (found: ${systems.join(', ')})`;\n } else {\n reason = 'No code found in observation coding';\n }\n\n const fromLoinc = loincCode ? loincToCode(loincCode) : undefined;\n if (fromLoinc) return { internalCode: fromLoinc, loincCode, reason };\n\n if (declaredCode && isValidCode(declaredCode)) {\n // `isValidCode` aceita alias, mas alias não serve como código armazenado:\n // 49 definições têm um, e tanto `codeToLoinc` quanto as faixas de\n // referência são indexadas só pelo canônico. Sem normalizar, `VLDL_Cholesterol`\n // entraria no lugar de `VLDL` e perderia o LOINC 13458-5 que ele tem.\n // Importar um Bundle é fronteira de dados, que é onde `normalizeCode` deve\n // ser aplicado.\n const canonical = normalizeCode(declaredCode);\n\n // `codeToLoinc` devolve undefined para quem não tem LOINC, que é o caso\n // esperado aqui. O campo fica de fora em vez de receber um valor inventado.\n return { internalCode: canonical, loincCode: codeToLoinc(canonical), reason };\n }\n\n return { loincCode, reason };\n}\n\n/**\n * Extract interpretation flag from Observation\n */\nfunction extractFlag(observation: FHIRObservation): 'H' | 'L' | '' {\n const code = observation.interpretation?.[0]?.coding?.[0]?.code;\n if (code === 'H' || code === 'HH') return 'H';\n if (code === 'L' || code === 'LL') return 'L';\n return '';\n}\n\n/**\n * Extract Observation resources from a FHIR Bundle\n */\nexport function extractObservationsFromBundle(bundle: FHIRBundle): {\n observations: FHIRObservation[];\n skipped: SkippedEntry[];\n} {\n const observations: FHIRObservation[] = [];\n const skipped: SkippedEntry[] = [];\n\n for (let i = 0; i < bundle.entry.length; i++) {\n const entry = bundle.entry[i]!;\n if (!entry.resource) {\n skipped.push({ index: i, reason: 'Entry has no resource' });\n continue;\n }\n\n if (entry.resource.resourceType !== 'Observation') {\n // Non-observation resources are silently skipped (Patient, DiagnosticReport, etc.)\n continue;\n }\n\n if (observations.length >= MAX_OBSERVATIONS) {\n skipped.push({ index: i, reason: `Maximum of ${MAX_OBSERVATIONS} observations exceeded` });\n continue;\n }\n\n observations.push(entry.resource as FHIRObservation);\n }\n\n return { observations, skipped };\n}\n\n/**\n * Map a FHIR Observation to internal format using LOINC→biomarker code lookup\n */\nexport function mapFHIRObservationToInternal(\n observation: FHIRObservation,\n index: number,\n): { observation: ImportedObservation } | { skipped: SkippedEntry } {\n const { internalCode, loincCode, reason } = resolveBiomarkerCode(observation);\n\n if (!internalCode) {\n return {\n skipped: { index, loincCode, reason, resourceType: 'Observation' },\n };\n }\n\n const definition = getDefinitionByCode(internalCode);\n\n // Extract value\n let value: number | string;\n let unit = '';\n let isQualitative = false;\n\n if (observation.valueQuantity?.value !== undefined) {\n value = observation.valueQuantity.value;\n unit = observation.valueQuantity.unit || observation.valueQuantity.code || '';\n } else if (observation.valueString) {\n value = observation.valueString;\n isQualitative = true;\n } else {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no value (valueQuantity or valueString)',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract collection date (effectiveDateTime or effectivePeriod.start)\n const collectionDate = observation.effectiveDateTime || observation.effectivePeriod?.start || '';\n if (!collectionDate) {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no effectiveDateTime or effectivePeriod.start',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract reference ranges\n let referenceMin: number | undefined;\n let referenceMax: number | undefined;\n if (observation.referenceRange?.[0]) {\n referenceMin = observation.referenceRange[0].low?.value;\n referenceMax = observation.referenceRange[0].high?.value;\n }\n\n const imported: ImportedObservation = {\n biomarkerCode: internalCode,\n biomarkerName:\n definition?.names.pt[0] || definition?.names.en[0] || observation.code.text || internalCode,\n collectionDate,\n flag: extractFlag(observation),\n isQualitative,\n loincCode,\n referenceMax,\n referenceMin,\n unit: unit || definition?.unit || '',\n value,\n };\n\n return { observation: imported };\n}\n\n/**\n * Process a complete FHIR Bundle for import\n */\nexport function processImportBundle(data: unknown): FHIRImportResult {\n // Structural validation\n const validationErrors = validateFHIRImportBundle(data);\n if (validationErrors.length > 0) {\n return {\n errors: validationErrors,\n imported: [],\n skipped: [],\n totalProcessed: 0,\n };\n }\n\n const bundle = data as FHIRBundle;\n\n // Extract observations\n const { observations, skipped } = extractObservationsFromBundle(bundle);\n\n // Map each observation to internal format\n const imported: ImportedObservation[] = [];\n const allSkipped: SkippedEntry[] = [...skipped];\n\n for (let i = 0; i < observations.length; i++) {\n const result = mapFHIRObservationToInternal(observations[i]!, i);\n\n if ('observation' in result) {\n imported.push(result.observation);\n } else {\n allSkipped.push(result.skipped);\n }\n }\n\n return {\n errors: [],\n imported,\n skipped: allSkipped,\n totalProcessed: observations.length,\n };\n}\n\nexport { MAX_FILE_SIZE, MAX_OBSERVATIONS };\n"]}
|
|
@@ -2125,9 +2125,12 @@ var BIOMARKER_DEFINITIONS = [
|
|
|
2125
2125
|
"VATVolume",
|
|
2126
2126
|
"Visceral Adipose Tissue Volume",
|
|
2127
2127
|
"VAT",
|
|
2128
|
+
// "Visceral Fat" e "Gordura Visceral" nus não dizem qual das duas
|
|
2129
|
+
// medidas o laudo traz, então também estão no `VisceralFatLevel`. O
|
|
2130
|
+
// pré-scan devolve os dois candidatos e o modelo decide pela unidade e
|
|
2131
|
+
// pela ordem de grandeza, que é o que separa um índice 9 de 120 cm³.
|
|
2128
2132
|
"Visceral Fat",
|
|
2129
|
-
"Visceral Volume"
|
|
2130
|
-
"Volume"
|
|
2133
|
+
"Visceral Volume"
|
|
2131
2134
|
],
|
|
2132
2135
|
pt: [
|
|
2133
2136
|
"Volume de Gordura Visceral",
|
|
@@ -2376,8 +2379,15 @@ var BIOMARKER_DEFINITIONS = [
|
|
|
2376
2379
|
category: "composicao-corporal",
|
|
2377
2380
|
code: "VisceralFatLevel",
|
|
2378
2381
|
names: {
|
|
2379
|
-
en: ["Visceral Fat Level", "Visceral Fat Index", "VFL"],
|
|
2380
|
-
pt: [
|
|
2382
|
+
en: ["Visceral Fat Level", "Visceral Fat Index", "VFL", "Visceral Fat"],
|
|
2383
|
+
pt: [
|
|
2384
|
+
"N\xEDvel de Gordura Visceral",
|
|
2385
|
+
"\xCDndice de Gordura Visceral",
|
|
2386
|
+
"Gordura Visceral N\xEDvel",
|
|
2387
|
+
// Termo nu, compartilhado com o `VATVolume` de propósito. Ver o
|
|
2388
|
+
// comentário lá.
|
|
2389
|
+
"Gordura Visceral"
|
|
2390
|
+
]
|
|
2381
2391
|
},
|
|
2382
2392
|
unit: ""
|
|
2383
2393
|
},
|
|
@@ -3337,4 +3347,4 @@ function getBiomarkersForCategories(categories, options) {
|
|
|
3337
3347
|
|
|
3338
3348
|
|
|
3339
3349
|
exports.BIOMARKER_DEFINITIONS = BIOMARKER_DEFINITIONS; exports.loincToCode = loincToCode; exports.codeToLoinc = codeToLoinc; exports.isValidLoinc = isValidLoinc; exports.isValidCode = isValidCode; exports.normalizeCode = normalizeCode; exports.getSexForCode = getSexForCode; exports.getDefinitionsBySex = getDefinitionsBySex; exports.getDefinitionByCode = getDefinitionByCode; exports.getDefinitionByLoinc = getDefinitionByLoinc; exports.getAllDefinitions = getAllDefinitions; exports.getVisibleDefinitions = getVisibleDefinitions; exports.getAllCodes = getAllCodes; exports.getAllLoincCodes = getAllLoincCodes; exports.generateLLMReference = generateLLMReference; exports.toBiomarkerTests = toBiomarkerTests; exports.getAllSearchPatterns = getAllSearchPatterns; exports.generateFilteredLLMReference = generateFilteredLLMReference; exports.DEXA_INDICATOR_CODES = DEXA_INDICATOR_CODES; exports.DEXA_CATEGORIES = DEXA_CATEGORIES; exports.generateDexaFullReference = generateDexaFullReference; exports.isDexaDocument = isDexaDocument; exports.CAC_INDICATOR_CODES = CAC_INDICATOR_CODES; exports.generateCacFullReference = generateCacFullReference; exports.isCacDocument = isCacDocument; exports.findCodeByName = findCodeByName; exports.validateLoincNameMatch = validateLoincNameMatch; exports.isBiomarkerVisible = isBiomarkerVisible; exports.filterVisibleBiomarkers = filterVisibleBiomarkers; exports.getBiomarkersByCategory = getBiomarkersByCategory; exports.getBiomarkersForCategories = getBiomarkersForCategories;
|
|
3340
|
-
//# sourceMappingURL=chunk-
|
|
3350
|
+
//# sourceMappingURL=chunk-EHMCWZO3.cjs.map
|