From 2370122e0b9edff479c0b5151c3964482ee8cd48 Mon Sep 17 00:00:00 2001 From: Filipe Lopes Date: Mon, 16 Nov 2026 17:19:21 -0300 Subject: [PATCH 1/6] fix(mapper): populate canonical url from algorithm metadata --- .../map-projects/MultiAlgoSelector.jsx | 7 ++----- .../__tests__/customAlgoMetadata.test.js | 17 +++++++++++++++++ src/components/map-projects/algorithms.jsx | 9 ++------- .../map-projects/customAlgoMetadata.js | 13 +++++++++++++ 4 files changed, 34 insertions(+), 12 deletions(-) create mode 100644 src/components/map-projects/__tests__/customAlgoMetadata.test.js create mode 100644 src/components/map-projects/customAlgoMetadata.js diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index 2c7abf56..17fc3f2c 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -35,6 +35,7 @@ import orderBy from 'lodash/orderBy' import ConceptIcon from '../concepts/ConceptIcon' import { OperationsContext } from '../app/LayoutContext' import { isLikelyCanonicalUrl } from './algorithms' +import { metadataFields } from './customAlgoMetadata.js' import RepoVersionSearchAutocomplete from '../repos/RepoVersionSearchAutocomplete' import APIService from '../../services/APIService'; import { needsSessionToken, getTokenFlag, tokenInputValue, removeSavedToken } from '../../services/tokenScope'; @@ -389,11 +390,7 @@ export default function MultiAlgoSelector({ return; } - updateSelected(key, { - id: data.ID || data.id || '', - name: data.name || '', - description: data.description || '', - }); + updateSelected(key, metadataFields(data)); setCustomAlgoState(key, { isLoading: false, tokenRequired: false, diff --git a/src/components/map-projects/__tests__/customAlgoMetadata.test.js b/src/components/map-projects/__tests__/customAlgoMetadata.test.js new file mode 100644 index 00000000..499cfadb --- /dev/null +++ b/src/components/map-projects/__tests__/customAlgoMetadata.test.js @@ -0,0 +1,17 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { metadataFields } from '../customAlgoMetadata.js' + +test('metadata supplies the canonical URL alongside the other form fields', () => { + assert.deepEqual(metadataFields({ ID: 'agent', name: 'Agent', canonical_url: 'http://example.test/system' }), { + id: 'agent', name: 'Agent', description: '', canonical_url: 'http://example.test/system' + }) +}) + +test('missing or invalid canonical URL leaves the existing field untouched', () => { + for (const canonical_url of [undefined, '', 'invalid', null]) { + assert.deepEqual(metadataFields({ id: 'agent', name: 'Agent', canonical_url }), { + id: 'agent', name: 'Agent', description: '' + }) + } +}) diff --git a/src/components/map-projects/algorithms.jsx b/src/components/map-projects/algorithms.jsx index 9f41c5e0..fbce5bc4 100644 --- a/src/components/map-projects/algorithms.jsx +++ b/src/components/map-projects/algorithms.jsx @@ -1,5 +1,6 @@ import React from 'react' import MatchingIcon from '@mui/icons-material/DeviceHub'; +import { isLikelyCanonicalUrl } from './customAlgoMetadata.js' // Canonical concept-identity config per algorithm type // (plans/unified-mapper-model.md). Single source of truth shared between @@ -47,13 +48,7 @@ export const CONCEPT_IDENTITY_BY_TYPE = { } } -// Cheap structural validator for canonical URLs. The unified mapper model -// requires every algorithm's concept_identity.canonical_url to be a URL — -// custom algos rely on user input for this, so the form validates here. -export const isLikelyCanonicalUrl = (value) => { - if(!value || typeof value !== 'string') return false - return /^https?:\/\/[^\s]+$/i.test(value.trim()) -} +export { isLikelyCanonicalUrl } // Walk algosSelected and return the subset that fails project-config // validation. Currently: custom algos must have a valid canonical_url. diff --git a/src/components/map-projects/customAlgoMetadata.js b/src/components/map-projects/customAlgoMetadata.js new file mode 100644 index 00000000..adc794d8 --- /dev/null +++ b/src/components/map-projects/customAlgoMetadata.js @@ -0,0 +1,13 @@ +// Match the form's URL validation when accepting metadata from a custom API. +export const isLikelyCanonicalUrl = value => { + if(!value || typeof value !== 'string') return false + return /^https?:\/\/[^\s]+$/i.test(value.trim()) +} + +// Omit an absent or invalid canonical so an existing form value is preserved. +export const metadataFields = data => ({ + id: data.ID || data.id || '', + name: data.name || '', + description: data.description || '', + ...(isLikelyCanonicalUrl(data.canonical_url) ? { canonical_url: data.canonical_url.trim() } : {}), +}) From 3198b26e7c21fa2c712c90d70bc2c5508ad977af Mon Sep 17 00:00:00 2001 From: Filipe Lopes Date: Mon, 16 Nov 2026 17:21:22 -0300 Subject: [PATCH 2/6] fix(mapper): retry algorithm metadata without operation marker --- .../map-projects/MultiAlgoSelector.jsx | 9 +-- .../__tests__/customAlgoMetadata.test.js | 58 ++++++++++++++++++- .../map-projects/customAlgoMetadata.js | 14 +++++ 3 files changed, 76 insertions(+), 5 deletions(-) diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index 17fc3f2c..dced75e2 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -35,7 +35,7 @@ import orderBy from 'lodash/orderBy' import ConceptIcon from '../concepts/ConceptIcon' import { OperationsContext } from '../app/LayoutContext' import { isLikelyCanonicalUrl } from './algorithms' -import { metadataFields } from './customAlgoMetadata.js' +import { metadataFields, fetchAlgorithmMetadata } from './customAlgoMetadata.js' import RepoVersionSearchAutocomplete from '../repos/RepoVersionSearchAutocomplete' import APIService from '../../services/APIService'; import { needsSessionToken, getTokenFlag, tokenInputValue, removeSavedToken } from '../../services/tokenScope'; @@ -354,9 +354,10 @@ export default function MultiAlgoSelector({ setCustomAlgoState(key, {isLoading: true, requestError: '', requestSuccess: '', tokenRequired: false}); const service = APIService.new(); - service.URL = selected.url; - - const response = await service.get(token || false, {}, undefined, true); + const response = await fetchAlgorithmMetadata(selected.url, url => { + service.URL = url; + return service.get(token || false, {}, undefined, true); + }); const status = response?.response?.status || response?.status; if([401, 403].includes(status)) { diff --git a/src/components/map-projects/__tests__/customAlgoMetadata.test.js b/src/components/map-projects/__tests__/customAlgoMetadata.test.js index 499cfadb..a2ae1900 100644 --- a/src/components/map-projects/__tests__/customAlgoMetadata.test.js +++ b/src/components/map-projects/__tests__/customAlgoMetadata.test.js @@ -1,6 +1,7 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { metadataFields } from '../customAlgoMetadata.js' +import { createServer } from 'node:http' +import { metadataFields, fetchAlgorithmMetadata } from '../customAlgoMetadata.js' test('metadata supplies the canonical URL alongside the other form fields', () => { assert.deepEqual(metadataFields({ ID: 'agent', name: 'Agent', canonical_url: 'http://example.test/system' }), { @@ -15,3 +16,58 @@ test('missing or invalid canonical URL leaves the existing field untouched', () }) } }) + +test('metadata GET tries the operation without dollar first, then the original on failure', async () => { + const urls = [] + const result = await fetchAlgorithmMetadata('https://example.test/api/$match?x=$keep', async url => { + urls.push(url) + return urls.length === 1 ? {response: {status: 404}} : {data: {ID: 'x', name: 'X'}} + }) + assert.deepEqual(urls, ['https://example.test/api/match?x=$keep', 'https://example.test/api/$match?x=$keep']) + assert.equal(result.data.ID, 'x') +}) + +test('metadata GET avoids a retry on success or when the URL has no operation marker', async () => { + for (const url of ['https://example.test/api/$match/', 'https://example.test/api/match']) { + const calls = [] + await fetchAlgorithmMetadata(url, async candidate => { calls.push(candidate); return {data: {id: 'x', name: 'X'}} }) + assert.equal(calls.length, 1) + assert.equal(calls[0], 'https://example.test/api/match' + (url.endsWith('/') ? '/' : '')) + } +}) + +test('metadata GET retries when the first response is not usable metadata', async () => { + const calls = [] + const result = await fetchAlgorithmMetadata('https://example.test/$match', async url => { + calls.push(url) + return calls.length === 1 ? {data: {message: 'not metadata'}} : {data: {id: 'x', name: 'X'}} + }) + assert.equal(calls.length, 2) + assert.equal(result.data.id, 'x') +}) + +test('metadata GET retains an authentication failure if the alternate is missing', async () => { + const result = await fetchAlgorithmMetadata('https://example.test/$match', async url => ( + {response: {status: url.includes('$') ? 404 : 401}} + )) + assert.equal(result.response.status, 401) +}) + +test('metadata fallback performs real GET requests against a local server', async t => { + const requests = [] + const server = createServer((req, res) => { + requests.push([req.method, req.url, req.headers.authorization]) + res.setHeader('Content-Type', 'application/json') + if(req.url === '/$match') res.end(JSON.stringify({ID: 'x', name: 'X', canonical_url: 'https://example.test/system'})) + else { res.statusCode = 404; res.end('{}') } + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => server.close(resolve))) + const url = `http://127.0.0.1:${server.address().port}/$match` + const response = await fetchAlgorithmMetadata(url, async candidate => { + const result = await fetch(candidate, {headers: {Authorization: 'Token test'}}) + return result.ok ? {data: await result.json()} : {response: {status: result.status}} + }) + assert.deepEqual(requests, [['GET', '/match', 'Token test'], ['GET', '/$match', 'Token test']]) + assert.equal(metadataFields(response.data).canonical_url, 'https://example.test/system') +}) diff --git a/src/components/map-projects/customAlgoMetadata.js b/src/components/map-projects/customAlgoMetadata.js index adc794d8..9eb6f671 100644 --- a/src/components/map-projects/customAlgoMetadata.js +++ b/src/components/map-projects/customAlgoMetadata.js @@ -11,3 +11,17 @@ export const metadataFields = data => ({ description: data.description || '', ...(isLikelyCanonicalUrl(data.canonical_url) ? { canonical_url: data.canonical_url.trim() } : {}), }) + +// Try the non-operation metadata path before the original POST endpoint. +export const fetchAlgorithmMetadata = async (url, get) => { + const [path] = url.split(/[?#]/, 1) + const metadataUrl = path.replace(/\/\$([^/]+)(\/?)$/, '/$1$2') + url.slice(path.length) + const first = await get(metadataUrl) + const data = first?.data || first + if(metadataUrl === url || (!first?.response && data?.name && (data?.ID || data?.id))) return first + const second = await get(url) + const secondData = second?.data || second + if(!second?.response && secondData?.name && (secondData?.ID || secondData?.id)) return second + const firstStatus = first?.response?.status || first?.status + return [401, 403].includes(firstStatus) ? first : second +} From c800ed00b5397ab7a20f74f9e0810a71f6a265fe Mon Sep 17 00:00:00 2001 From: Filipe Lopes Date: Mon, 16 Nov 2026 17:36:39 -0300 Subject: [PATCH 3/6] fix(mapper): discover custom algorithm metadata at parent endpoint --- .../__tests__/customAlgoMetadata.test.js | 42 +++++++++++++++++++ .../map-projects/customAlgoMetadata.js | 10 +++-- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/components/map-projects/__tests__/customAlgoMetadata.test.js b/src/components/map-projects/__tests__/customAlgoMetadata.test.js index a2ae1900..9410a769 100644 --- a/src/components/map-projects/__tests__/customAlgoMetadata.test.js +++ b/src/components/map-projects/__tests__/customAlgoMetadata.test.js @@ -46,6 +46,20 @@ test('metadata GET retries when the first response is not usable metadata', asyn assert.equal(result.data.id, 'x') }) +test('metadata GET falls back to the parent endpoint after both operation URLs fail', async () => { + const calls = [] + const result = await fetchAlgorithmMetadata('https://example.test/api/ciel-bridge-rxnorm/$match?lang=en', async url => { + calls.push(url) + return calls.length < 3 ? {response: {status: 404}} : {data: {ID: 'x', name: 'X'}} + }) + assert.deepEqual(calls, [ + 'https://example.test/api/ciel-bridge-rxnorm/match?lang=en', + 'https://example.test/api/ciel-bridge-rxnorm/$match?lang=en', + 'https://example.test/api/ciel-bridge-rxnorm?lang=en', + ]) + assert.equal(result.data.ID, 'x') +}) + test('metadata GET retains an authentication failure if the alternate is missing', async () => { const result = await fetchAlgorithmMetadata('https://example.test/$match', async url => ( {response: {status: url.includes('$') ? 404 : 401}} @@ -53,6 +67,16 @@ test('metadata GET retains an authentication failure if the alternate is missing assert.equal(result.response.status, 401) }) +test('parent fallback keeps the first authentication error if all three attempts fail', async () => { + const calls = [] + const result = await fetchAlgorithmMetadata('https://example.test/api/$match/', async url => { + calls.push(url) + return {response: {status: calls.length === 2 ? 403 : 404}} + }) + assert.deepEqual(calls, ['https://example.test/api/match/', 'https://example.test/api/$match/', 'https://example.test/api']) + assert.equal(result.response.status, 403) +}) + test('metadata fallback performs real GET requests against a local server', async t => { const requests = [] const server = createServer((req, res) => { @@ -71,3 +95,21 @@ test('metadata fallback performs real GET requests against a local server', asyn assert.deepEqual(requests, [['GET', '/match', 'Token test'], ['GET', '/$match', 'Token test']]) assert.equal(metadataFields(response.data).canonical_url, 'https://example.test/system') }) + +test('parent fallback obtains metadata through real HTTP after two 404 responses', async t => { + const requests = [] + const server = createServer((req, res) => { + requests.push(req.url) + res.setHeader('Content-Type', 'application/json') + if(req.url === '/api/algorithm') res.end(JSON.stringify({ID: 'x', name: 'X'})) + else { res.statusCode = 404; res.end('{}') } + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => server.close(resolve))) + const result = await fetchAlgorithmMetadata(`http://127.0.0.1:${server.address().port}/api/algorithm/$match`, async url => { + const response = await fetch(url) + return response.ok ? {data: await response.json()} : {response: {status: response.status}} + }) + assert.deepEqual(requests, ['/api/algorithm/match', '/api/algorithm/$match', '/api/algorithm']) + assert.equal(result.data.ID, 'x') +}) diff --git a/src/components/map-projects/customAlgoMetadata.js b/src/components/map-projects/customAlgoMetadata.js index 9eb6f671..1fc572ec 100644 --- a/src/components/map-projects/customAlgoMetadata.js +++ b/src/components/map-projects/customAlgoMetadata.js @@ -12,7 +12,7 @@ export const metadataFields = data => ({ ...(isLikelyCanonicalUrl(data.canonical_url) ? { canonical_url: data.canonical_url.trim() } : {}), }) -// Try the non-operation metadata path before the original POST endpoint. +// Try metadata paths in order: operation without $, original URL, then parent. export const fetchAlgorithmMetadata = async (url, get) => { const [path] = url.split(/[?#]/, 1) const metadataUrl = path.replace(/\/\$([^/]+)(\/?)$/, '/$1$2') + url.slice(path.length) @@ -22,6 +22,10 @@ export const fetchAlgorithmMetadata = async (url, get) => { const second = await get(url) const secondData = second?.data || second if(!second?.response && secondData?.name && (secondData?.ID || secondData?.id)) return second - const firstStatus = first?.response?.status || first?.status - return [401, 403].includes(firstStatus) ? first : second + const parentPath = path.replace(/\/\$[^/]+\/?$/, '') + const parentUrl = parentPath + url.slice(path.length) + const third = await get(parentUrl) + const thirdData = third?.data || third + if(!third?.response && thirdData?.name && (thirdData?.ID || thirdData?.id)) return third + return [first, second, third].find(response => [401, 403].includes(response?.response?.status || response?.status)) || third } From 74f1b880d1587b496e18472c3a0ebe8d270747f6 Mon Sep 17 00:00:00 2001 From: Filipe Lopes Date: Tue, 17 Nov 2026 06:32:10 -0300 Subject: [PATCH 4/6] fix(mapper): ignore the edited algorithm when checking id and name conflicts --- .../map-projects/MultiAlgoSelector.jsx | 14 ++++---------- .../__tests__/customAlgoMetadata.test.js | 19 ++++++++++++++++++- .../map-projects/customAlgoMetadata.js | 8 ++++++++ 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index dced75e2..cab037e3 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -26,7 +26,6 @@ import AddRoundedIcon from "@mui/icons-material/AddRounded"; import MatchingIcon from '@mui/icons-material/DeviceHub'; import countBy from 'lodash/countBy' import omit from 'lodash/omit' -import filter from 'lodash/filter' import find from 'lodash/find' import isString from 'lodash/isString' import orderBy from 'lodash/orderBy' @@ -35,7 +34,7 @@ import orderBy from 'lodash/orderBy' import ConceptIcon from '../concepts/ConceptIcon' import { OperationsContext } from '../app/LayoutContext' import { isLikelyCanonicalUrl } from './algorithms' -import { metadataFields, fetchAlgorithmMetadata } from './customAlgoMetadata.js' +import { metadataFields, fetchAlgorithmMetadata, conflictingFields } from './customAlgoMetadata.js' import RepoVersionSearchAutocomplete from '../repos/RepoVersionSearchAutocomplete' import APIService from '../../services/APIService'; import { needsSessionToken, getTokenFlag, tokenInputValue, removeSavedToken } from '../../services/tokenScope'; @@ -202,14 +201,9 @@ export default function MultiAlgoSelector({ const updateSelected = (key, patch) => { const next = normalizedValue.map(v => (v.__key === key ? { ...v, ...patch } : v)); onChange(next); - if((patch.id || patch.name)) { - if(filter(value, patch).length > 0) - setErrors(prev => ({...prev, [key]: {...prev[key], ...patch}})) - else if (patch.id) - setErrors(prev => ({...prev, [key]: {...omit(prev[key], 'id')}})) - else if (patch.name) - setErrors(prev => ({...prev, [key]: {...omit(prev[key], 'name')}})) - } + const conflicts = conflictingFields(normalizedValue, key, patch); + if(Object.keys(conflicts).length > 0) + setErrors(prev => ({...prev, [key]: {...prev[key], ...conflicts}})) }; // For each selected bridge algo, fetch the source repo's canonical_url from diff --git a/src/components/map-projects/__tests__/customAlgoMetadata.test.js b/src/components/map-projects/__tests__/customAlgoMetadata.test.js index 9410a769..baed115c 100644 --- a/src/components/map-projects/__tests__/customAlgoMetadata.test.js +++ b/src/components/map-projects/__tests__/customAlgoMetadata.test.js @@ -1,7 +1,24 @@ import test from 'node:test' import assert from 'node:assert/strict' import { createServer } from 'node:http' -import { metadataFields, fetchAlgorithmMetadata } from '../customAlgoMetadata.js' +import { metadataFields, fetchAlgorithmMetadata, conflictingFields } from '../customAlgoMetadata.js' + +test('an algorithm never conflicts with itself when its own id and name are re-applied', () => { + const items = [{__key: 'a', id: 'icd-agent', name: 'ICD Agent'}] + assert.deepEqual(conflictingFields(items, 'a', {id: 'icd-agent', name: 'ICD Agent', description: ''}), {id: false, name: false}) +}) + +test('id and name conflicts are reported independently against the other algorithms only', () => { + const items = [{__key: 'a', id: 'icd-agent', name: 'ICD Agent'}, {__key: 'b', id: 'other', name: 'ICD Agent'}] + assert.deepEqual(conflictingFields(items, 'a', {id: 'other', name: 'Fresh'}), {id: true, name: false}) + assert.deepEqual(conflictingFields(items, 'a', {id: 'fresh', name: 'ICD Agent'}), {id: false, name: true}) +}) + +test('fields absent from the patch are not evaluated', () => { + const items = [{__key: 'a', id: 'x', name: 'X'}, {__key: 'b', id: 'y', name: 'Y'}] + assert.deepEqual(conflictingFields(items, 'a', {description: 'd'}), {}) + assert.deepEqual(conflictingFields(items, 'a', {id: 'y'}), {id: true}) +}) test('metadata supplies the canonical URL alongside the other form fields', () => { assert.deepEqual(metadataFields({ ID: 'agent', name: 'Agent', canonical_url: 'http://example.test/system' }), { diff --git a/src/components/map-projects/customAlgoMetadata.js b/src/components/map-projects/customAlgoMetadata.js index 1fc572ec..75d7d78f 100644 --- a/src/components/map-projects/customAlgoMetadata.js +++ b/src/components/map-projects/customAlgoMetadata.js @@ -29,3 +29,11 @@ export const fetchAlgorithmMetadata = async (url, get) => { if(!third?.response && thirdData?.name && (thirdData?.ID || thirdData?.id)) return third return [first, second, third].find(response => [401, 403].includes(response?.response?.status || response?.status)) || third } + +// Whether the patched id/name collide with ANOTHER algorithm (the one being edited is excluded by key). +export const conflictingFields = (items, key, patch) => { + const others = (items || []).filter(item => item.__key !== key) + return Object.fromEntries(['id', 'name'] + .filter(field => patch[field]) + .map(field => [field, others.some(item => item[field] === patch[field])])) +} From 520e12ebf9680f60865b77f302ec9836b9917458 Mon Sep 17 00:00:00 2001 From: Filipe Lopes Date: Fri, 20 Nov 2026 09:05:33 -0300 Subject: [PATCH 5/6] OpenConceptLab/ocl_issues#3055 | Custom algorithm metadata: request the configured URL first, then the path without the operation marker, then the parent path --- .../__tests__/customAlgoMetadata.test.js | 34 +++++++++++------- .../map-projects/customAlgoMetadata.js | 35 +++++++++++-------- 2 files changed, 42 insertions(+), 27 deletions(-) diff --git a/src/components/map-projects/__tests__/customAlgoMetadata.test.js b/src/components/map-projects/__tests__/customAlgoMetadata.test.js index baed115c..3d6db480 100644 --- a/src/components/map-projects/__tests__/customAlgoMetadata.test.js +++ b/src/components/map-projects/__tests__/customAlgoMetadata.test.js @@ -34,32 +34,40 @@ test('missing or invalid canonical URL leaves the existing field untouched', () } }) -test('metadata GET tries the operation without dollar first, then the original on failure', async () => { +test('metadata GET tries the configured URL first, then the operation without dollar on failure', async () => { const urls = [] const result = await fetchAlgorithmMetadata('https://example.test/api/$match?x=$keep', async url => { urls.push(url) return urls.length === 1 ? {response: {status: 404}} : {data: {ID: 'x', name: 'X'}} }) - assert.deepEqual(urls, ['https://example.test/api/match?x=$keep', 'https://example.test/api/$match?x=$keep']) + assert.deepEqual(urls, ['https://example.test/api/$match?x=$keep', 'https://example.test/api/match?x=$keep']) assert.equal(result.data.ID, 'x') }) -test('metadata GET avoids a retry on success or when the URL has no operation marker', async () => { - for (const url of ['https://example.test/api/$match/', 'https://example.test/api/match']) { +test('metadata GET never reaches another document when the configured URL already returns metadata', async () => { + for (const url of ['https://example.test/api/$match/', 'https://example.test/fhir/ConceptMap/$translate']) { const calls = [] - await fetchAlgorithmMetadata(url, async candidate => { calls.push(candidate); return {data: {id: 'x', name: 'X'}} }) - assert.equal(calls.length, 1) - assert.equal(calls[0], 'https://example.test/api/match' + (url.endsWith('/') ? '/' : '')) + const result = await fetchAlgorithmMetadata(url, async candidate => ( + calls.push(candidate) && candidate === url ? {data: {id: 'configured', name: 'Configured'}} : {data: {id: 'translate', name: 'Wrong document'}} + )) + assert.deepEqual(calls, [url]) + assert.equal(result.data.id, 'configured') } }) -test('metadata GET retries when the first response is not usable metadata', async () => { +test('metadata GET requests a URL without an operation marker only once', async () => { + const calls = [] + await fetchAlgorithmMetadata('https://example.test/api/match', async candidate => { calls.push(candidate); return {response: {status: 404}} }) + assert.deepEqual(calls, ['https://example.test/api/match']) +}) + +test('metadata GET moves on when the configured URL does not return usable metadata', async () => { const calls = [] const result = await fetchAlgorithmMetadata('https://example.test/$match', async url => { calls.push(url) return calls.length === 1 ? {data: {message: 'not metadata'}} : {data: {id: 'x', name: 'X'}} }) - assert.equal(calls.length, 2) + assert.deepEqual(calls, ['https://example.test/$match', 'https://example.test/match']) assert.equal(result.data.id, 'x') }) @@ -70,8 +78,8 @@ test('metadata GET falls back to the parent endpoint after both operation URLs f return calls.length < 3 ? {response: {status: 404}} : {data: {ID: 'x', name: 'X'}} }) assert.deepEqual(calls, [ - 'https://example.test/api/ciel-bridge-rxnorm/match?lang=en', 'https://example.test/api/ciel-bridge-rxnorm/$match?lang=en', + 'https://example.test/api/ciel-bridge-rxnorm/match?lang=en', 'https://example.test/api/ciel-bridge-rxnorm?lang=en', ]) assert.equal(result.data.ID, 'x') @@ -90,7 +98,7 @@ test('parent fallback keeps the first authentication error if all three attempts calls.push(url) return {response: {status: calls.length === 2 ? 403 : 404}} }) - assert.deepEqual(calls, ['https://example.test/api/match/', 'https://example.test/api/$match/', 'https://example.test/api']) + assert.deepEqual(calls, ['https://example.test/api/$match/', 'https://example.test/api/match/', 'https://example.test/api']) assert.equal(result.response.status, 403) }) @@ -109,7 +117,7 @@ test('metadata fallback performs real GET requests against a local server', asyn const result = await fetch(candidate, {headers: {Authorization: 'Token test'}}) return result.ok ? {data: await result.json()} : {response: {status: result.status}} }) - assert.deepEqual(requests, [['GET', '/match', 'Token test'], ['GET', '/$match', 'Token test']]) + assert.deepEqual(requests, [['GET', '/$match', 'Token test']]) assert.equal(metadataFields(response.data).canonical_url, 'https://example.test/system') }) @@ -127,6 +135,6 @@ test('parent fallback obtains metadata through real HTTP after two 404 responses const response = await fetch(url) return response.ok ? {data: await response.json()} : {response: {status: response.status}} }) - assert.deepEqual(requests, ['/api/algorithm/match', '/api/algorithm/$match', '/api/algorithm']) + assert.deepEqual(requests, ['/api/algorithm/$match', '/api/algorithm/match', '/api/algorithm']) assert.equal(result.data.ID, 'x') }) diff --git a/src/components/map-projects/customAlgoMetadata.js b/src/components/map-projects/customAlgoMetadata.js index 75d7d78f..e7aac9da 100644 --- a/src/components/map-projects/customAlgoMetadata.js +++ b/src/components/map-projects/customAlgoMetadata.js @@ -12,22 +12,29 @@ export const metadataFields = data => ({ ...(isLikelyCanonicalUrl(data.canonical_url) ? { canonical_url: data.canonical_url.trim() } : {}), }) -// Try metadata paths in order: operation without $, original URL, then parent. +const isMetadata = response => { + const data = response?.data || response + return !response?.response && Boolean(data?.name && (data?.ID || data?.id)) +} + +// The configured URL is authoritative: request it first, then the operation without $ +// (`/$match` -> `/match`), then the parent path. Candidates that collapse to the same URL +// (no `$` marker) are requested once. export const fetchAlgorithmMetadata = async (url, get) => { const [path] = url.split(/[?#]/, 1) - const metadataUrl = path.replace(/\/\$([^/]+)(\/?)$/, '/$1$2') + url.slice(path.length) - const first = await get(metadataUrl) - const data = first?.data || first - if(metadataUrl === url || (!first?.response && data?.name && (data?.ID || data?.id))) return first - const second = await get(url) - const secondData = second?.data || second - if(!second?.response && secondData?.name && (secondData?.ID || secondData?.id)) return second - const parentPath = path.replace(/\/\$[^/]+\/?$/, '') - const parentUrl = parentPath + url.slice(path.length) - const third = await get(parentUrl) - const thirdData = third?.data || third - if(!third?.response && thirdData?.name && (thirdData?.ID || thirdData?.id)) return third - return [first, second, third].find(response => [401, 403].includes(response?.response?.status || response?.status)) || third + const suffix = url.slice(path.length) + const candidates = [...new Set([ + url, + path.replace(/\/\$([^/]+)(\/?)$/, '/$1$2') + suffix, + path.replace(/\/\$[^/]+\/?$/, '') + suffix, + ])] + const responses = [] + for(const candidate of candidates) { + const response = await get(candidate) + if(isMetadata(response)) return response + responses.push(response) + } + return responses.find(response => [401, 403].includes(response?.response?.status || response?.status)) || responses[responses.length - 1] } // Whether the patched id/name collide with ANOTHER algorithm (the one being edited is excluded by key). From b709f42984baf7386efca8d85baa88445dbed961 Mon Sep 17 00:00:00 2001 From: Filipe Lopes Date: Fri, 20 Nov 2026 09:05:33 -0300 Subject: [PATCH 6/6] OpenConceptLab/ocl_issues#3055 | Custom algorithm form: metadata fills the canonical URL only when empty; document why the validator exists --- src/components/map-projects/MultiAlgoSelector.jsx | 2 +- .../map-projects/__tests__/customAlgoMetadata.test.js | 8 ++++++++ src/components/map-projects/customAlgoMetadata.js | 10 ++++++---- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index cab037e3..4b5cea2c 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -385,7 +385,7 @@ export default function MultiAlgoSelector({ return; } - updateSelected(key, metadataFields(data)); + updateSelected(key, metadataFields(data, selected)); setCustomAlgoState(key, { isLoading: false, tokenRequired: false, diff --git a/src/components/map-projects/__tests__/customAlgoMetadata.test.js b/src/components/map-projects/__tests__/customAlgoMetadata.test.js index 3d6db480..fb1261c9 100644 --- a/src/components/map-projects/__tests__/customAlgoMetadata.test.js +++ b/src/components/map-projects/__tests__/customAlgoMetadata.test.js @@ -20,6 +20,14 @@ test('fields absent from the patch are not evaluated', () => { assert.deepEqual(conflictingFields(items, 'a', {id: 'y'}), {id: true}) }) +test('metadata does not replace a canonical URL the user already filled in', () => { + const data = { id: 'agent', name: 'Agent', canonical_url: 'http://example.test/system' } + assert.equal('canonical_url' in metadataFields(data, { canonical_url: 'http://typed.test' }), false) + for (const canonical_url of [undefined, '', ' ']) { + assert.equal(metadataFields(data, { canonical_url }).canonical_url, 'http://example.test/system') + } +}) + test('metadata supplies the canonical URL alongside the other form fields', () => { assert.deepEqual(metadataFields({ ID: 'agent', name: 'Agent', canonical_url: 'http://example.test/system' }), { id: 'agent', name: 'Agent', description: '', canonical_url: 'http://example.test/system' diff --git a/src/components/map-projects/customAlgoMetadata.js b/src/components/map-projects/customAlgoMetadata.js index e7aac9da..f6007184 100644 --- a/src/components/map-projects/customAlgoMetadata.js +++ b/src/components/map-projects/customAlgoMetadata.js @@ -1,15 +1,17 @@ -// Match the form's URL validation when accepting metadata from a custom API. +// Cheap structural validator for canonical URLs. The unified mapper model requires every +// algorithm's concept_identity.canonical_url to be a URL, and custom algorithms rely on user +// input or on the metadata below for it, so the form validates here. export const isLikelyCanonicalUrl = value => { if(!value || typeof value !== 'string') return false return /^https?:\/\/[^\s]+$/i.test(value.trim()) } -// Omit an absent or invalid canonical so an existing form value is preserved. -export const metadataFields = data => ({ +// Omit an absent or invalid canonical, and never replace one the user already filled in. +export const metadataFields = (data, current = {}) => ({ id: data.ID || data.id || '', name: data.name || '', description: data.description || '', - ...(isLikelyCanonicalUrl(data.canonical_url) ? { canonical_url: data.canonical_url.trim() } : {}), + ...(isLikelyCanonicalUrl(data.canonical_url) && !current.canonical_url?.trim() ? { canonical_url: data.canonical_url.trim() } : {}), }) const isMetadata = response => {