From f3958cb76e4cc94cf6b23fc8ce4315f83d7389b8 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 11:58:18 -0600 Subject: [PATCH 01/23] fix(search): handle repeated query params and non-string _search JSON --- tests/tx/fix-iss01-search-params.test.js | 62 +++++++++++++++++ translations/Messages.properties | 2 + tx/workers/search.js | 89 +++++++++++++++++------- 3 files changed, 126 insertions(+), 27 deletions(-) create mode 100644 tests/tx/fix-iss01-search-params.test.js diff --git a/tests/tx/fix-iss01-search-params.test.js b/tests/tx/fix-iss01-search-params.test.js new file mode 100644 index 00000000..01352b26 --- /dev/null +++ b/tests/tx/fix-iss01-search-params.test.js @@ -0,0 +1,62 @@ +/** + * Regression test for ISS-01: search endpoints with repeated query params and non-string _search JSON. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-01: search endpoints handle repeated query params and non-string _search JSON', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test('GET /CodeSystem?status=active&status=draft returns 200 (AND-ed) instead of 500', async () => { + const res = await request(app).get(`${R5}/CodeSystem?status=active&status=draft`).set('Accept', 'application/fhir+json'); + expect(res.status).toBe(200); + expect(res.body.resourceType).toBe('Bundle'); + expect(res.body.total).toBe(0); + }); + + test('GET /ValueSet and /ConceptMap with repeated status return 200 instead of 500', async () => { + for (const rt of ['ValueSet', 'ConceptMap']) { + const res = await request(app).get(`${R5}/${rt}?status=active&status=draft&_count=1`).set('Accept', 'application/fhir+json'); + expect(res.status).toBe(200); + expect(res.body.resourceType).toBe('Bundle'); + } + }); + + test('POST /ConceptMap/_search with numeric JSON values returns 200 instead of 500', async () => { + const res = await request(app).post(`${R5}/ConceptMap/_search`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ _count: 3, version: 4 }); + expect(res.status).toBe(200); + expect(res.body.resourceType).toBe('Bundle'); + }); + + test('POST /ConceptMap/_search with non-primitive object value returns 400 OperationOutcome', async () => { + const res = await request(app).post(`${R5}/ConceptMap/_search`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ version: { bad: true } }); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('invalid'); + }); + + test('Bundle.link.url preserves repeated query params without comma-joining', async () => { + const res = await request(app).get(`${R5}/ValueSet?source=none&status=active&status=draft&_count=1`).set('Accept', 'application/fhir+json'); + expect(res.status).toBe(200); + const selfUrl = res.body.link.find(l => l.relation === 'self').url; + expect(selfUrl).toContain('status=active&status=draft'); + expect(selfUrl).not.toContain('active%2Cdraft'); + }); +}); diff --git a/translations/Messages.properties b/translations/Messages.properties index 7ba20ffa..ae08935c 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -1511,6 +1511,8 @@ TX_PARAM_INVALID_VALUE = The parameter ''{0}'' has the value {1} as a {2}, which TX_PARAM_WRONG_TYPE = The parameter ''{0}'' has {1}, but its value must be {2} TX_PARAM_VERSION_RULE_INVALID = The value ''{1}'' of the parameter ''{0}'' isn''t valid: it must be the url of a {2}, then ''|'', then the version TX_PARAM_CACHE_ID_WITHDRAWN = The parameter ''cache-id'' is no longer supported: start a cache with $cache-control (mode=start), and send the cache-id it returns in the HTTP header ''X-Cache-Id'' +TX_SEARCH_PARAMS_NOT_OBJECT = Search parameters must be an object +TX_SEARCH_PARAM_NOT_PRIMITIVE = Search parameter ''{0}'' must have a primitive value FILTER_VALUE_UNKNOWN_CODE = The filter value ''{0}'' is not a code in {1} XHTML_CONTROL_NO_SOURCE = The xhtml node at ''{0}'' does not have a class attribute to indicate its source (boilerplate, generated, or original) and this is required by the profile {1} XHTML_XHTML_MIXED_LANG = The xhtml has some language sections ({0}), and also has content that is not in a language section diff --git a/tx/workers/search.js b/tx/workers/search.js index a7d9a0cb..b4901621 100644 --- a/tx/workers/search.js +++ b/tx/workers/search.js @@ -11,7 +11,7 @@ const { VersionUtilities } = require("../../library/fhir/version-utilities"); const {debugLog} = require("../operation-context"); const {acceptsHtml} = require("../tx-html"); -const { buildOperationOutcome } = require('../library/operation-outcome'); +const { Issue, OperationOutcome, buildOperationOutcome } = require('../library/operation-outcome'); class SearchWorker extends TerminologyWorker { /** * @param {OperationContext} opContext - Operation context @@ -69,10 +69,17 @@ class SearchWorker extends TerminologyWorker { this.log.debug(`Search ${resourceType} with params:`, params); try { + if (!params || typeof params !== 'object' || Array.isArray(params)) { + return res.status(400).json(buildOperationOutcome('error', 'invalid', + this.i18n.translate('TX_SEARCH_PARAMS_NOT_OBJECT', this.opContext.langs), 'invalid-data')); + } + // Parse pagination parameters - const offset = Math.max(0, parseInt(params._offset) || 0); - const summary = params._summary || 'false'; - const totalMode = params._total || 'accurate'; + const firstVal = (v) => (Array.isArray(v) ? v[0] : v); + const offsetRaw = firstVal(params._offset); + const offset = Math.max(0, parseInt(offsetRaw) || 0); + const summary = firstVal(params._summary) || 'false'; + const totalMode = firstVal(params._total) || 'accurate'; // Determine elements based on _summary parameter let elements; @@ -86,9 +93,11 @@ class SearchWorker extends TerminologyWorker { case 'data': elements = null; // no filter for terminology break; - default: - elements = params._elements ? decodeURIComponent(params._elements).split(',').map(e => e.trim()) : null; + default: { + const rawElements = Array.isArray(params._elements) ? params._elements.join(',') : params._elements; + elements = rawElements ? decodeURIComponent(String(rawElements)).split(',').map(e => e.trim()) : null; break; + } } // Default page size depends on the return format: browsers get small pages @@ -96,8 +105,9 @@ class SearchWorker extends TerminologyWorker { // the data, and small pages make crawlers (e.g. the tx registry) painfully // slow. An explicit _count always wins, subject to the caps. const defaultCount = acceptsHtml(req) ? SearchWorker.HTML_PAGE_SIZE : 1000; - const count = summary === 'count' ? 0 : Math.min(elements ? 2000 : 200, params._count && Utilities.isInteger(params._count) ? parseInt(params._count) : defaultCount); - const sort = params._sort || "id"; + const countRaw = firstVal(params._count); + const count = summary === 'count' ? 0 : Math.min(elements ? 2000 : 200, countRaw !== undefined && countRaw !== null && Utilities.isInteger(String(countRaw)) ? parseInt(countRaw) : defaultCount); + const sort = firstVal(params._sort) || "id"; // A person using the HTML search form gets a partial match on url (e.g. an OID); an API // client gets the match it always has, because clients look resources up by url and @@ -148,6 +158,11 @@ class SearchWorker extends TerminologyWorker { this.log.error(error); debugLog(error); req.logInfo = "error "+(error.msgId || error.className); + if (error instanceof Issue) { + const oo = new OperationOutcome(); + oo.addIssue(error); + return res.status(error.statusCode || 500).json(oo.jsonObj); + } return res.status(500).json(buildOperationOutcome('error', 'exception', error.message)); } } @@ -158,14 +173,14 @@ class SearchWorker extends TerminologyWorker { searchCodeSystems(params, partialUrl = false) { const matches = []; - // Extract search parameters (excluding special params) - const searchParams = {}; - for (const { name, value } of this.searchParamsFor(params, partialUrl)) { - searchParams[name] = name == 'url' || name == 'url:below' || name == 'version' ? value : value.toLowerCase(); - } + // Extract search parameters (excluding special params), preserving repeated params as AND criteria + const searchParams = this.searchParamsFor(params, partialUrl).map(({ name, value }) => ({ + name, + value: name == 'url' || name == 'url:below' || name == 'version' ? value : value.toLowerCase() + })); // If no search params, return all - const hasSearchParams = Object.keys(searchParams).length > 0; + const hasSearchParams = searchParams.length > 0; this.searchCodeSystemResources(searchParams, hasSearchParams, matches); this.searchCodeSystemProviders(searchParams, hasSearchParams, matches); @@ -178,21 +193,33 @@ class SearchWorker extends TerminologyWorker { * an exact match, url:below a left match (the url starts with the value, case-sensitive) and * url:contains the url contains the value, without regard to case. With partialUrl (the HTML * search form), url becomes url:contains, and the value is trimmed (a form value often picks - * up a space) + * up a space). Repeated query parameters expand into separate AND-ed criteria; non-primitive + * values in POST /_search JSON are rejected with 400. * @param {Object} params - the request parameters * @param {boolean} partialUrl * @returns {Array<{name: string, value: string}>} */ searchParamsFor(params, partialUrl) { const searchParams = []; - for (const [key, value] of Object.entries(params)) { - if (!key.startsWith('_') && value && SearchWorker.ALLOWED_PARAMS.includes(key)) { - if (key === 'url' && partialUrl && typeof value === 'string') { - if (value.trim()) { - searchParams.push({ name: 'url:contains', value: value.trim() }); + for (const [key, rawValue] of Object.entries(params || {})) { + if (!key.startsWith('_') && rawValue !== undefined && rawValue !== null && rawValue !== '' && SearchWorker.ALLOWED_PARAMS.includes(key)) { + const values = Array.isArray(rawValue) ? rawValue : [rawValue]; + for (const v of values) { + if (v === undefined || v === null || v === '') { + continue; + } + if (typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') { + throw new Issue('error', 'invalid', null, 'TX_SEARCH_PARAM_NOT_PRIMITIVE', + this.i18n.translate('TX_SEARCH_PARAM_NOT_PRIMITIVE', this.opContext.langs, [key]), 'invalid-data', 400); + } + const strVal = String(v); + if (key === 'url' && partialUrl) { + if (strVal.trim()) { + searchParams.push({ name: 'url:contains', value: strVal.trim() }); + } + } else { + searchParams.push({ name: key, value: strVal }); } - } else { - searchParams.push({ name: key, value: value }); } } } @@ -380,10 +407,18 @@ class SearchWorker extends TerminologyWorker { // Preserve search params for pagination links (excluding _offset) const searchParams = new URLSearchParams(); - const params = req.method === 'POST' ? req.body : req.query; + const params = (req.method === 'POST' ? req.body : req.query) || {}; for (const [key, value] of Object.entries(params)) { - if (key !== '_offset' && value) { - searchParams.set(key, value); + if (key !== '_offset' && value !== undefined && value !== null && value !== '') { + if (Array.isArray(value)) { + for (const v of value) { + if (v !== undefined && v !== null && v !== '') { + searchParams.append(key, String(v)); + } + } + } else { + searchParams.append(key, String(value)); + } } } @@ -505,7 +540,7 @@ class SearchWorker extends TerminologyWorker { // Check each search parameter for partial match let isMatch = true; - for (const [param, searchValue] of Object.entries(searchParams)) { + for (const { name: param, value: searchValue } of searchParams) { // Map content-mode to content property const jsonProp = param === 'content-mode' ? 'content' : param; @@ -595,7 +630,7 @@ class SearchWorker extends TerminologyWorker { // Check each search parameter for partial match let isMatch = true; - for (const [param, searchValue] of Object.entries(searchParams)) { + for (const { name: param, value: searchValue } of searchParams) { // Map content-mode to content property const jsonProp = param === 'content-mode' ? 'content' : param; From 7b6c0f13f2d5b8fd1cd7fad6a05035fceca80252 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 11:58:34 -0600 Subject: [PATCH 02/23] fix(batch-validate): return 405 for GET and 400 for malformed POST bodies --- tests/tx/fix-iss02-batch-validate-get.test.js | 55 +++++++++++++++++++ translations/Messages.properties | 2 + tx/tx.js | 39 +++++++------ tx/workers/batch-validate.js | 22 +++++++- 4 files changed, 95 insertions(+), 23 deletions(-) create mode 100644 tests/tx/fix-iss02-batch-validate-get.test.js diff --git a/tests/tx/fix-iss02-batch-validate-get.test.js b/tests/tx/fix-iss02-batch-validate-get.test.js new file mode 100644 index 00000000..c16df6a5 --- /dev/null +++ b/tests/tx/fix-iss02-batch-validate-get.test.js @@ -0,0 +1,55 @@ +/** + * Regression test for ISS-02: GET /$batch-validate-code returns 405 and malformed POST returns 400. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-02: $batch-validate-code GET 405 and malformed POST body 400', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test.each(['ValueSet', 'CodeSystem'])('GET /%s/$batch-validate-code returns 405 with Allow: POST', async (rt) => { + const res = await request(app).get(`${R5}/${rt}/$batch-validate-code`).set('Accept', 'application/fhir+json'); + expect(res.status).toBe(405); + expect(res.headers.allow).toBe('POST'); + expect(res.body.resourceType).toBe('OperationOutcome'); + }); + + test('POST /ValueSet/$batch-validate-code with non-Parameters body returns 400', async () => { + const res = await request(app).post(`${R5}/ValueSet/$batch-validate-code`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Bundle', type: 'collection' }); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('invalid'); + }); + + test('GET /ValueSet/$batch-validate-code honors Accept: application/fhir+xml on 405', async () => { + const res = await request(app).get(`${R5}/ValueSet/$batch-validate-code`).set('Accept', 'application/fhir+xml'); + expect(res.status).toBe(405); + expect(res.headers.allow).toBe('POST'); + expect(res.headers['content-type']).toMatch(/xml/); + expect(res.text).toContain(' { + const res = await request(app).post(`${R5}/ValueSet/$batch-validate-code`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter: [{ name: 'validation', valueString: 'bad' }] }); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('invalid'); + }); +}); diff --git a/translations/Messages.properties b/translations/Messages.properties index ae08935c..ad39dde1 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -1513,6 +1513,8 @@ TX_PARAM_VERSION_RULE_INVALID = The value ''{1}'' of the parameter ''{0}'' isn'' TX_PARAM_CACHE_ID_WITHDRAWN = The parameter ''cache-id'' is no longer supported: start a cache with $cache-control (mode=start), and send the cache-id it returns in the HTTP header ''X-Cache-Id'' TX_SEARCH_PARAMS_NOT_OBJECT = Search parameters must be an object TX_SEARCH_PARAM_NOT_PRIMITIVE = Search parameter ''{0}'' must have a primitive value +TX_BATCH_VALIDATE_PARAMETERS_REQUIRED = $batch-validate-code requires a Parameters resource body +TX_BATCH_VALIDATE_ENTRY_PARAMETERS_REQUIRED = Each validation entry must carry a Parameters resource FILTER_VALUE_UNKNOWN_CODE = The filter value ''{0}'' is not a code in {1} XHTML_CONTROL_NO_SOURCE = The xhtml node at ''{0}'' does not have a class attribute to indicate its source (boilerplate, generated, or original) and this is required by the profile {1} XHTML_XHTML_MIXED_LANG = The xhtml has some language sections ({0}), and also has content that is not in a language section diff --git a/tx/tx.js b/tx/tx.js index 91047583..26712f49 100644 --- a/tx/tx.js +++ b/tx/tx.js @@ -1358,16 +1358,11 @@ class TXModule { } }); - // CodeSystem/$batch-validate-code (GET and POST) - router.get('/CodeSystem/\\$batch-validate-code', async (req, res) => { - const start = Date.now(); - try { - let worker = new BatchValidateWorker(req.txOpContext, this.log, req.txProvider, this.languages, this.i18n); - worker.conceptMapValueSetMatching = this.config.conceptMapValueSetMatching === true; - await worker.handleCodeSystem(req, res); - } finally { - this.countRequest(endpointPath, '$batch', Date.now() - start, req); - } + // CodeSystem/$batch-validate-code (POST only; GET returns 405) + router.get('/CodeSystem/\\$batch-validate-code', (req, res) => { + res.setHeader('Allow', 'POST'); + return res.status(405).json(this.operationOutcome('error', 'not-supported', + `Method ${req.method} is not supported`, 'not-supported')); }); router.post('/CodeSystem/\\$batch-validate-code', async (req, res) => { const start = Date.now(); @@ -1421,16 +1416,11 @@ class TXModule { } }); - // ValueSet/$batch-validate-code (GET and POST) - router.get('/ValueSet/\\$batch-validate-code', async (req, res) => { - const start = Date.now(); - try { - let worker = new BatchValidateWorker(req.txOpContext, this.log, req.txProvider, this.languages, this.i18n); - worker.conceptMapValueSetMatching = this.config.conceptMapValueSetMatching === true; - await worker.handleValueSet(req, res); - } finally { - this.countRequest(endpointPath, '$batch', Date.now() - start, req); - } + // ValueSet/$batch-validate-code (POST only; GET returns 405) + router.get('/ValueSet/\\$batch-validate-code', (req, res) => { + res.setHeader('Allow', 'POST'); + return res.status(405).json(this.operationOutcome('error', 'not-supported', + `Method ${req.method} is not supported`, 'not-supported')); }); router.post('/ValueSet/\\$batch-validate-code', async (req, res) => { const start = Date.now(); @@ -1730,6 +1720,15 @@ class TXModule { router.all(`/${resourceType}/:id`, (req, res, next) => { const start = Date.now(); try { + if (req.params.id === '$batch-validate-code' && (resourceType === 'CodeSystem' || resourceType === 'ValueSet')) { + res.setHeader('Allow', 'POST'); + return res.status(405).json(this.operationOutcome( + 'error', + 'not-supported', + `Method ${req.method} is not supported`, + 'not-supported' + )); + } // /ConceptMap/$closure etc: an operation this server doesn't have at this // level, not a resource that refuses the method if (req.params.id.startsWith('$')) { diff --git a/tx/workers/batch-validate.js b/tx/workers/batch-validate.js index aa516711..7c0bcb98 100644 --- a/tx/workers/batch-validate.js +++ b/tx/workers/batch-validate.js @@ -88,6 +88,15 @@ class BatchValidateWorker extends TerminologyWorker { async processBatch(req, res, globalNames, codeSystemRoute = false) { try { let params = req.body; + if (!params || typeof params !== 'object' || params.resourceType !== 'Parameters' || + (params.parameter !== undefined && !Array.isArray(params.parameter))) { + return res.status(400).json(outcomeFromError(new Issue('error', 'invalid', null, + 'TX_BATCH_VALIDATE_PARAMETERS_REQUIRED', + this.i18n.translate('TX_BATCH_VALIDATE_PARAMETERS_REQUIRED', this.opContext.langs), 'invalid-data', 400))); + } + if (!params.parameter) { + params.parameter = []; + } this.addHttpParams(req, params); let globalParams = []; @@ -111,6 +120,13 @@ class BatchValidateWorker extends TerminologyWorker { for (const p of params.parameter) { if (p.name == 'validation') { + if (!p.resource || p.resource.resourceType !== 'Parameters' || + (p.resource.parameter !== undefined && !Array.isArray(p.resource.parameter))) { + return res.status(400).json(outcomeFromError(new Issue('error', 'invalid', null, + 'TX_BATCH_VALIDATE_ENTRY_PARAMETERS_REQUIRED', + this.i18n.translate('TX_BATCH_VALIDATE_ENTRY_PARAMETERS_REQUIRED', this.opContext.langs), 'invalid-data', 400))); + } + const validationParams = p.resource.parameter || []; let op = new Parameters(); op.jsonObj.parameter = []; for (const gp of globalParams) { @@ -125,14 +141,14 @@ class BatchValidateWorker extends TerminologyWorker { } continue; } - let exists = p.resource.parameter.find(pp => gp.name == pp.name); + let exists = validationParams.find(pp => gp.name == pp.name); if (!exists) { op.jsonObj.parameter.push(gp); } } const entryParams = frontLoaded - ? p.resource.parameter.filter(pp => pp.name !== 'tx-resource') - : p.resource.parameter; + ? validationParams.filter(pp => pp.name !== 'tx-resource') + : validationParams; op.jsonObj.parameter.push(...entryParams); // Each entry gets its own provider list, closed as soon as the entry is From 16b959fd0f0d3215b0dd29b56065249c50f73084 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 11:58:59 -0600 Subject: [PATCH 03/23] fix(worker): return HTTP 422 instead of 500 for ValueSet.compose.lockedDate --- tests/tx/fix-iss03-locked-date.test.js | 53 ++++++++++++++++++++++++++ tx/workers/worker.js | 2 +- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 tests/tx/fix-iss03-locked-date.test.js diff --git a/tests/tx/fix-iss03-locked-date.test.js b/tests/tx/fix-iss03-locked-date.test.js new file mode 100644 index 00000000..57809bcb --- /dev/null +++ b/tests/tx/fix-iss03-locked-date.test.js @@ -0,0 +1,53 @@ +/** + * Regression test for ISS-03: ValueSet.compose.lockedDate returns HTTP 422 instead of 500. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-03: ValueSet.compose.lockedDate returns 422 business-rule', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + const lockedVs = { + resourceType: 'ValueSet', + url: 'http://example.org/vs-locked', + status: 'active', + compose: { + lockedDate: '2025-01-01', + include: [{ system: 'http://hl7.org/fhir/administrative-gender' }] + } + }; + + test('$expand rejects lockedDate with 422 business-rule', async () => { + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: lockedVs }]); + expect(res.status).toBe(422); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('business-rule'); + }); + + test('$compare rejects lockedDate with 422 business-rule', async () => { + const res = await post('ValueSet/$compare', [ + { name: 'thisValueSet', resource: lockedVs }, + { name: 'otherUrl', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' } + ]); + expect(res.status).toBe(422); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('business-rule'); + }); +}); diff --git a/tx/workers/worker.js b/tx/workers/worker.js index 50353a7e..a392ef39 100644 --- a/tx/workers/worker.js +++ b/tx/workers/worker.js @@ -1435,7 +1435,7 @@ class TerminologyWorker { checkNoLockedDate(url, compose) { if (compose.lockedDate) { - throw new Issue("error", "business-rule", null, null, `Cannot process ValueSet ${url} due to the presence of a lockedDate on the compose`); + throw new Issue("error", "business-rule", null, null, `Cannot process ValueSet ${url} due to the presence of a lockedDate on the compose`, null, 422); } return true; } From 8f801e24814a57f4e16a22f51661cb505ae13e7d Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 11:59:08 -0600 Subject: [PATCH 04/23] fix(parameters): reject multi-value[x] and mixed choice-type parameters with 400 --- tests/tx/fix-iss04-multi-value-param.test.js | 54 ++++++++++++++++++++ translations/Messages.properties | 1 + tx/library/parameter-types.js | 19 ++++--- 3 files changed, 68 insertions(+), 6 deletions(-) create mode 100644 tests/tx/fix-iss04-multi-value-param.test.js diff --git a/tests/tx/fix-iss04-multi-value-param.test.js b/tests/tx/fix-iss04-multi-value-param.test.js new file mode 100644 index 00000000..051ae8d1 --- /dev/null +++ b/tests/tx/fix-iss04-multi-value-param.test.js @@ -0,0 +1,54 @@ +/** + * Regression test for ISS-04: multi-value[x] / mixed choice-type Parameters.parameter rejected with 400. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-04: multi-value[x] Parameters.parameter rejected with 400', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + test.each([ + ['$expand url with valueUri + valueString', 'ValueSet/$expand', [ + { name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender', valueString: [] } + ]], + ['$validate-code code with valueCode + valueString', 'ValueSet/$validate-code', [ + { name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'system', valueUri: 'http://hl7.org/fhir/administrative-gender' }, + { name: 'code', valueCode: 'male', valueString: {} } + ]], + ['$lookup system with valueUri + valueString', 'CodeSystem/$lookup', [ + { name: 'system', valueUri: 'http://hl7.org/fhir/administrative-gender', valueString: {} }, + { name: 'code', valueCode: 'male' } + ]], + ['$translate system with valueUri + valueString', 'ConceptMap/$translate', [ + { name: 'system', valueUri: 'http://hl7.org/fhir/administrative-gender', valueString: {} }, + { name: 'code', valueCode: 'male' }, + { name: 'targetSystem', valueUri: 'http://example.org/tgt' } + ]], + ['value[x] combined with resource', 'ValueSet/$expand', [ + { name: 'valueSet', valueUri: 'http://example.org/vs', resource: { resourceType: 'ValueSet', status: 'active' } } + ]] + ])('%s -> 400 invalid', async (_label, op, parameter) => { + const res = await post(op, parameter); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('invalid'); + }); +}); diff --git a/translations/Messages.properties b/translations/Messages.properties index ad39dde1..5f9b6260 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -1508,6 +1508,7 @@ TX_PARAM_PROFILE_RESOURCE = The parameter ''profile'' is only supported as an in TX_PARAM_PROFILE_TYPE = The parameter ''profile'' is only supported as an inline Parameters resource, not a value of type {0} TX_PARAM_PROFILE_VALUE = The parameter ''profile'' is only supported as an inline Parameters resource, not the value ''{0}'' TX_PARAM_INVALID_VALUE = The parameter ''{0}'' has the value {1} as a {2}, which isn''t valid: a {2} is a JSON {3} +TX_PARAM_MULTIPLE_VALUES = Parameter ''{0}'' must have at most one value[x], resource, or part TX_PARAM_WRONG_TYPE = The parameter ''{0}'' has {1}, but its value must be {2} TX_PARAM_VERSION_RULE_INVALID = The value ''{1}'' of the parameter ''{0}'' isn''t valid: it must be the url of a {2}, then ''|'', then the version TX_PARAM_CACHE_ID_WITHDRAWN = The parameter ''cache-id'' is no longer supported: start a cache with $cache-control (mode=start), and send the cache-id it returns in the HTTP header ''X-Cache-Id'' diff --git a/tx/library/parameter-types.js b/tx/library/parameter-types.js index 1aceceb2..dcb842d8 100644 --- a/tx/library/parameter-types.js +++ b/tx/library/parameter-types.js @@ -48,14 +48,15 @@ function isStringParameter(name) { return KIND_OF.get(name) === 'string'; } -/** the value[x] of a parameter: [type (e.g. 'Code'), value], or null */ -function valueOf(p) { +/** all value[x] entries of a parameter: Array<[type (e.g. 'Code'), value]> */ +function valuesOf(p) { + const result = []; for (const key of Object.keys(p)) { - if (key.startsWith('value') && key.length > 5 && key[5] === key[5].toUpperCase()) { - return [key.substring(5), p[key]]; + if (key.startsWith('value') && key.length > 5 && key[5] === key[5].toUpperCase() && p[key] !== undefined) { + result.push([key.substring(5), p[key]]); } } - return null; + return result; } /** why the value isn't valid JSON for its type, or null */ @@ -164,7 +165,13 @@ function parameterTypeIssue(params, i18n, langs) { if (p.name === 'cache-id') { return cacheIdIssue(here, i18n, langs); } - const v = valueOf(p); + const values = valuesOf(p); + const contentCount = values.length + (p.resource !== undefined ? 1 : 0) + (p.part !== undefined ? 1 : 0); + if (contentCount > 1) { + const msg = i18n.translate('TX_PARAM_MULTIPLE_VALUES', langs, [p.name]); + return new Issue('error', 'invalid', here, 'TX_PARAM_MULTIPLE_VALUES', msg, 'invalid-data', 400).handleAsOO(400); + } + const v = values.length === 1 ? values[0] : null; if (v) { const [type, value] = v; const wanted = jsonProblem(type, value); From f57c19a304e49e5a5a4091dd23d335ca0d9abba6 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 11:59:19 -0600 Subject: [PATCH 05/23] fix(omop): throw typed 422 too-costly Issue from iterator()/nextContext() --- tests/tx/fix-iss05-omop-iterator.test.js | 35 ++++++++++++++++++++++++ translations/Messages.properties | 1 + tx/cs/cs-omop.js | 6 ++-- 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 tests/tx/fix-iss05-omop-iterator.test.js diff --git a/tests/tx/fix-iss05-omop-iterator.test.js b/tests/tx/fix-iss05-omop-iterator.test.js new file mode 100644 index 00000000..ede3baf0 --- /dev/null +++ b/tests/tx/fix-iss05-omop-iterator.test.js @@ -0,0 +1,35 @@ +/** + * Regression test for ISS-05: OMOP whole-system iteration throws typed HTTP 422 too-costly Issue. + */ + +const path = require('path'); +const { OMOPServicesFactory } = require('../../tx/cs/cs-omop'); +const { OperationContext } = require('../../tx/operation-context'); +const { Issue } = require('../../tx/library/operation-outcome'); +const { TestUtilities } = require('../test-utilities'); + +describe('ISS-05: OMOP iterator throws typed 422 too-costly Issue', () => { + test('OMOPServices.iterator and nextContext throw Issue with statusCode 422', async () => { + const testDbPath = path.resolve(__dirname, '../../tx/data/omop-fragment.db'); + const opContext = new OperationContext('en', await TestUtilities.loadTranslations()); + const factory = new OMOPServicesFactory(opContext.i18n, testDbPath); + const provider = await factory.build(opContext, []); + try { + for (const call of [() => provider.iterator(null), () => provider.nextContext(null)]) { + let caught = null; + try { + await call(); + } catch (e) { + caught = e; + } + expect(caught).toBeInstanceOf(Issue); + expect(caught.statusCode).toBe(422); + expect(caught.cause).toBe('too-costly'); + expect(caught.msgId).toBe('CODESYSTEM_TOO_LARGE_TO_ITERATE'); + expect(caught.message).toContain('too large'); + } + } finally { + provider.close(); + } + }); +}); diff --git a/translations/Messages.properties b/translations/Messages.properties index 5f9b6260..f4928ae2 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -162,6 +162,7 @@ CODESYSTEM_THO_CHECK = Most code systems defined in HL7 IGs will need to move to CODESYSTEM_TOO_COSTLY_TIME = The operation ''{1}'' took too long to process (>{0}sec) (at {2}) CODESYSTEM_VERSION_NEEDED = The code system ''{0}'' says that a version must be specified when it is referenced (versionNeeded = true), but this coding has no version CODESYSTEM_NOT_ENUMERABLE = The code system ''{0}'' cannot be expanded because its codes cannot be iterated or enumerated in any meaningful sense +CODESYSTEM_TOO_LARGE_TO_ITERATE = The code system ''{0}'' is too large to iterate Coding_has_no_system__cannot_validate = Coding has no system. A code with no system has no defined meaning, and it cannot be validated. A system should be provided Coding_has_no_system_or_code__cannot_validate = Coding has neither a system nor a code, so it cannot be validated. A system and a code should be provided CONCEPTMAP_GROUP_SOURCE_CODE_INVALID = The source code ''{0}'' is not valid in the code system {1} diff --git a/tx/cs/cs-omop.js b/tx/cs/cs-omop.js index 33cf0e40..040001af 100644 --- a/tx/cs/cs-omop.js +++ b/tx/cs/cs-omop.js @@ -500,12 +500,14 @@ class OMOPServices extends BaseCSServices { // Iterator methods - not supported for OMOP due to size async iterator(context) { await this.#ensureContext(context); - throw new Error('getNextContext not supported by OMOP - too large to iterate'); + throw new Issue('error', 'too-costly', null, 'CODESYSTEM_TOO_LARGE_TO_ITERATE', + this.opContext.i18n.translate('CODESYSTEM_TOO_LARGE_TO_ITERATE', this.opContext.langs, [this.system()]), 'too-costly', 422); } // eslint-disable-next-line no-unused-vars async nextContext(iteratorContext) { - throw new Error('getNextContext not supported by OMOP - too large to iterate'); + throw new Issue('error', 'too-costly', null, 'CODESYSTEM_TOO_LARGE_TO_ITERATE', + this.opContext.i18n.translate('CODESYSTEM_TOO_LARGE_TO_ITERATE', this.opContext.langs, [this.system()]), 'too-costly', 422); } // Filter support From bdb64e1a6bf56220bc6318b2b796b7e7d24a9879 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 11:59:32 -0600 Subject: [PATCH 06/23] fix(parsers): preserve UTF-16 surrogate pairs in VCL and SNOMED SCG error messages --- tests/tx/fix-iss08-surrogate-pairs.test.js | 40 ++++++++++++++++++++++ tx/sct/expressions.js | 23 ++++++++++--- vcl/vcl-parser.js | 4 ++- 3 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 tests/tx/fix-iss08-surrogate-pairs.test.js diff --git a/tests/tx/fix-iss08-surrogate-pairs.test.js b/tests/tx/fix-iss08-surrogate-pairs.test.js new file mode 100644 index 00000000..4898e4ac --- /dev/null +++ b/tests/tx/fix-iss08-surrogate-pairs.test.js @@ -0,0 +1,40 @@ +/** + * Regression test for ISS-08: preserve non-BMP UTF-16 surrogate pairs in VCL and SNOMED SCG errors. + */ + +const { parseVCL } = require('../../vcl/vcl-parser'); +const { SnomedExpressionParser } = require('../../tx/sct/expressions'); + +describe('ISS-08: non-BMP UTF-16 surrogate pair safety in VCL and SNOMED SCG parsers', () => { + test('VCL lexer error preserves full astral character without lone surrogate escapes', () => { + let msg = ''; + try { + parseVCL('😀'); + } catch (e) { + msg = e.message; + } + expect(msg).toContain('😀'); + expect(JSON.stringify({ msg })).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/i); + }); + + test('SNOMED SCG parser error preserves full astral character and safe snippet without lone surrogates', () => { + const parser = new SnomedExpressionParser(); + let msg = ''; + try { + parser.parse('🩺-test-🧬'); + } catch (e) { + msg = e.message; + } + expect(msg).toContain('🩺'); + expect(JSON.stringify({ msg })).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/i); + + const longStr = 'a'.repeat(199) + '🩺'; + let longMsg = ''; + try { + parser.parse(longStr); + } catch (e) { + longMsg = e.message; + } + expect(JSON.stringify({ longMsg })).not.toMatch(/\\ud[89a-f][0-9a-f]{2}/i); + }); +}); diff --git a/tx/sct/expressions.js b/tx/sct/expressions.js index 5527d50f..dc9f939a 100644 --- a/tx/sct/expressions.js +++ b/tx/sct/expressions.js @@ -758,7 +758,7 @@ class SnomedExpressionParser { } const result = this.source.substring(start, this.cursor); - this.rule(result.length > 0, 'Concept not found (next char = "' + this.peekDisp() + '", in "' + this.source.substring(0, 200) + '")'); + this.rule(result.length > 0, 'Concept not found (next char = "' + this.peekDisp() + '", in "' + this.sourceSnippet(200) + '")'); return result; } @@ -847,7 +847,7 @@ class SnomedExpressionParser { */ fixed(c) { const success = this.gchar(c); - this.rule(success, 'Expected character "' + c + '" but found ' + this.peek()); + this.rule(success, 'Expected character "' + c + '" but found ' + this.peekDisp()); this.ws(); } @@ -881,13 +881,28 @@ class SnomedExpressionParser { } /** - * Get a display string for the current character + * Get a display string for the current character (preserving full Unicode code points) */ peekDisp() { if (this.cursor >= this.source.length) { return '[n/a: overrun]'; } - return this.source[this.cursor]; + const cp = this.source.codePointAt(this.cursor); + return (cp !== undefined ? String.fromCodePoint(cp) : this.source[this.cursor]).toWellFormed(); + } + + /** + * Slice the source without splitting a trailing UTF-16 surrogate pair + */ + sourceSnippet(maxLen) { + let s = this.source.length > maxLen ? this.source.substring(0, maxLen) : this.source; + if (s.length > 0) { + const last = s.charCodeAt(s.length - 1); + if (last >= 0xD800 && last <= 0xDBFF) { + s = s.substring(0, s.length - 1); + } + } + return s.toWellFormed(); } /** diff --git a/vcl/vcl-parser.js b/vcl/vcl-parser.js index ca915d84..e3611834 100644 --- a/vcl/vcl-parser.js +++ b/vcl/vcl-parser.js @@ -246,7 +246,9 @@ class VCLLexer { } tokens.push(new Token(TokenType.SCODE, this.input.substring(startPos, this.pos), startPos)); } else { - throw new VCLParseException(`Unexpected character: ${ch}`, startPos); + const cp = this.input.codePointAt(startPos); + const disp = (cp !== undefined ? String.fromCodePoint(cp) : ch).toWellFormed(); + throw new VCLParseException(`Unexpected character: ${disp}`, startPos); } } tokens.push(new Token(TokenType.EOF, '', this.pos)); From f72a80ede614242c87491c5dccb9cabe0fea3614 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 11:59:54 -0600 Subject: [PATCH 07/23] fix(parameters): enforce 32-bit signed FHIR integer bounds with HTTP 400 --- tests/tx/fix-iss09-int32-bounds.test.js | 58 +++++++++++++++++++++++++ tx/library/parameter-types.js | 31 +++++++++++-- 2 files changed, 86 insertions(+), 3 deletions(-) create mode 100644 tests/tx/fix-iss09-int32-bounds.test.js diff --git a/tests/tx/fix-iss09-int32-bounds.test.js b/tests/tx/fix-iss09-int32-bounds.test.js new file mode 100644 index 00000000..9346e14b --- /dev/null +++ b/tests/tx/fix-iss09-int32-bounds.test.js @@ -0,0 +1,58 @@ +/** + * Regression test for ISS-09: 32-bit signed FHIR integer bounds in parameter validation. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-09: 32-bit signed FHIR integer bounds in parameter validation', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + test.each([ + ['valueInteger overflow (2^31)', { name: 'offset', valueInteger: 2147483648 }], + ['valueInteger underflow (-2^31 - 1)', { name: 'offset', valueInteger: -2147483649 }], + ['valueString integer overflow', { name: 'offset', valueString: '2147483648' }], + ['valuePositiveInt zero', { name: 'count', valuePositiveInt: 0 }], + ['valueUnsignedInt negative', { name: 'offset', valueUnsignedInt: -1 }] + ])('%s -> 400 invalid', async (_label, paramObj) => { + const res = await post('ValueSet/$expand', [ + { name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + paramObj + ]); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('invalid'); + }); + + test('GET query param integer overflow -> 400 invalid', async () => { + const res = await request(app) + .get(`${R5}/ValueSet/$expand?url=http://hl7.org/fhir/ValueSet/administrative-gender&offset=2147483648`) + .set('Accept', 'application/fhir+json'); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + }); + + test('max valid 32-bit signed integer (2147483647) is accepted', async () => { + const res = await post('ValueSet/$expand', [ + { name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'offset', valueInteger: 2147483647 } + ]); + expect(res.status).toBe(200); + }); +}); diff --git a/tx/library/parameter-types.js b/tx/library/parameter-types.js index dcb842d8..5d5b1292 100644 --- a/tx/library/parameter-types.js +++ b/tx/library/parameter-types.js @@ -48,6 +48,9 @@ function isStringParameter(name) { return KIND_OF.get(name) === 'string'; } +const INT32_MIN = -2147483648; +const INT32_MAX = 2147483647; + /** all value[x] entries of a parameter: Array<[type (e.g. 'Code'), value]> */ function valuesOf(p) { const result = []; @@ -68,7 +71,21 @@ function jsonProblem(type, value) { if (typeof value !== 'number' || !Number.isFinite(value)) { return 'number'; } - return WHOLE.includes(type) && !Number.isInteger(value) ? 'whole number' : null; + if (WHOLE.includes(type)) { + if (!Number.isInteger(value)) { + return 'whole number'; + } + if (type === 'Integer' && (value < INT32_MIN || value > INT32_MAX)) { + return '32-bit signed integer'; + } + if (type === 'PositiveInt' && (value < 1 || value > INT32_MAX)) { + return 'positive 32-bit integer'; + } + if (type === 'UnsignedInt' && (value < 0 || value > INT32_MAX)) { + return 'non-negative 32-bit integer'; + } + } + return null; } if (JSON_BOOLEAN.includes(type)) { return typeof value === 'boolean' ? null : 'boolean'; @@ -124,8 +141,16 @@ function kindAccepts(kind, type, value) { return JSON_STRING.includes(type); case 'boolean': return type === 'Boolean' || (JSON_STRING.includes(type) && (value === 'true' || value === 'false')); - case 'integer': - return WHOLE.includes(type) || (JSON_STRING.includes(type) && /^-?[0-9]+$/.test(value)); + case 'integer': { + if (WHOLE.includes(type)) { + return typeof value === 'number' && Number.isInteger(value) && value >= INT32_MIN && value <= INT32_MAX; + } + if (JSON_STRING.includes(type) && /^-?[0-9]+$/.test(value)) { + const n = Number(value); + return Number.isSafeInteger(n) && n >= INT32_MIN && n <= INT32_MAX; + } + return false; + } default: return type === kind; } From eaf5ac0bc56b50a8a1a8f28c45dce55cee123d95 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:00:10 -0600 Subject: [PATCH 08/23] fix(tx): return 400 FHIR JSON OperationOutcome on malformed JSON bodies --- tests/tx/fix-iss15-malformed-json.test.js | 44 +++++++++++++++++++++++ translations/Messages.properties | 1 + tx/tx.js | 30 ++++++++++------ 3 files changed, 65 insertions(+), 10 deletions(-) create mode 100644 tests/tx/fix-iss15-malformed-json.test.js diff --git a/tests/tx/fix-iss15-malformed-json.test.js b/tests/tx/fix-iss15-malformed-json.test.js new file mode 100644 index 00000000..560c57b9 --- /dev/null +++ b/tests/tx/fix-iss15-malformed-json.test.js @@ -0,0 +1,44 @@ +/** + * Regression test for ISS-15: malformed JSON request bodies return FHIR JSON OperationOutcome + * without logging an error in the server log, with i18n message INVALID_JSON. + */ + +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-15: malformed JSON request body returns FHIR JSON OperationOutcome', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test('POST with Content-Type: application/json and truncated JSON returns 400 JSON OperationOutcome without error log', async () => { + const logSpy = jest.spyOn(getTxModule().log, 'error'); + try { + const res = await request(app) + .post(`${R5}/CodeSystem/$lookup`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send('{"resourceType":"Parameters","parameter":['); + expect(res.status).toBe(400); + expect(res.headers['content-type']).toMatch(/json/); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('invalid'); + expect(res.body.issue[0].details.text).toMatch(/^Invalid JSON:/); + expect(res.body.issue[0].extension).toContainEqual({ + url: 'http://hl7.org/fhir/StructureDefinition/operationoutcome-message-id', + valueString: 'INVALID_JSON' + }); + expect(logSpy).not.toHaveBeenCalled(); + } finally { + logSpy.mockRestore(); + } + }); +}); diff --git a/translations/Messages.properties b/translations/Messages.properties index f4928ae2..dd3dc6bf 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -1630,6 +1630,7 @@ VALUESET_CODE_CONCEPT_HINT = {3}. Note that the display in the ValueSet does not VALUESET_CODE_CONCEPT_HINT_VER ={3}. Note that the display in the ValueSet does not have to match; this check exists to help check that it''s not accidentally the wrong code TERMINOLOGY_TX_SYSTEM_UNSUPPORTED = The code cannot be checked because codeSystem ''{0}'' version ''{1}'' is not supported ({2}) INVALID_REGEX = The regex ''{0}'' is not valid: {1} +INVALID_JSON = Invalid JSON: {0} INVALID_ECL = Invalid ECL expression: ''{0}'': ({1}) UNSUPPORTED_ECL = The ECL expression is not supported: ''{0}'': ({1}) diff --git a/tx/tx.js b/tx/tx.js index 26712f49..37908fe3 100644 --- a/tx/tx.js +++ b/tx/tx.js @@ -87,7 +87,7 @@ const { ClosureStore } = require("./closure/closure-store"); const {BundleXML} = require("./xml/bundle-xml"); const ConceptUsageTracker = require("./usage-tracker"); const ProblemFinder = require("./problems"); -const { buildOperationOutcome, outcomeFromError } = require('./library/operation-outcome'); +const { Issue, buildOperationOutcome, outcomeFromError } = require('./library/operation-outcome'); const { Extensions } = require('./library/extensions'); const txOpenApi = require('./openapi'); const { SyndicationStore } = require('./syndication/syndication-store'); @@ -1117,6 +1117,12 @@ class TXModule { `The request body is bigger than this server accepts (${req.bodyTooLarge.limit} bytes)`)); } + // Malformed JSON rejected by the app-level JSON body parser (see below) + if (req.bodyParseError) { + return res.status(400).json(outcomeFromError(new Issue('error', 'invalid', null, 'INVALID_JSON', + this.i18n.translate('INVALID_JSON', req.txOpContext.langs, [req.bodyParseError.message]), 'invalid-data', 400))); + } + // Only process POST/PUT if (req.method !== 'POST' && req.method !== 'PUT') { return next(); @@ -1147,8 +1153,8 @@ class TXModule { req.body = JSON.parse(text); } } catch (e) { - this.log.error(`JSON parse error: ${e.message}`); - return res.status(400).json(buildOperationOutcome('error', 'invalid', `Invalid JSON: ${e.message}`)); + return res.status(400).json(outcomeFromError(new Issue('error', 'invalid', null, 'INVALID_JSON', + this.i18n.translate('INVALID_JSON', req.txOpContext.langs, [e.message]), 'invalid-data', 400))); } } @@ -1215,15 +1221,19 @@ class TXModule { next(); }); - // A body over the size limit is refused by the body parsers, which run before this - // router, and Express would answer with its HTML error page. Note it and carry on, so - // the router answers with an OperationOutcome, in the format the client asked for + // A body over the size limit or with invalid JSON is refused by the body parsers, which + // run before this router, and Express would answer with its HTML error page. Note it and + // carry on, so the router answers with an OperationOutcome, in the format the client asked for app.use(endpointPath, (err, req, res, next) => { - if (err.type !== 'entity.too.large') { - return next(err); + if (err.type === 'entity.too.large') { + req.bodyTooLarge = err; + return next(); } - req.bodyTooLarge = err; - next(); + if (err.type === 'entity.parse.failed') { + req.bodyParseError = err; + return next(); + } + return next(err); }); // Register the router with the app From 83d21ad18d1cc131adfa6676b3c930728bed193c Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 15:18:40 -0600 Subject: [PATCH 09/23] fix(translate,xversion): strip R4 equivalence on R5 responses and reject missing relationship --- tests/tx/fix-iss10-translate-r5-equiv.test.js | 190 ++++++++++++++++++ translations/Messages.properties | 1 + tx/tx.js | 2 +- tx/workers/translate.js | 10 + tx/xversion/xv-bundle.js | 13 +- tx/xversion/xv-conceptmap.js | 33 ++- tx/xversion/xv-parameters.js | 42 ++-- tx/xversion/xv-resource.js | 2 +- 8 files changed, 267 insertions(+), 26 deletions(-) create mode 100644 tests/tx/fix-iss10-translate-r5-equiv.test.js diff --git a/tests/tx/fix-iss10-translate-r5-equiv.test.js b/tests/tx/fix-iss10-translate-r5-equiv.test.js new file mode 100644 index 00000000..01729166 --- /dev/null +++ b/tests/tx/fix-iss10-translate-r5-equiv.test.js @@ -0,0 +1,190 @@ +/** + * Regression test for ISS-10: + * - Outbound R5 $translate strips legacy R4 'equivalence' and keeps 'relationship' (no incoming strip in parametersToR5). + * - Outbound R5 ConceptMap read (and search Bundle) strips internal R4 target.equivalence kept alongside relationship. + * - An R4-shaped ConceptMap (missing target.relationship) sent directly to /r5 reports a 400 error instead of silently mapping. + */ + +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { ConceptMap } = require('../../tx/library/conceptmap'); +const { parametersToR5, parametersFromR5 } = require('../../tx/xversion/xv-parameters'); +const { conceptMapToR5, conceptMapFromR5 } = require('../../tx/xversion/xv-conceptmap'); +const { bundleFromR5 } = require('../../tx/xversion/xv-bundle'); + +const R5 = '/tx/r5'; + +describe('ISS-10: R5 equivalence stripping and missing-relationship error', () => { + let app; + let storedR4Cm; + let mockCmProvider; + + const r4RawCm = () => ({ + resourceType: 'ConceptMap', + id: 'iss10-r4-cm', + url: 'http://example.org/cm-r4-stored-iss10', + version: '1.0', + status: 'active', + group: [{ + source: 'http://example.org/src', + target: 'http://example.org/tgt', + element: [{ + code: 'S1', + target: [{ code: 'T1', equivalence: 'wider' }] + }] + }] + }); + + beforeAll(async () => { + app = await getTestApp(); + storedR4Cm = new ConceptMap(r4RawCm(), '4.0.1'); + mockCmProvider = { + fetchConceptMapById: async (id) => (id === 'iss10-r4-cm' ? storedR4Cm : null), + fetchConceptMap: async (url) => (url === storedR4Cm.url ? storedR4Cm : null), + findConceptMapForTranslation: async () => [storedR4Cm], + searchConceptMaps: async () => [storedR4Cm] + }; + getTxModule().endpoints[0].provider.conceptMapProviders.unshift(mockCmProvider); + }, 240000); + + afterAll(async () => { + const txModule = getTxModule(); + if (txModule && txModule.endpoints[0]) { + const list = txModule.endpoints[0].provider.conceptMapProviders; + const idx = list.indexOf(mockCmProvider); + if (idx >= 0) list.splice(idx, 1); + } + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + const param = (res, name) => (res.body.parameter || []).find(p => p.name === name); + + test('parametersToR5 does not strip incoming R5 equivalence; parametersFromR5 strips outbound R5 equivalence', () => { + const p = { + resourceType: 'Parameters', + parameter: [{ + name: 'match', + part: [ + { name: 'relationship', valueCode: 'source-is-narrower-than-target' }, + { name: 'equivalence', valueCode: 'wider' } + ] + }] + }; + const incoming = parametersToR5(p, '5.0'); + expect(incoming).toBe(p); + expect(incoming.parameter[0].part.find(pp => pp.name === 'equivalence')).toBeDefined(); + + const outbound = parametersFromR5(p, '5.0'); + expect(outbound).not.toBe(p); + expect(outbound.parameter[0].part.find(pp => pp.name === 'relationship')).toEqual({ + name: 'relationship', + valueCode: 'source-is-narrower-than-target' + }); + expect(outbound.parameter[0].part.find(pp => pp.name === 'equivalence')).toBeUndefined(); + // Copy-on-write: original untouched + expect(p.parameter[0].part.find(pp => pp.name === 'equivalence')).toBeDefined(); + }); + + test('conceptMapFromR5 and bundleFromR5 strip internal target.equivalence on R5 without mutating stored R4 map', () => { + const internal = conceptMapToR5(r4RawCm(), '4.0.1'); + expect(internal.group[0].element[0].target[0].equivalence).toBe('wider'); + expect(internal.group[0].element[0].target[0].relationship).toBe('source-is-narrower-than-target'); + + const r5Cm = conceptMapFromR5(internal, '5.0'); + expect(r5Cm.group[0].element[0].target[0].relationship).toBe('source-is-narrower-than-target'); + expect(r5Cm.group[0].element[0].target[0].equivalence).toBeUndefined(); + // Stored internal copy retains equivalence for R4 clients + expect(internal.group[0].element[0].target[0].equivalence).toBe('wider'); + + const bundle = { resourceType: 'Bundle', type: 'searchset', entry: [{ resource: internal }] }; + const r5Bundle = bundleFromR5(bundle, '5.0'); + expect(r5Bundle.entry[0].resource.group[0].element[0].target[0].equivalence).toBeUndefined(); + expect(r5Bundle.entry[0].resource.group[0].element[0].target[0].relationship).toBe('source-is-narrower-than-target'); + }); + + test('GET /r5/ConceptMap/:id strips target.equivalence from stored R4 ConceptMap', async () => { + const res = await request(app) + .get(`${R5}/ConceptMap/iss10-r4-cm`) + .set('Accept', 'application/fhir+json'); + expect(res.status).toBe(200); + expect(res.body.resourceType).toBe('ConceptMap'); + const target = res.body.group[0].element[0].target[0]; + expect(target.relationship).toBe('source-is-narrower-than-target'); + expect(target.equivalence).toBeUndefined(); + // Stored ConceptMap still retains equivalence for R4 + expect(storedR4Cm.jsonObj.group[0].element[0].target[0].equivalence).toBe('wider'); + }); + + test('outbound R5 $translate (forward and reverse) on stored R4 ConceptMap emits relationship only', async () => { + const fwd = await post('ConceptMap/$translate', [ + { name: 'url', valueUri: storedR4Cm.url }, + { name: 'system', valueUri: 'http://example.org/src' }, + { name: 'code', valueCode: 'S1' } + ]); + expect(fwd.status).toBe(200); + const fwdMatch = param(fwd, 'match'); + expect(fwdMatch).toBeDefined(); + expect(fwdMatch.part.find(p => p.name === 'relationship')).toEqual({ + name: 'relationship', + valueCode: 'source-is-narrower-than-target' + }); + expect(fwdMatch.part.find(p => p.name === 'equivalence')).toBeUndefined(); + + const rev = await post('ConceptMap/$translate', [ + { name: 'url', valueUri: storedR4Cm.url }, + { name: 'targetCoding', valueCoding: { system: 'http://example.org/tgt', code: 'T1' } } + ]); + expect(rev.status).toBe(200); + const revMatch = param(rev, 'match'); + expect(revMatch).toBeDefined(); + expect(revMatch.part.find(p => p.name === 'relationship')).toEqual({ + name: 'relationship', + valueCode: 'source-is-narrower-than-target' + }); + expect(revMatch.part.find(p => p.name === 'equivalence')).toBeUndefined(); + }); + + test('R4-shaped ConceptMap (missing target.relationship) sent to /r5 $translate returns 400 error', async () => { + const r4ShapedOnR5 = { + resourceType: 'ConceptMap', + url: 'http://example.org/cm-r4-inline-iss10', + version: '1.0', + status: 'active', + group: [{ + source: 'http://example.org/src', + target: 'http://example.org/tgt', + element: [{ + code: 'S1', + target: [{ code: 'T1', equivalence: 'wider' }] + }] + }] + }; + + const fwd = await post('ConceptMap/$translate', [ + { name: 'url', valueUri: r4ShapedOnR5.url }, + { name: 'system', valueUri: 'http://example.org/src' }, + { name: 'code', valueCode: 'S1' }, + { name: 'tx-resource', resource: r4ShapedOnR5 } + ]); + expect(fwd.status).toBe(400); + expect(fwd.body.resourceType).toBe('OperationOutcome'); + expect(fwd.body.issue[0].code).toBe('invalid'); + expect(fwd.body.issue[0].details.text).toContain('relationship'); + + const rev = await post('ConceptMap/$translate', [ + { name: 'url', valueUri: r4ShapedOnR5.url }, + { name: 'targetCoding', valueCoding: { system: 'http://example.org/tgt', code: 'T1' } }, + { name: 'tx-resource', resource: r4ShapedOnR5 } + ]); + expect(rev.status).toBe(400); + expect(rev.body.resourceType).toBe('OperationOutcome'); + expect(rev.body.issue[0].code).toBe('invalid'); + expect(rev.body.issue[0].details.text).toContain('relationship'); + }); +}); diff --git a/translations/Messages.properties b/translations/Messages.properties index dd3dc6bf..671bf565 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -189,6 +189,7 @@ TRANSLATE_SCT_EDITION_TOP_LEVEL_ONE = No translation: the only {0} ancestor of { TRANSLATE_SCT_EDITION_TOP_LEVEL_MANY = No translation: the only {0} ancestors of {1} are the top-level hierarchy concepts {2} CODESYSTEM_MODIFIER_EXTENSION_UNKNOWN = The code system {0} can''t be processed: {1} has a modifier extension that isn''t understood ({2}) CONCEPTMAP_MODIFIER_EXTENSION_UNKNOWN = The concept map {0} can''t be processed: {1} has a modifier extension that isn''t understood ({2}) +CONCEPTMAP_TARGET_NO_RELATIONSHIP = ConceptMap ''{0}'' target for code ''{1}'' has no relationship (R5 requires ConceptMap.group.element.target.relationship) CONCEPTMAP_SHAREABLE_EXTRA_MISSING = Published concept maps SHOULD conform to the ShareableConceptMap profile, which says that the element ConceptMap.{0} should be present, but it is not CONCEPTMAP_SHAREABLE_EXTRA_MISSING_HL7 = Concept maps published by HL7 SHALL conform to the ShareableConceptMap profile, which says that the element ConceptMap.{0} should be present, but it is not CONCEPTMAP_SHAREABLE_MISSING = Published concept maps SHOULD conform to the ShareableConceptMap profile, which says that the element ConceptMap.{0} is mandatory, but it is not present diff --git a/tx/tx.js b/tx/tx.js index 37908fe3..80a2abc5 100644 --- a/tx/tx.js +++ b/tx/tx.js @@ -2598,7 +2598,7 @@ class TXModule { } transformResourceForVersion(data, fhirVersion) { - if (fhirVersion == "5.0" || !data.resourceType) { + if (!data.resourceType) { return data; } switch (data.resourceType) { diff --git a/tx/workers/translate.js b/tx/workers/translate.js index 348f1b1b..41fa8415 100644 --- a/tx/workers/translate.js +++ b/tx/workers/translate.js @@ -566,6 +566,11 @@ class TranslateWorker extends TerminologyWorker { ok = ['null', 'related-to', 'equivalent', 'source-is-narrower-than-target', 'source-is-broader-than-target', 'not-related-to'].includes(map.relationship); } if (ok) { + if (!map.relationship) { + throw new Issue('error', 'invalid', null, 'CONCEPTMAP_TARGET_NO_RELATIONSHIP', + this.i18n.translate('CONCEPTMAP_TARGET_NO_RELATIONSHIP', this.opContext.langs, [cm.vurl || cm.url || '(inline)', srcCode || '']), + 'invalid-data', 400); + } groupResult = true; // a target that names a value set rather than a code: every code in it is a target @@ -661,6 +666,11 @@ class TranslateWorker extends TerminologyWorker { ok = ['null', 'related-to', 'equivalent', 'source-is-narrower-than-target', 'source-is-broader-than-target', 'not-related-to'].includes(map.relationship); } if (ok) { + if (!map.relationship) { + throw new Issue('error', 'invalid', null, 'CONCEPTMAP_TARGET_NO_RELATIONSHIP', + this.i18n.translate('CONCEPTMAP_TARGET_NO_RELATIONSHIP', this.opContext.langs, [cm.vurl || cm.url || '(inline)', em.code || '']), + 'invalid-data', 400); + } result = true; const t = { diff --git a/tx/xversion/xv-bundle.js b/tx/xversion/xv-bundle.js index 8aecfb36..157dfaa7 100644 --- a/tx/xversion/xv-bundle.js +++ b/tx/xversion/xv-bundle.js @@ -1,4 +1,5 @@ const {VersionUtilities} = require("../../library/fhir/version-utilities"); +const { mapShared } = require("./xv-shared"); /** * Converts input Bundle to R5 format (modifies input object for performance) @@ -32,7 +33,17 @@ function bundleFromR5(r5Obj, targetVersion) { const {convertResourceFromR5} = require("./xv-resource"); if (VersionUtilities.isR5Ver(targetVersion)) { - return r5Obj; // No conversion needed + if (!Array.isArray(r5Obj.entry)) { + return r5Obj; + } + const entry = mapShared(r5Obj.entry, be => { + if (!be || !be.resource) { + return be; + } + const resource = convertResourceFromR5(be.resource, targetVersion); + return resource === be.resource ? be : { ...be, resource }; + }); + return entry === r5Obj.entry ? r5Obj : { ...r5Obj, entry }; } // Clone the object to avoid modifying the original diff --git a/tx/xversion/xv-conceptmap.js b/tx/xversion/xv-conceptmap.js index 6265ac8e..ba60125a 100644 --- a/tx/xversion/xv-conceptmap.js +++ b/tx/xversion/xv-conceptmap.js @@ -196,7 +196,11 @@ function conceptMapToR5(jsonObj, sourceVersion) { */ function conceptMapFromR5(r5Obj, targetVersion) { if (VersionUtilities.isR5Ver(targetVersion)) { - return r5Obj; // No conversion needed + if (!Array.isArray(r5Obj.group)) { + return r5Obj; + } + const group = convertOnce(r5Obj.group, 'cm-r5', groups => mapShared(groups, groupCleanForR5)); + return group === r5Obj.group ? r5Obj : { ...r5Obj, group }; } // R3 is converted as R4 is if (!VersionUtilities.isR4Ver(targetVersion) && !VersionUtilities.isR3Ver(targetVersion)) { @@ -254,6 +258,33 @@ function conceptMapFromR5(r5Obj, targetVersion) { return out; } +/** Strip internal R4 target.equivalence kept alongside relationship, for R5 responses @private */ +function groupCleanForR5(group) { + if (!Array.isArray(group.element)) { + return group; + } + const element = mapShared(group.element, elementCleanForR5); + return element === group.element ? group : { ...group, element }; +} + +function elementCleanForR5(element) { + if (!Array.isArray(element.target)) { + return element; + } + const target = mapShared(element.target, targetCleanForR5); + return target === element.target ? element : { ...element, target }; +} + +function targetCleanForR5(target) { + if (target.equivalence === undefined && target._equivalence === undefined) { + return target; + } + const copy = { ...target }; + delete copy.equivalence; + delete copy._equivalence; + return copy; +} + /** A group (the same object if nothing in it changes) @private */ function groupFromR5(group, attributes) { const unmapped = unmappedFromR5(group.unmapped); diff --git a/tx/xversion/xv-parameters.js b/tx/xversion/xv-parameters.js index 8b598aec..7b809b71 100644 --- a/tx/xversion/xv-parameters.js +++ b/tx/xversion/xv-parameters.js @@ -11,11 +11,7 @@ const { mapShared } = require("./xv-shared"); function parametersToR5(jsonObj, sourceVersion) { if (VersionUtilities.isR5Ver(sourceVersion)) { - if (jsonObj.parameter && jsonObj.parameter.find(p => p.name == 'match')) { - return convertResourceWithinR5(JSON.parse(JSON.stringify(jsonObj))); - } else { - return jsonObj; // No conversion needed - } + return jsonObj; // No conversion needed } const {convertResourceToR5} = require("./xv-resource"); @@ -39,7 +35,25 @@ function parametersToR5(jsonObj, sourceVersion) { */ function parametersFromR5(r5Obj, targetVersion) { if (VersionUtilities.isR5Ver(targetVersion)) { - return r5Obj; // No conversion needed + if (!Array.isArray(r5Obj.parameter)) { + return r5Obj; + } + const { convertResourceFromR5 } = require("./xv-resource"); + const parameter = mapShared(r5Obj.parameter, p => { + let copy = p; + if (p.resource) { + const resource = convertResourceFromR5(p.resource, targetVersion); + if (resource !== p.resource) { + copy = { ...copy, resource }; + } + } + // Strip legacy R4 'equivalence' parts from $translate match entries on R5 responses + if (p.name === 'match' && Array.isArray(p.part) && p.part.some(pp => pp.name === 'equivalence')) { + copy = { ...copy, part: p.part.filter(pp => pp.name !== 'equivalence') }; + } + return copy; + }); + return parameter === r5Obj.parameter ? r5Obj : { ...r5Obj, parameter }; } let convert; if (VersionUtilities.isR4Ver(targetVersion)) { @@ -102,22 +116,6 @@ function parameterR5ToR3(p, topLevel) { return copy; } -function convertResourceWithinR5(r5Obj) { - for (let p of r5Obj.parameter || []) { - if (p.name == 'match') { - fixMatchParameterfor5(p); - } - } - return r5Obj; - -} - -function fixMatchParameterfor5(p) { - if (p.part) { - p.part = p.part.filter(pp => pp.name !== 'equivalence'); - } -} - // The parts of a $translate match, for R4: a new array (the parts themselves are not changed) function matchPartsFor4(parts) { const out = [...parts]; diff --git a/tx/xversion/xv-resource.js b/tx/xversion/xv-resource.js index 84c0ec55..bdb7afeb 100644 --- a/tx/xversion/xv-resource.js +++ b/tx/xversion/xv-resource.js @@ -28,7 +28,7 @@ function convertResourceToR5(data, sourceVersion) { } function convertResourceFromR5(data, targetVersion) { - if (!data || targetVersion == "5.0" || !data.resourceType) { + if (!data || !data.resourceType) { return data; } switch (data.resourceType) { From f298e3e83c516089002fd7bb90af1b89b19d0640 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:00:46 -0600 Subject: [PATCH 10/23] fix(lookup): omit empty description for displayless parent/child concepts --- tests/tx/fix-iss11-lookup-empty-desc.test.js | 70 ++++++++++++++++++++ tx/cs/cs-cs.js | 10 ++- 2 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 tests/tx/fix-iss11-lookup-empty-desc.test.js diff --git a/tests/tx/fix-iss11-lookup-empty-desc.test.js b/tests/tx/fix-iss11-lookup-empty-desc.test.js new file mode 100644 index 00000000..97cd043b --- /dev/null +++ b/tests/tx/fix-iss11-lookup-empty-desc.test.js @@ -0,0 +1,70 @@ +/** + * Regression test for ISS-11: $lookup omits empty description for displayless parent/child concepts. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-11: $lookup omits empty description for displayless parent/child concepts', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + test('parent property omits description when parent has no display', async () => { + const csNoDisp = { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-nodisp-iss11', + version: '1.0', + status: 'active', + content: 'complete', + hierarchyMeaning: 'is-a', + concept: [{ code: 'P', concept: [{ code: 'C', display: 'Child Only' }] }] + }; + const res = await post('CodeSystem/$lookup', [ + { name: 'system', valueUri: csNoDisp.url }, + { name: 'code', valueCode: 'C' }, + { name: 'tx-resource', resource: csNoDisp } + ]); + expect(res.status).toBe(200); + const props = (res.body.parameter || []).filter(p => p.name === 'property'); + const parentProp = props.find(p => p.part.some(x => x.name === 'code' && x.valueCode === 'parent')); + expect(parentProp).toBeDefined(); + expect(parentProp.part.find(x => x.name === 'description')).toBeUndefined(); + }); + + test('child property omits description when child has no display', async () => { + const csNoChildDisp = { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-nochilddisp-iss11', + version: '1.0', + status: 'active', + content: 'complete', + hierarchyMeaning: 'is-a', + concept: [{ code: 'P', display: 'Parent Only', concept: [{ code: 'C' }] }] + }; + const res = await post('CodeSystem/$lookup', [ + { name: 'system', valueUri: csNoChildDisp.url }, + { name: 'code', valueCode: 'P' }, + { name: 'tx-resource', resource: csNoChildDisp } + ]); + expect(res.status).toBe(200); + const props = (res.body.parameter || []).filter(p => p.name === 'property'); + const childProp = props.find(p => p.part.some(x => x.name === 'code' && x.valueCode === 'child')); + expect(childProp).toBeDefined(); + expect(childProp.part.find(x => x.name === 'description')).toBeUndefined(); + }); +}); diff --git a/tx/cs/cs-cs.js b/tx/cs/cs-cs.js index 95bf13ad..0a5a9b8c 100644 --- a/tx/cs/cs-cs.js +++ b/tx/cs/cs-cs.js @@ -1162,7 +1162,10 @@ class FhirCodeSystemProvider extends BaseCSServices { let parts = []; parts.push({ name: 'code', valueCode: 'parent' }); parts.push({ name: 'value', valueCode: parentCode }); - parts.push({ name: 'description', valueString: await this.display(parentCode) }); + const parentDisplay = await this.display(parentCode); + if (parentDisplay) { + parts.push({ name: 'description', valueString: parentDisplay }); + } params.push({ name: 'property', part : [...parts]}); } } @@ -1175,7 +1178,10 @@ class FhirCodeSystemProvider extends BaseCSServices { let parts = []; parts.push({ name: 'code', valueCode: 'child' }); parts.push({ name: 'value', valueCode: childCode }); - parts.push({ name: 'description', valueString: await this.display(childCode) }); + const childDisplay = await this.display(childCode); + if (childDisplay) { + parts.push({ name: 'description', valueString: childDisplay }); + } params.push({ name: 'property', part : [...parts]}); } } From 28c28ef76e12e1509e94a9658cf75255a465a4f3 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:01:10 -0600 Subject: [PATCH 11/23] fix(expand): fix doubled cs.system() and non-standard example parameter name --- tests/tx/fix-iss12-expand-example-cs.test.js | 52 ++++++++++++++++++++ tx/workers/expand.js | 4 +- 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 tests/tx/fix-iss12-expand-example-cs.test.js diff --git a/tests/tx/fix-iss12-expand-example-cs.test.js b/tests/tx/fix-iss12-expand-example-cs.test.js new file mode 100644 index 00000000..a49ae6a9 --- /dev/null +++ b/tests/tx/fix-iss12-expand-example-cs.test.js @@ -0,0 +1,52 @@ +/** + * Regression test for ISS-12: expand.js doubled cs.system() and non-standard "example" parameter name. + */ + +const { ExpandWorker, ValueSetExpander } = require('../../tx/workers/expand'); +const { FhirCodeSystemProvider } = require('../../tx/cs/cs-cs'); +const { CodeSystem } = require('../../tx/library/codesystem'); +const ValueSet = require('../../tx/library/valueset'); +const { TxParameters } = require('../../tx/params'); +const { OperationContext } = require('../../tx/operation-context'); +const { SearchFilterText } = require('../../tx/library/designations'); +const { TestUtilities } = require('../test-utilities'); + +describe('ISS-12: $expand on content=example CodeSystem emits single-URL used-codesystem', () => { + test('does not double cs.system() or emit non-standard "example" parameter name', async () => { + const langDefs = await TestUtilities.loadLanguageDefinitions(); + const i18n = await TestUtilities.loadTranslations(langDefs); + const opContext = new OperationContext('en', i18n); + const exampleCs = new CodeSystem({ + resourceType: 'CodeSystem', + url: 'http://example.org/cs-example-iss12', + version: '4.0.1', + status: 'active', + content: 'example', + concept: [{ code: 'ex1', display: 'Example 1' }] + }); + const csProvider = new FhirCodeSystemProvider(opContext, exampleCs, []); + const mockLog = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + const mockProvider = { + getFhirVersion: () => '5.0.0', + getCodeSystemProvider: async () => csProvider, + loadSupplements: () => [], + findValueSet: async () => null + }; + const worker = new ExpandWorker(opContext, mockLog, mockProvider, langDefs, i18n); + const params = new TxParameters(langDefs, i18n); + const expander = new ValueSetExpander(worker, params); + const vs = new ValueSet({ + resourceType: 'ValueSet', + url: 'http://example.org/vs-example-iss12', + status: 'active', + compose: { include: [{ system: exampleCs.url, version: '4.0.1' }] } + }); + const expanded = await expander.expand(vs, new SearchFilterText(''), true); + const expParams = expanded.expansion.parameter || []; + expect(expParams.find(p => p.name === 'example')).toBeUndefined(); + expect(expParams.find(p => p.name === 'used-codesystem')).toEqual({ + name: 'used-codesystem', + valueUri: 'http://example.org/cs-example-iss12|4.0.1' + }); + }); +}); diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 9cff0b2e..0a0b7fd1 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -1191,9 +1191,9 @@ class ValueSetExpander { Extensions.addBoolean(exp, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed", true); Extensions.addString(exp, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason","This extension is based on a fragment of the code system " + cset.system); } else { - this.addParamUri(exp, cs.contentMode(), cs.system() + cs.system()+ (cs.version() ? '|' + cs.version(): "")); + this.addParamUri(exp, 'used-codesystem', cs.system() + (cs.version() ? '|' + cs.version() : '')); Extensions.addBoolean(exp, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed", true); - Extensions.addString(exp, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason","This extension is based on a fragment of the code system " + cset.system); + Extensions.addString(exp, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason", "This extension is based on a " + cs.contentMode() + " of the code system " + cset.system); } } From 189d2a916c69e4bc0c4d3fb46a6945cfa41e499d Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:03:32 -0600 Subject: [PATCH 12/23] fix(cs): support structural parent exists filter in FhirCodeSystemProvider --- .../tx/fix-iss18-parent-exists-filter.test.js | 83 +++++++++++++++++++ tx/cs/cs-cs.js | 37 ++++++++- 2 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 tests/tx/fix-iss18-parent-exists-filter.test.js diff --git a/tests/tx/fix-iss18-parent-exists-filter.test.js b/tests/tx/fix-iss18-parent-exists-filter.test.js new file mode 100644 index 00000000..ead9d5df --- /dev/null +++ b/tests/tx/fix-iss18-parent-exists-filter.test.js @@ -0,0 +1,83 @@ +/** + * Regression test for ISS-18: FhirCodeSystemProvider structural parent exists filter. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-18: cs-cs.js structural parent exists filter', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + const makeCs = (url, declareParent) => ({ + resourceType: 'CodeSystem', + url, + version: '1.0', + status: 'active', + content: 'complete', + hierarchyMeaning: 'is-a', + ...(declareParent ? { property: [{ code: 'parent', uri: 'http://hl7.org/fhir/concept-properties#parent', type: 'code' }] } : {}), + concept: [{ code: 'R', display: 'Root', concept: [{ code: 'C1', display: 'Child 1' }] }] + }); + + test.each([ + ['with declared standard parent property', 'http://example.org/cs-hier-iss18a', true], + ['without declared parent property', 'http://example.org/cs-hier-iss18b', false] + ])('%s: parent exists=true returns C1 and exists=false returns R', async (_label, url, declareParent) => { + const cs = makeCs(url, declareParent); + const resTrue = await post('ValueSet/$expand', [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', url: url + '/vs-t', status: 'active', compose: { include: [{ system: url, filter: [{ property: 'parent', op: 'exists', value: 'true' }] }] } } }, + { name: 'tx-resource', resource: cs } + ]); + expect(resTrue.status).toBe(200); + expect(resTrue.body.expansion.contains.map(c => c.code)).toEqual(['C1']); + + const resFalse = await post('ValueSet/$expand', [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', url: url + '/vs-f', status: 'active', compose: { include: [{ system: url, filter: [{ property: 'parent', op: 'exists', value: 'false' }] }] } } }, + { name: 'tx-resource', resource: cs } + ]); + expect(resFalse.status).toBe(200); + expect(resFalse.body.expansion.contains.map(c => c.code)).toEqual(['R']); + }); + + test('declared built-in status/inactive/deprecated properties retain known-property semantics', async () => { + const url = 'http://example.org/cs-known-props-iss18'; + const cs = { + resourceType: 'CodeSystem', + url, + version: '1.0', + status: 'active', + content: 'complete', + property: [ + { code: 'status', uri: 'http://hl7.org/fhir/concept-properties#status', type: 'code' }, + { code: 'inactive', uri: 'http://hl7.org/fhir/concept-properties#inactive', type: 'boolean' }, + { code: 'deprecated', uri: 'http://hl7.org/fhir/concept-properties#deprecated', type: 'boolean' } + ], + concept: [ + { code: 'A', display: 'Active (no explicit property)' }, + { code: 'D', display: 'Deprecated via status', property: [{ code: 'status', valueCode: 'deprecated' }] } + ] + }; + const res = await post('ValueSet/$expand', [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', url: url + '/vs-dep', status: 'active', compose: { include: [{ system: url, filter: [{ property: 'deprecated', op: 'in', value: 'true' }] }] } } }, + { name: 'tx-resource', resource: cs } + ]); + expect(res.status).toBe(200); + expect(res.body.expansion.contains.map(c => c.code)).toEqual(['D']); + }); +}); diff --git a/tx/cs/cs-cs.js b/tx/cs/cs-cs.js index 0a5a9b8c..3e040b09 100644 --- a/tx/cs/cs-cs.js +++ b/tx/cs/cs-cs.js @@ -1226,8 +1226,8 @@ class FhirCodeSystemProvider extends BaseCSServices { return true; } - // Child existence filter - if (prop === 'child' && op === 'exists') { + // Child and parent existence filters + if ((prop === 'child' || prop === 'parent') && op === 'exists') { return true; } @@ -1525,10 +1525,13 @@ class FhirCodeSystemProvider extends BaseCSServices { if (prop === 'child' && op === 'exists' && !this.redefinesStandardProperty('child')) { results = await this._handleChildExistsFilter(filterContext, value); } + if (prop === 'parent' && op === 'exists' && !this.redefinesStandardProperty('parent')) { + results = await this._handleParentExistsFilter(filterContext, value); + } // Handle property-based filters const propertyDefs = this.propertyDefinitions(); - if (propertyDefs && !(prop === 'child' && results)) { + if (propertyDefs && !((prop === 'child' || prop === 'parent') && results)) { const propertyDef = propertyDefs.find(p => p.code === prop); if (propertyDef) { results = await this._handlePropertyFilter(filterContext, propertyDef, op, value); @@ -1572,7 +1575,7 @@ class FhirCodeSystemProvider extends BaseCSServices { if (prop === 'concept' || prop === 'code') { return op === 'is-a' || op === 'descendent-of' || op === 'descendent-leaf' || op === 'is-not-a' || op === 'regex'; } - if (prop === 'child' && op === 'exists') { + if ((prop === 'child' || prop === 'parent') && op === 'exists') { return true; } const propertyDefs = this.propertyDefinitions(); @@ -1793,6 +1796,32 @@ class FhirCodeSystemProvider extends BaseCSServices { return results; } + /** + * Handle parent exists filter (over nested concept hierarchy and explicit parent properties) + * @param {FilterExecutionContext} filterContext - Filter context + * @param {string} value - 'true' or 'false' + * @returns {Promise} Filter results + * @private + */ + async _handleParentExistsFilter(filterContext, value) { + const results = new FhirCodeSystemProviderFilterContext(); + const wantParents = (value === 'true'); + + const allCodes = this.codeSystem.getAllCodes(); + for (const code of allCodes) { + this.opContext.deadCheck('cs:parentExistsFilter'); + const hasParents = this.codeSystem.getParents(code).length > 0; + if (hasParents === wantParents) { + const concept = this.codeSystem.getConceptByCode(code); + if (concept) { + results.add(concept, 0); + } + } + } + + return results; + } + /** * Handle property-based filter * @param {FilterExecutionContext} filterContext - Filter context From 8af47ac61fee94e17753cd59d605f180a4b8388d Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:03:43 -0600 Subject: [PATCH 13/23] fix(lookup): pass null for missing version so system|version lookups succeed --- .../fix-iss19-lookup-system-version.test.js | 43 +++++++++++++++++++ tx/provider.js | 6 +-- tx/workers/lookup.js | 5 ++- 3 files changed, 49 insertions(+), 5 deletions(-) create mode 100644 tests/tx/fix-iss19-lookup-system-version.test.js diff --git a/tests/tx/fix-iss19-lookup-system-version.test.js b/tests/tx/fix-iss19-lookup-system-version.test.js new file mode 100644 index 00000000..043fb4c0 --- /dev/null +++ b/tests/tx/fix-iss19-lookup-system-version.test.js @@ -0,0 +1,43 @@ +/** + * Regression test for ISS-19: $lookup accepts system|version without a separate version parameter. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-19: $lookup accepts system|version without separate version parameter', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const param = (res, name) => (res.body.parameter || []).find(p => p.name === name); + + test('GET /CodeSystem/$lookup?system=...|5.0.0&code=male succeeds with 200', async () => { + const res = await request(app) + .get(`${R5}/CodeSystem/$lookup?system=http%3A%2F%2Fhl7.org%2Ffhir%2Fadministrative-gender%7C5.0.0&code=male`) + .set('Accept', 'application/fhir+json'); + expect(res.status).toBe(200); + expect(param(res, 'display').valueString).toBe('Male'); + }); + + test('POST /CodeSystem/$lookup with coding.system carrying |version succeeds with 200', async () => { + const res = await request(app) + .post(`${R5}/CodeSystem/$lookup`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ + resourceType: 'Parameters', + parameter: [{ name: 'coding', valueCoding: { system: 'http://hl7.org/fhir/administrative-gender|5.0.0', code: 'male' } }] + }); + expect(res.status).toBe(200); + expect(param(res, 'display').valueString).toBe('Male'); + }); +}); diff --git a/tx/provider.js b/tx/provider.js index c1de8309..8ceb5a69 100644 --- a/tx/provider.js +++ b/tx/provider.js @@ -205,7 +205,7 @@ class Provider { if (system.includes("|")) { const url = system.substring(0, system.indexOf("|")); const v = system.substring(system.indexOf("|")+1); - if (version == null || v === version) { + if (!version || v === version) { version = v; } else { throw new TerminologyError(`Version inconsistent in ${system}: ${v} vs ${version}`); @@ -647,7 +647,7 @@ class Provider { if (system.includes("|")) { const url = system.substring(0, system.indexOf("|")); const v = system.substring(system.indexOf("|")+1); - if (version == null || v === version) { + if (!version || v === version) { version = v; } else { throw new TerminologyError(`Version inconsistent in ${system}: ${v} vs ${version}`); @@ -724,7 +724,7 @@ class Provider { if (system.includes("|")) { const url = system.substring(0, system.indexOf("|")); const v = system.substring(system.indexOf("|")+1); - if (version == null || v === version) { + if (!version || v === version) { version = v; } else { throw new TerminologyError(`Version inconsistent in ${system}: ${v} vs ${version}`); diff --git a/tx/workers/lookup.js b/tx/workers/lookup.js index f6d4baf9..e5553858 100644 --- a/tx/workers/lookup.js +++ b/tx/workers/lookup.js @@ -108,13 +108,14 @@ class LookupWorker extends TerminologyWorker { } // Allow complete or fragment content modes, nullOk = true to handle not-found ourselves - csProvider = await this.findCodeSystem(coding.system, coding.version || '', txp, ['complete', 'fragment'], true); + csProvider = await this.findCodeSystem(coding.system, coding.version || null, txp, ['complete', 'fragment'], + null, true, false, false, txp.supplements); this.seeSourceProvider(csProvider, coding.system); code = coding.code; } else if (params.has('system') && params.has('code')) { // system + code parameters - csProvider = await this.findCodeSystem(params.get('system'), params.get('version') || '', txp, ['complete', 'fragment'], + csProvider = await this.findCodeSystem(params.get('system'), params.get('version') || null, txp, ['complete', 'fragment'], null, true, false, false, txp.supplements); this.seeSourceProvider(csProvider, params.get('system')); code = params.get('code'); From 2c6d49694a42a3d58d83be4ec01d6fbd5b6b0e91 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:04:11 -0600 Subject: [PATCH 14/23] fix(ecl): reject 4 malformed ECL 2.2 constructs (cardinality, history, empty term, non-ASCII ws) --- tests/tx/fix-iss22-ecl-grammar.test.js | 39 ++++++++++++++++++++++++++ tx/sct/ecl.js | 21 ++++++++++++-- 2 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 tests/tx/fix-iss22-ecl-grammar.test.js diff --git a/tests/tx/fix-iss22-ecl-grammar.test.js b/tests/tx/fix-iss22-ecl-grammar.test.js new file mode 100644 index 00000000..2e576d12 --- /dev/null +++ b/tests/tx/fix-iss22-ecl-grammar.test.js @@ -0,0 +1,39 @@ +/** + * Regression test for ISS-22: ECL 2.2 lexer/parser rejects inverted cardinality, repeated + * history supplements, empty pipe terms, and non-ASCII whitespace. + */ + +const { ECLLexer, ECLParser } = require('../../tx/sct/ecl'); + +function parseEcl(expr) { + const tokens = new ECLLexer(expr).tokenize(); + return new ECLParser(tokens).parse(); +} + +describe('ISS-22: ECL 2.2 lexer/parser rejects 4 malformed constructs', () => { + test.each([ + ['inverted cardinality [5..2]', '<< 38341003 : [5..2] 363698007 = << 123037004'], + ['repeated {{ + HISTORY-* }}', '<< 763158003 {{ + HISTORY-MIN }} {{ + HISTORY-MAX }}'], + ['history supplement followed by concept filter', '<< 763158003 {{ + HISTORY-MIN }} {{ C active=1 }}'], + ['history supplement followed by description filter', '<< 763158003 {{ + HISTORY-MIN }} {{ D term="foo" }}'], + ['history supplement followed by member filter', '^ 700043003 {{ + HISTORY-MIN }} {{ M active=1 }}'], + ['history supplement with comma-chained filter', '<< 763158003 {{ + HISTORY-MIN, C active=1 }}'], + ['empty pipe term ||', '<< 123037004 ||'], + ['whitespace-only pipe term | |', '<< 123037004 | |'], + ['non-ASCII whitespace NBSP \\u00A0', '<<\u00a073211009'] + ])('rejects %s', (_label, expr) => { + expect(() => parseEcl(expr)).toThrow(); + }); + + test.each([ + ['valid cardinality [1..2]', '<< 38341003 : [1..2] 363698007 = << 123037004'], + ['valid open cardinality [2..*]', '<< 38341003 : [2..*] 363698007 = << 123037004'], + ['single {{ + HISTORY-MIN }}', '<< 763158003 {{ + HISTORY-MIN }}'], + ['concept filter then {{ + HISTORY-MIN }}', '<< 763158003 {{ C active=1 }} {{ + HISTORY-MIN }}'], + ['member + concept filter then {{ + HISTORY-MIN }}', '^ 700043003 {{ M active=1 }} {{ C active=1 }} {{ + HISTORY-MIN }}'], + ['non-empty pipe term', '<< 123037004 |Body structure|'], + ['ASCII whitespace', '<< \t\n 73211009'] + ])('accepts %s', (_label, expr) => { + expect(() => parseEcl(expr)).not.toThrow(); + }); +}); diff --git a/tx/sct/ecl.js b/tx/sct/ecl.js index ed3f9bea..8aa046cf 100644 --- a/tx/sct/ecl.js +++ b/tx/sct/ecl.js @@ -135,7 +135,7 @@ class ECLLexer { } skipWhitespace() { - while (this.current && /\s/.test(this.current)) { + while (this.current && /[ \t\r\n]/.test(this.current)) { this.advance(); } } @@ -167,7 +167,11 @@ class ECLLexer { } this.advance(); // Skip closing | - return value.trim(); + const trimmed = value.trim(); + if (!trimmed) { + this.error('Empty term between | delimiters'); + } + return trimmed; } readString() { @@ -222,7 +226,7 @@ class ECLLexer { getNextToken() { while (this.current) { - if (/\s/.test(this.current)) { + if (/[ \t\r\n]/.test(this.current)) { this.skipWhitespace(); continue; } @@ -717,8 +721,12 @@ class ECLParser { // into focus.memberFilters; the others are parsed into focus-level // `filters` and rejected (as unsupported) at evaluation time. const filters = []; + let hasHistory = false; while (this.match(ECLTokenType.LFILTER)) { const fc = this.parseFilterConstraint(); + if (hasHistory) { + throw new Error('A history supplement ({{ + HISTORY... }}) must appear last and at most once per sub-expression constraint'); + } if (fc.kind === 'M') { if (focus.type !== ECLNodeType.MEMBER_OF) { throw new Error('A member filter ({{ M ... }}) may only follow a memberOf (^) expression constraint'); @@ -727,6 +735,9 @@ class ECLParser { throw new Error('A member filter ({{ M ... }}) must precede any description, concept or history filter'); } focus.memberFilters = (focus.memberFilters || []).concat(fc.filters); + } else if (fc.kind === '+') { + hasHistory = true; + filters.push(fc); } else { filters.push(fc); } @@ -1563,6 +1574,10 @@ class ECLParser { this.expect(ECLTokenType.RBRACKET); + if (max !== '*' && max < min) { + this.error(`Invalid cardinality [${min}..${max}]: maximum cannot be less than minimum`); + } + return { type: ECLNodeType.CARDINALITY, min, From 38ca3578fe9a84ade0e4061655d03d186edb4220 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:04:26 -0600 Subject: [PATCH 15/23] fix(expand): include primaryResources in sessionless additionalResources for cycle detection --- tests/tx/fix-iss29-sessionless-cycle.test.js | 57 ++++++++++++++++++++ tx/workers/worker.js | 4 +- 2 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 tests/tx/fix-iss29-sessionless-cycle.test.js diff --git a/tests/tx/fix-iss29-sessionless-cycle.test.js b/tests/tx/fix-iss29-sessionless-cycle.test.js new file mode 100644 index 00000000..2b17b322 --- /dev/null +++ b/tests/tx/fix-iss29-sessionless-cycle.test.js @@ -0,0 +1,57 @@ +/** + * Regression test for ISS-29: sessionless $expand includes primaryResources in additionalResources + * so circular inline valueSet -> tx-resource -> inline valueSet triggers VALUESET_CIRCULAR_REFERENCE. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-29: sessionless $expand includes primary valueSet in additionalResources', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test('circular inline valueSet -> tx-resource -> inline valueSet reports VALUESET_CIRCULAR_REFERENCE', async () => { + const res = await request(app) + .post(`${R5}/ValueSet/$expand`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ + resourceType: 'Parameters', + parameter: [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-cycle-a-iss29', + status: 'active', + compose: { include: [{ valueSet: ['http://example.org/vs-cycle-b-iss29'] }] } + } + }, + { + name: 'tx-resource', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-cycle-b-iss29', + status: 'active', + compose: { include: [{ valueSet: ['http://example.org/vs-cycle-a-iss29'] }] } + } + } + ] + }); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + const msgIds = (res.body.issue || []).flatMap(i => (i.extension || []) + .filter(e => e.url === 'http://hl7.org/fhir/StructureDefinition/operationoutcome-message-id') + .map(e => e.valueString)); + expect(msgIds).toContain('VALUESET_CIRCULAR_REFERENCE'); + }); +}); diff --git a/tx/workers/worker.js b/tx/workers/worker.js index a392ef39..3d76f26e 100644 --- a/tx/workers/worker.js +++ b/tx/workers/worker.js @@ -940,8 +940,8 @@ class TerminologyWorker { } this.additionalResourcesCacheId = cacheId; } else { - // No cache-id, just use the tx-resources directly - this.additionalResources = txResources; + // No cache-id, use both tx-resources and primary inline resources directly + this.additionalResources = txResources.concat(primaryResources); } } From 84a30674c985ee4a9fe960fff091f96b10276545 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:04:42 -0600 Subject: [PATCH 16/23] fix(expand): retain used-supplement parameter when offset >= total --- .../fix-iss30-offset-used-supplement.test.js | 78 +++++++++++++++++++ tx/workers/expand.js | 10 +++ 2 files changed, 88 insertions(+) create mode 100644 tests/tx/fix-iss30-offset-used-supplement.test.js diff --git a/tests/tx/fix-iss30-offset-used-supplement.test.js b/tests/tx/fix-iss30-offset-used-supplement.test.js new file mode 100644 index 00000000..24557cbc --- /dev/null +++ b/tests/tx/fix-iss30-offset-used-supplement.test.js @@ -0,0 +1,78 @@ +/** + * Regression test for ISS-30: $expand retains used-supplement when offset >= total. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-30: $expand retains used-supplement when offset >= total', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test('offset=10 still emits used-supplement parameter', async () => { + const res = await request(app) + .post(`${R5}/ValueSet/$expand`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ + resourceType: 'Parameters', + parameter: [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-supp-iss30', + status: 'active', + extension: [{ + url: 'http://hl7.org/fhir/StructureDefinition/valueset-supplement', + valueCanonical: 'http://example.org/cs-supp-iss30|1.0' + }], + compose: { include: [{ system: 'http://example.org/cs-supp-base-iss30', concept: [{ code: 'A' }, { code: 'B' }] }] } + } + }, + { name: 'offset', valueInteger: 10 }, + { name: 'count', valueInteger: 5 }, + { + name: 'tx-resource', + resource: { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-supp-base-iss30', + version: '1.0', + status: 'active', + content: 'complete', + concept: [{ code: 'A', display: 'Alpha' }, { code: 'B', display: 'Beta' }] + } + }, + { + name: 'tx-resource', + resource: { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-supp-iss30', + version: '1.0', + status: 'active', + content: 'supplement', + supplements: 'http://example.org/cs-supp-base-iss30|1.0', + concept: [ + { code: 'A', designation: [{ language: 'de', value: 'Alpha DE' }] }, + { code: 'B', designation: [{ language: 'de', value: 'Beta DE' }] } + ] + } + } + ] + }); + expect(res.status).toBe(200); + expect(res.body.expansion.parameter).toContainEqual({ + name: 'used-supplement', + valueUri: 'http://example.org/cs-supp-iss30|1.0' + }); + }); +}); diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 0a0b7fd1..9552857d 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -1416,6 +1416,11 @@ class ValueSetExpander { this.checkProviderCanonicalStatus(expansion, cs, this.valueSet); const sv = this.canonical(await cs.system(), await cs.version()); this.addParamUri(expansion, 'used-codesystem', sv); + if (!this.noDetails && typeof cs.listSupplements === 'function') { + for (const supp of cs.listSupplements(false)) { + this.reportedSupplements.add(supp); + } + } for (const u of cset.valueSet || []) { await this.worker.checkAndYield('processCodes#2'); @@ -1918,6 +1923,11 @@ class ValueSetExpander { this.checkResourceCanonicalStatus(expansion, cs, this.valueSet); const sv = this.canonical(await cs.system(), await cs.version()); this.addParamUri(expansion, 'used-codesystem', sv); + if (!this.noDetails && typeof cs.listSupplements === 'function') { + for (const supp of cs.listSupplements(false)) { + this.reportedSupplements.add(supp); + } + } for (const u of cset.valueSet || []) { await this.worker.checkAndYield('processCodes#3'); From e06be1ca92485eb4304970c81c4c27b88047fd98 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:05:11 -0600 Subject: [PATCH 17/23] fix(validate): unwrap ValueSet wrapper and call checkCanonicalStatusCS on providers --- tests/tx/fix-iss31-canonical-status.test.js | 103 ++++++++++++++++++++ tx/workers/validate.js | 17 ++-- 2 files changed, 112 insertions(+), 8 deletions(-) create mode 100644 tests/tx/fix-iss31-canonical-status.test.js diff --git a/tests/tx/fix-iss31-canonical-status.test.js b/tests/tx/fix-iss31-canonical-status.test.js new file mode 100644 index 00000000..310378af --- /dev/null +++ b/tests/tx/fix-iss31-canonical-status.test.js @@ -0,0 +1,103 @@ +/** + * Regression test for ISS-31: checkCanonicalStatusFull unwraps ValueSet wrapper and + * CodeSystemProvider call sites use checkCanonicalStatusCS. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-31: checkCanonicalStatus* unwraps ValueSet wrapper and uses checkCanonicalStatusCS', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + const param = (res, name) => (res.body.parameter || []).find(p => p.name === name); + const msgIdsOf = (res) => { + const p = param(res, 'issues'); + const issues = (p && p.resource && p.resource.issue) || []; + return issues.flatMap(i => (i.extension || []) + .filter(e => e.url === 'http://hl7.org/fhir/StructureDefinition/operationoutcome-message-id') + .map(e => e.valueString)); + }; + + test('experimental ValueSet referencing experimental CodeSystem does not emit spurious MSG_EXPERIMENTAL', async () => { + const res = await post('ValueSet/$validate-code', [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-exp-iss31', + version: '1.0', + status: 'active', + experimental: true, + compose: { include: [{ system: 'http://example.org/cs-exp-iss31' }] } + } + }, + { name: 'system', valueUri: 'http://example.org/cs-exp-iss31' }, + { name: 'code', valueCode: 'A' }, + { name: 'display', valueString: 'Alpha' }, + { + name: 'tx-resource', + resource: { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-exp-iss31', + version: '1.0', + status: 'active', + experimental: true, + content: 'complete', + concept: [{ code: 'A', display: 'Alpha' }] + } + } + ]); + expect(res.status).toBe(200); + expect(param(res, 'result').valueBoolean).toBe(true); + expect(msgIdsOf(res)).not.toContain('MSG_EXPERIMENTAL'); + }); + + test('active ValueSet excluding from draft CodeSystem emits MSG_DRAFT_SRC_STATUS', async () => { + const res = await post('ValueSet/$validate-code', [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-exc-draft-iss31', + version: '1.0', + status: 'active', + compose: { + include: [{ system: 'http://hl7.org/fhir/administrative-gender' }], + exclude: [{ system: 'http://example.org/cs-draft-iss31', concept: [{ code: 'B' }] }] + } + } + }, + { name: 'system', valueUri: 'http://hl7.org/fhir/administrative-gender' }, + { name: 'code', valueCode: 'male' }, + { + name: 'tx-resource', + resource: { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-draft-iss31', + version: '1.0', + status: 'draft', + content: 'complete', + concept: [{ code: 'A', display: 'Alpha' }, { code: 'B', display: 'Beta' }] + } + } + ]); + expect(res.status).toBe(200); + expect(msgIdsOf(res)).toContain('MSG_DRAFT_SRC_STATUS'); + }); +}); diff --git a/tx/workers/validate.js b/tx/workers/validate.js index 52707635..ef0a7022 100644 --- a/tx/workers/validate.js +++ b/tx/workers/validate.js @@ -80,24 +80,25 @@ class ValueSetChecker { checkCanonicalStatusFull(path, op, rtype, vurl, pid, status, standardsStatus, experimental, source) { if (op !== null) { + const src = source && source.jsonObj ? source.jsonObj : source; if (standardsStatus === 'deprecated') { op.addIssueIfNew(new Issue('information', 'business-rule', '', 'MSG_DEPRECATED', this.worker.i18n.translate('MSG_DEPRECATED', this.params.HTTPLanguages, [vurl, '', rtype]), 'status-check'), false); } else if (standardsStatus === 'withdrawn') { op.addIssueIfNew(new Issue('information', 'business-rule', '', 'MSG_WITHDRAWN', this.worker.i18n.translate('MSG_WITHDRAWN', this.params.HTTPLanguages, [vurl, '', rtype]), 'status-check'), false); } else if (status === 'retired') { op.addIssueIfNew(new Issue('information', 'business-rule', '', 'MSG_RETIRED', this.worker.i18n.translate('MSG_RETIRED', this.params.HTTPLanguages, [vurl, '', rtype]), 'status-check'), false); - } else if (source !== null) { - if (experimental && !source.experimental) { + } else if (src !== null && src !== undefined) { + if (experimental && !src.experimental) { op.addIssueIfNew(new Issue('information', 'business-rule', '', 'MSG_EXPERIMENTAL', this.worker.i18n.translate('MSG_EXPERIMENTAL', this.params.HTTPLanguages, [vurl, '', rtype]), 'status-check'), false); } else if ((status === 'draft' || standardsStatus === 'draft') && - !((source.status === 'draft') || (Extensions.readString(source, 'http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status') === 'draft'))) { + !((src.status === 'draft') || (Extensions.readString(src, 'http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status') === 'draft'))) { // MSG_DRAFT_SRC_STATUS names the referring resource's status and type as well as its // url, so the reader can see why the reference is reported at all: a resource that is // not draft pointing at one that is. Matches ValueSetProcessBase.checkCanonical in the // java implementation, so both terminology services report this the same way op.addIssueIfNew(new Issue('information', 'business-rule', '', 'MSG_DRAFT_SRC_STATUS', this.worker.i18n.translate('MSG_DRAFT_SRC_STATUS', this.params.HTTPLanguages, - [vurl, this.worker.makeVurl(source), rtype, source.status, source.resourceType]), 'status-check'), false); + [vurl, this.worker.makeVurl(src), rtype, src.status, src.resourceType]), 'status-check'), false); } } } @@ -632,7 +633,7 @@ class ValueSetChecker { } else { defLang.value = cs.defLang(); this.worker.opContext.addNote(this.valueSet, 'Using CodeSystem "' + this.worker.renderer.displayCoded(cs) + '" (content = ' + cs.contentMode() + ')', this.indentCount); - await this.checkCanonicalStatus(path, op, cs, this.valueSet); + await this.checkCanonicalStatusCS(path, op, cs, this.valueSet); ver.value = cs.version(); contentMode.value = cs.contentMode(); let ctxt = await cs.locate(code, await this.batchPrefetched(cs)); @@ -730,7 +731,7 @@ class ValueSetChecker { } } else { defLang.value = cs.defLang(); - this.checkCanonicalStatus(path, op, cs, this.valueSet); + await this.checkCanonicalStatusCS(path, op, cs, this.valueSet); ver.value = cs.version(); contentMode.value = cs.contentMode(); let ctxt = cs.locate(code); @@ -916,7 +917,7 @@ class ValueSetChecker { // this server doesn't have), not with the server throw await this.unknownExcludeSystem(cc); } - await this.checkCanonicalStatus(path, op, cs, this.valueSet); + await this.checkCanonicalStatusCS(path, op, cs, this.valueSet); this.worker.checkSupplements(cs, cc, this.worker.requiredSupplements, this.worker.usedSupplements); contentMode.value = cs.contentMode(); let msg = ''; @@ -1001,7 +1002,7 @@ class ValueSetChecker { } } defLang.value = cs.defLang(); - await this.checkCanonicalStatus(path, op, cs, this.valueSet); + await this.checkCanonicalStatusCS(path, op, cs, this.valueSet); ver.value = cs.version(); contentMode.value = cs.contentMode(); let msg = ''; From d74ba5117f6c1cef2d543a433bf23c52ea992d5a Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:05:26 -0600 Subject: [PATCH 18/23] fix(worker): avoid literal 'null' on versionless CS and deduplicate VALUESET_VERSION_CHECK --- tests/tx/fix-iss32-check-version.test.js | 96 ++++++++++++++++++++++++ translations/Messages.properties | 1 + tx/workers/worker.js | 7 +- 3 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 tests/tx/fix-iss32-check-version.test.js diff --git a/tests/tx/fix-iss32-check-version.test.js b/tests/tx/fix-iss32-check-version.test.js new file mode 100644 index 00000000..cddaa90c --- /dev/null +++ b/tests/tx/fix-iss32-check-version.test.js @@ -0,0 +1,96 @@ +/** + * Regression test for ISS-32: checkVersion avoids literal 'null' on versionless CodeSystems + * and deduplicates VALUESET_VERSION_CHECK issues. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-32: checkVersion avoids literal "null" and deduplicates VALUESET_VERSION_CHECK', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + const param = (res, name) => (res.body.parameter || []).find(p => p.name === name); + const msgIdsOf = (res) => { + const p = param(res, 'issues'); + const issues = (p && p.resource && p.resource.issue) || []; + return issues.flatMap(i => (i.extension || []) + .filter(e => e.url === 'http://hl7.org/fhir/StructureDefinition/operationoutcome-message-id') + .map(e => e.valueString)); + }; + + test('versionless CodeSystem failing check-system-version does not interpolate literal "null"', async () => { + const res = await post('ValueSet/$expand', [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs/ver-null-iss32', + status: 'active', + compose: { include: [{ system: 'http://example.org/cs/ver-null-iss32' }] } + } + }, + { + name: 'tx-resource', + resource: { + resourceType: 'CodeSystem', + url: 'http://example.org/cs/ver-null-iss32', + status: 'active', + content: 'complete', + concept: [{ code: 'A', display: 'Alpha' }] + } + }, + { name: 'check-system-version', valueCanonical: 'http://example.org/cs/ver-null-iss32|3.0.0' } + ]); + expect(res.status).toBe(400); + const text = res.body.issue[0].details.text; + expect(text).not.toContain("'null'"); + expect(text).toContain('(no version)'); + }); + + test('$validate-code with conflicting force/check-system-version emits VALUESET_VERSION_CHECK only once', async () => { + const cs = (version) => ({ + resourceType: 'CodeSystem', + url: 'http://example.org/cs-ver-iss32', + version, + status: 'active', + content: 'complete', + concept: [{ code: 'A', display: 'Alpha' }, { code: 'B', display: 'Beta' }] + }); + const res = await post('ValueSet/$validate-code', [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-ver-iss32', + status: 'active', + compose: { include: [{ system: 'http://example.org/cs-ver-iss32', version: '1.0.0', concept: [{ code: 'A' }] }] } + } + }, + { name: 'system', valueUri: 'http://example.org/cs-ver-iss32' }, + { name: 'code', valueCode: 'B' }, + { name: 'force-system-version', valueCanonical: 'http://example.org/cs-ver-iss32|2.0.0' }, + { name: 'check-system-version', valueCanonical: 'http://example.org/cs-ver-iss32|1.0.0' }, + { name: 'tx-resource', resource: cs('1.0.0') }, + { name: 'tx-resource', resource: cs('2.0.0') } + ]); + expect(res.status).toBe(200); + const verIssues = msgIdsOf(res).filter(id => id === 'VALUESET_VERSION_CHECK'); + expect(verIssues).toHaveLength(1); + }); +}); diff --git a/translations/Messages.properties b/translations/Messages.properties index 671bf565..f5e18c99 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -1616,6 +1616,7 @@ CONCEPT_DEPRECATED_IN_VALUESET = The presence of the concept ''{1}'' in the syst SYSTEM_VERSION_MULTIPLE_OVERRIDE = Multiple version overrides found for system {0}: ''{1}'', ''{2}'' SYSTEM_VERSION_MULTIPLE_DEFAULT = Multiple default versions found for system {0}: ''{1}'', ''{2}'' VALUESET_VERSION_CHECK = The version ''{1}'' is not allowed for system ''{0}'': required to be ''{2}'' by a version-check parameter +TX_NO_VERSION = (no version) VALUESET_VALUE_MISMATCH = The code system ''{0}'' version ''{1}'' in the ValueSet include is different to the one in the value (''{2}'') VALUESET_VALUE_MISMATCH_CHANGED = The code system ''{0}'' version ''{1}'' resulting from the version ''{2}'' in the ValueSet include is different to the one in the value (''{3}'') VALUESET_VALUE_MISMATCH_DEFAULT = The code system ''{0}'' version ''{1}'' for the versionless include in the ValueSet include is different to the one in the value (''{3}'') diff --git a/tx/workers/worker.js b/tx/workers/worker.js index 3d76f26e..7c7e7530 100644 --- a/tx/workers/worker.js +++ b/tx/workers/worker.js @@ -1300,9 +1300,12 @@ class TerminologyWorker { for (let t of list) { if (t.mode === 'check' && !t.vs) { if (!VersionUtilities.versionMatchesByAlgorithm(t.version, version, versionAlgorithm)) { - let issue = new Issue("error", "exception", null, 'VALUESET_VERSION_CHECK', this.i18n.translate('VALUESET_VERSION_CHECK', params.FHTTPLanguages, [url, version, t.version]), 'version-error', 400); + const displayVersion = (version === null || version === undefined || version === '') + ? this.i18n.translate('TX_NO_VERSION', params.FHTTPLanguages) + : version; + let issue = new Issue("error", "exception", null, 'VALUESET_VERSION_CHECK', this.i18n.translate('VALUESET_VERSION_CHECK', params.FHTTPLanguages, [url, displayVersion, t.version]), 'version-error', 400); if (op) { - op.addIssue(issue); + op.addIssueIfNew(issue); } else { throw issue; } From cbc9cd7ec4697f249deb08c8f6146cef14c13db7 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:05:42 -0600 Subject: [PATCH 19/23] fix(validate): avoid duplicating valid display choices on abstract=false and compose.exclude --- .../fix-iss33-validate-display-dedup.test.js | 83 +++++++++++++++++++ tx/workers/validate.js | 4 +- 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 tests/tx/fix-iss33-validate-display-dedup.test.js diff --git a/tests/tx/fix-iss33-validate-display-dedup.test.js b/tests/tx/fix-iss33-validate-display-dedup.test.js new file mode 100644 index 00000000..c93416b8 --- /dev/null +++ b/tests/tx/fix-iss33-validate-display-dedup.test.js @@ -0,0 +1,83 @@ +/** + * Regression test for ISS-33: $validate-code does not repeat valid display choices + * on abstract=false or compose.exclude. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-33: $validate-code does not repeat valid display choices on abstract=false or compose.exclude', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const post = (op, parameter) => + request(app).post(`${R5}/${op}`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ resourceType: 'Parameters', parameter }); + + const param = (res, name) => (res.body.parameter || []).find(p => p.name === name); + + const csAbs = { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-abs-iss33', + version: '1.0', + status: 'active', + content: 'complete', + property: [{ code: 'notSelectable', uri: 'http://hl7.org/fhir/concept-properties#notSelectable', type: 'boolean' }], + concept: [{ + code: 'B', + display: 'Beta Root', + designation: [{ language: 'fr', value: 'Racine Beta' }], + property: [{ code: 'notSelectable', valueBoolean: true }] + }] + }; + + test('abstract=false reports 2 display choices, not 4', async () => { + const res = await post('CodeSystem/$validate-code', [ + { name: 'url', valueUri: csAbs.url }, + { name: 'code', valueCode: 'B' }, + { name: 'display', valueString: 'Wrong' }, + { name: 'abstract', valueBoolean: false }, + { name: 'tx-resource', resource: csAbs } + ]); + expect(res.status).toBe(200); + const msg = param(res, 'message').valueString; + expect(msg).toContain('one of 2 choices'); + expect(msg).not.toContain('one of 4 choices'); + }); + + test('compose.exclude reports 2 display choices, not 6', async () => { + const res = await post('ValueSet/$validate-code', [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-exc-iss33', + status: 'active', + compose: { + include: [{ system: csAbs.url }], + exclude: [{ system: csAbs.url, concept: [{ code: 'B' }] }] + } + } + }, + { name: 'system', valueUri: csAbs.url }, + { name: 'code', valueCode: 'B' }, + { name: 'display', valueString: 'Wrong' }, + { name: 'tx-resource', resource: csAbs } + ]); + expect(res.status).toBe(200); + const msg = param(res, 'message').valueString; + expect(msg).toContain('one of 2 choices'); + expect(msg).not.toContain('one of 6 choices'); + }); +}); diff --git a/tx/workers/validate.js b/tx/workers/validate.js index ef0a7022..1b6107fb 100644 --- a/tx/workers/validate.js +++ b/tx/workers/validate.js @@ -921,7 +921,8 @@ class ValueSetChecker { this.worker.checkSupplements(cs, cc, this.worker.requiredSupplements, this.worker.usedSupplements); contentMode.value = cs.contentMode(); let msg = ''; - excluded = (system === '%%null%%' || cs.system() === system) && await this.checkConceptSet(path, 'not in', cs, cc, code, displays, this.valueSet, msg, inactive, normalForm, vstatus, op, vcc); + const excludeDisplays = new Designations(this.worker.i18n.languageDefinitions); + excluded = (system === '%%null%%' || cs.system() === system) && await this.checkConceptSet(path, 'not in', cs, cc, code, excludeDisplays, this.valueSet, msg, inactive, normalForm, vstatus, op, vcc); if (msg) { messages.push(msg); } @@ -1336,6 +1337,7 @@ class ValueSetChecker { if (!c.version && mode == 'codeableConcept' && prov.version()) { c.version = prov.version(); } + list.clear(); await this.worker.listDisplaysFromCodeSystem(list, prov, ctxt.context); // the code resolved in the code system, so its status is known whether or not it // turns out to be in the value set. check() only picks the status up on the paths From 9733377bc76f77495d5f9b13864415ddb3a7c49c Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:05:51 -0600 Subject: [PATCH 20/23] fix(i18n): unescape template '' before substituting parameters --- library/i18n/i18nsupport.js | 10 ++-- tests/tx/fix-iss34-i18n-quote-order.test.js | 53 +++++++++++++++++++++ 2 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 tests/tx/fix-iss34-i18n-quote-order.test.js diff --git a/library/i18n/i18nsupport.js b/library/i18n/i18nsupport.js index 9162814d..2e70116c 100644 --- a/library/i18n/i18nsupport.js +++ b/library/i18n/i18nsupport.js @@ -142,8 +142,8 @@ class I18nSupport { return messageId; // Fallback to message ID if not found } - // Substitute parameters {0}, {1}, etc. - return this._substituteParameters(message.trim(), parameters).replaceAll("''", "'"); + // Unescape ICU '' in the template before substituting parameters so values starting with ' are preserved + return this._substituteParameters(message.trim().replaceAll("''", "'"), parameters); } _formatMessagePluralFromBundle(bundles, languages, messageId, count, parameters = []) { @@ -166,8 +166,8 @@ class I18nSupport { // Prepend count as parameter 0, shift other parameters const allParameters = [count.toString(), ...parameters]; - // Substitute parameters {0}, {1}, etc. - return this._substituteParameters(message, allParameters).replaceAll("''", "'"); + // Unescape ICU '' in the template before substituting parameters + return this._substituteParameters(message.replaceAll("''", "'"), allParameters); } /** @@ -279,7 +279,7 @@ function englishMessage(messageId, parameters = []) { if (!message) { return messageId; } - return I18nSupport.prototype._substituteParameters(message.trim(), parameters).replaceAll("''", "'"); + return I18nSupport.prototype._substituteParameters(message.trim().replaceAll("''", "'"), parameters); } let shared = null; diff --git a/tests/tx/fix-iss34-i18n-quote-order.test.js b/tests/tx/fix-iss34-i18n-quote-order.test.js new file mode 100644 index 00000000..e6d61e85 --- /dev/null +++ b/tests/tx/fix-iss34-i18n-quote-order.test.js @@ -0,0 +1,53 @@ +/** + * Regression test for ISS-34: I18nSupport unescapes template '' before parameter substitution + * so displays starting with ' are not mangled. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-34: i18n unescapes template quotes before parameter substitution', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const param = (res, name) => (res.body.parameter || []).find(p => p.name === name); + + test('display starting with single quote is not mangled in validation message', async () => { + const res = await request(app) + .post(`${R5}/CodeSystem/$validate-code`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ + resourceType: 'Parameters', + parameter: [ + { name: 'url', valueUri: 'http://example.org/cs-quote-iss34' }, + { name: 'code', valueCode: 'Q1' }, + { name: 'display', valueString: 'Wrong' }, + { + name: 'tx-resource', + resource: { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-quote-iss34', + version: '1.0', + status: 'active', + content: 'complete', + language: 'nl', + concept: [{ code: 'Q1', display: "'release' van contractuur" }] + } + } + ] + }); + expect(res.status).toBe(200); + const msg = param(res, 'message').valueString; + expect(msg).toContain("''release' van contractuur'"); + }); +}); From 3a3f5a979fee7254266763f387f4abf2fd2ff681 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:06:01 -0600 Subject: [PATCH 21/23] fix(subsumes): reject non-Parameters JSON POST with 400 Wrong_type_for_resource_expected --- .../tx/fix-iss35-subsumes-wrong-type.test.js | 40 +++++++++++++++++++ tx/workers/subsumes.js | 5 +++ 2 files changed, 45 insertions(+) create mode 100644 tests/tx/fix-iss35-subsumes-wrong-type.test.js diff --git a/tests/tx/fix-iss35-subsumes-wrong-type.test.js b/tests/tx/fix-iss35-subsumes-wrong-type.test.js new file mode 100644 index 00000000..6c795763 --- /dev/null +++ b/tests/tx/fix-iss35-subsumes-wrong-type.test.js @@ -0,0 +1,40 @@ +/** + * Regression test for ISS-35: $subsumes rejects non-Parameters JSON POST with + * 400 Wrong_type_for_resource_expected. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-35: $subsumes rejects non-Parameters JSON POST with Wrong_type_for_resource_expected', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test('POST /CodeSystem/$subsumes with Bundle returns 400 Wrong_type_for_resource_expected', async () => { + for (const acceptLang of [undefined, '*', 'en-US,en;q=0.9']) { + const req = request(app) + .post(`${R5}/CodeSystem/$subsumes`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json'); + if (acceptLang) { + req.set('Accept-Language', acceptLang); + } + const res = await req.send({ resourceType: 'Bundle', id: 'wrong-rt' }); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + const msgIds = (res.body.issue || []).flatMap(i => (i.extension || []) + .filter(e => e.url === 'http://hl7.org/fhir/StructureDefinition/operationoutcome-message-id') + .map(e => e.valueString)); + expect(msgIds).toContain('Wrong_type_for_resource_expected'); + } + }); +}); diff --git a/tx/workers/subsumes.js b/tx/workers/subsumes.js index 90f456ac..f4a66abd 100644 --- a/tx/workers/subsumes.js +++ b/tx/workers/subsumes.js @@ -12,6 +12,7 @@ const { FhirCodeSystemProvider } = require('../cs/cs-cs'); const {TxParameters} = require("../params"); const {Parameters} = require("../library/parameters"); const {Issue, OperationOutcome} = require("../library/operation-outcome"); +const {Languages} = require("../../library/i18n/languages"); const {debugLog} = require("../operation-context"); class SubsumesWorker extends TerminologyWorker { /** @@ -219,6 +220,10 @@ class SubsumesWorker extends TerminologyWorker { let result; if (req.body && req.body.resourceType === 'Parameters') { result = req.body; + } else if (req.method === 'POST' && req.body && req.body.resourceType) { + const langs = Languages.fromAcceptLanguage(req.headers?.['accept-language'], this.languages, true, true); + throw new Issue('error', 'invalid', null, 'Wrong_type_for_resource_expected', + this.i18n.translate('Wrong_type_for_resource_expected', langs, ['Parameters', req.body.resourceType])).handleAsOO(400); } else { // Parse from query params or form body and convert to Parameters resource const params = req.method === 'POST' ? req.body : req.query; From c223dc9cebade024a6b390608c51496d1f524890 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:06:08 -0600 Subject: [PATCH 22/23] fix(expand): deduplicate preferredForLanguage designation in listDisplaysFromIncludeConcept --- ...fix-iss37-expand-designation-dedup.test.js | 63 +++++++++++++++++++ tx/workers/expand.js | 18 +++++- 2 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 tests/tx/fix-iss37-expand-designation-dedup.test.js diff --git a/tests/tx/fix-iss37-expand-designation-dedup.test.js b/tests/tx/fix-iss37-expand-designation-dedup.test.js new file mode 100644 index 00000000..5ea9ce5e --- /dev/null +++ b/tests/tx/fix-iss37-expand-designation-dedup.test.js @@ -0,0 +1,63 @@ +/** + * Regression test for ISS-37: $expand deduplicates preferredForLanguage designation + * in listDisplaysFromIncludeConcept. + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('ISS-37: $expand deduplicates preferredForLanguage designation in listDisplaysFromIncludeConcept', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test('repeated concept.display in compose.include emits only one preferredForLanguage designation', async () => { + const res = await request(app) + .post(`${R5}/ValueSet/$expand`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .send({ + resourceType: 'Parameters', + parameter: [ + { + name: 'valueSet', + resource: { + resourceType: 'ValueSet', + url: 'http://example.org/vs-desig-iss37', + status: 'active', + compose: { include: [{ system: 'http://example.org/cs-desig-iss37', concept: [{ code: 'C1', display: 'Child One' }] }] } + } + }, + { name: 'includeDesignations', valueBoolean: true }, + { name: 'displayLanguage', valueCode: 'de' }, + { + name: 'tx-resource', + resource: { + resourceType: 'CodeSystem', + url: 'http://example.org/cs-desig-iss37', + version: '1.0', + status: 'active', + content: 'complete', + concept: [{ + code: 'C1', + display: 'Child One', + designation: [{ language: 'de', value: 'Kind Eins' }] + }] + } + } + ] + }); + expect(res.status).toBe(200); + const desigs = res.body.expansion.contains[0].designation || []; + const childOneDesigs = desigs.filter(d => d.value === 'Child One'); + expect(childOneDesigs).toHaveLength(1); + }); +}); diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 9552857d..f9f4562b 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -11,7 +11,7 @@ const { supplementProperties } = require('../library/supplement-properties'); const { TerminologyWorker } = require('./worker'); const {TxParameters} = require("../params"); -const {Designations, SearchFilterText} = require("../library/designations"); +const {Designations, DesignationUse, SearchFilterText} = require("../library/designations"); const { storedExpansionIssue } = require("../library/stored-expansion"); const {Extensions} = require("../library/extensions"); const {getValuePrimitive, getValueName, validateParameter} = require("../../library/utils/utilities"); @@ -300,15 +300,27 @@ class ValueSetExpander { } listDisplaysFromIncludeConcept(displays, concept, vs) { + const hasSame = (langCode, use, value) => displays.designations.some(d => + (d.language ? d.language.code : '') === (langCode || '') && + (d.use ? d.use.system : '') === (use ? use.system : '') && + (d.use ? d.use.code : '') === (use ? use.code : '') && + d.value === value + ); if (concept.display) { if (!VersionUtilities.isR4Plus(this.worker.provider.getFhirVersion())) { displays.clear(); } let lang = vs.language ? this.worker.languages.parse(vs.language) : null; - displays.addDesignation(true, "active", lang, null, concept.display); + const langCode = lang ? lang.code : ''; + if (!hasSame(langCode, DesignationUse.DISPLAY, concept.display)) { + displays.addDesignation(true, "active", lang, null, concept.display); } + } for (const cd of concept.designation || []) { - displays.addDesignationFromConcept(cd); + const val = cd && cd.value ? cd.value.trim() : ''; + if (!val || !hasSame(cd.language || '', cd.use || null, val)) { + displays.addDesignationFromConcept(cd); + } } } canonical(system, version) { From 87b4c54d5972893d74e5f94af40381f77356506d Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:26:49 -0600 Subject: [PATCH 23/23] fix(i18n): parse Accept-Language as Languages iterable in requestLanguages and buildParameters --- tests/tx/fix-accept-language-iterable.test.js | 61 +++++++++++++++++++ tx/tx.js | 7 ++- tx/workers/worker.js | 2 +- 3 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 tests/tx/fix-accept-language-iterable.test.js diff --git a/tests/tx/fix-accept-language-iterable.test.js b/tests/tx/fix-accept-language-iterable.test.js new file mode 100644 index 00000000..c2680737 --- /dev/null +++ b/tests/tx/fix-accept-language-iterable.test.js @@ -0,0 +1,61 @@ +/** + * Regression test: Accept-Language header parsing in requestLanguages() and + * TerminologyWorker.buildParameters() must return an iterable Languages instance + * rather than a single Language from LanguageDefinitions.parse(). + */ + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const R5 = '/tx/r5'; + +describe('Accept-Language iterable handling in error responses', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 240000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + test.each(['*', 'en-US', 'en-US,en;q=0.9', 'de;q=0.8,en;q=0.5'])( + 'invalid parameter with Accept-Language: %s returns 400 (not 500 languages is not iterable)', + async (acceptLang) => { + const res = await request(app) + .post(`${R5}/ValueSet/$expand`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .set('Accept-Language', acceptLang) + .send({ + resourceType: 'Parameters', + parameter: [ + { name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'offset', valueInteger: 2147483648 } + ] + }); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('invalid'); + } + ); + + test.each(['*', 'en-US,en;q=0.9'])( + 'non-Parameters POST to $lookup with Accept-Language: %s returns 400 Wrong_type_for_resource_expected', + async (acceptLang) => { + const res = await request(app) + .post(`${R5}/CodeSystem/$lookup`) + .set('Content-Type', 'application/json') + .set('Accept', 'application/fhir+json') + .set('Accept-Language', acceptLang) + .send({ resourceType: 'Bundle', id: 'wrong-rt' }); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + const msgIds = (res.body.issue || []).flatMap(i => (i.extension || []) + .filter(e => e.url === 'http://hl7.org/fhir/StructureDefinition/operationoutcome-message-id') + .map(e => e.valueString)); + expect(msgIds).toContain('Wrong_type_for_resource_expected'); + } + ); +}); diff --git a/tx/tx.js b/tx/tx.js index 80a2abc5..f191d111 100644 --- a/tx/tx.js +++ b/tx/tx.js @@ -27,7 +27,7 @@ const { addPreBodyCheck } = require('../library/server/pre-body'); const { requestMessage } = require('../library/i18n/i18nsupport'); const { Library } = require('./library'); const { OperationContext, ResourceCache, ExpansionCache, ExpansionCacheBudget, debugLog} = require('./operation-context'); -const { LanguageDefinitions } = require('../library/i18n/languages'); +const { LanguageDefinitions, Languages } = require('../library/i18n/languages'); const { I18nSupport } = require('../library/i18n/i18nsupport'); const { duplicatesOutcomeAsync } = require('../library/fhir/json-duplicates'); const { CodeSystemXML } = require('./xml/codesystem-xml'); @@ -2223,10 +2223,11 @@ class TXModule { * The languages a request asks for its messages in (Accept-Language), or the default */ requestLanguages(req) { + const header = req && req.headers ? req.headers['accept-language'] : null; try { - return this.languages.parse(req.headers ? req.headers['accept-language'] : null); + return Languages.fromAcceptLanguage(header, this.languages, true, true); } catch (e) { - return this.languages.parse(null); + return Languages.fromAcceptLanguage(null, this.languages, true, true); } } diff --git a/tx/workers/worker.js b/tx/workers/worker.js index 7c7e7530..327a9893 100644 --- a/tx/workers/worker.js +++ b/tx/workers/worker.js @@ -678,7 +678,7 @@ class TerminologyWorker { if (req.method === 'POST' && req.body && req.body.resourceType === 'Parameters') { params = req.body; } else if (req.method === 'POST' && req.body && req.body.resourceType) { - let langs = this.languages.parse(req.headers['accept-language']); + let langs = Languages.fromAcceptLanguage(req.headers?.['accept-language'], this.languages, true, true); throw new Issue('error', 'invalid', null, 'Wrong_type_for_resource_expected', this.i18n.translate('Wrong_type_for_resource_expected', langs, ["Parameters", req.body.resourceType])).handleAsOO(400); } else { // Convert query params or form body to Parameters