diff --git a/CHANGELOG.md b/CHANGELOG.md index 3065f652..0e7986b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- IPS: clinical profiles have guided input - questions for the people filling a document in, about a section. A profile with any contains a Questionnaire (`#Q`) and has an `input-guide` extension (`http://www.healthintersections.com.au/fhir/StructureDefinition/input-guide`) for each guide: the Questionnaire, its questions' linkIds (made and kept by the server), the section (a Coding), and optionally the resource the answers make (`Condition:problem`, `Condition:diagnosis`, `Observation:vitals`, `MedicationStatement`, `AllergyIntolerance`) and its code. A question is text, a type (`display`, `boolean`, `quantity` with optional units, `date`, `choice` with its answer Codings) and optionally a definition (a path in a resource). The profile page shows them as a table grouped by section (IPS order, then the others), and the administrator adds, edits, deletes and moves them within a section a guide at a time, in a dialog. Uploads keep their guided input, and are refused if it is more than this or names a question the Questionnaire doesn't have - Keys: a key store for the whole server (`keystore`, off unless enabled; [library/keystore/README.md](library/keystore/README.md)). `/keys` lists public keys for anyone, and as a JWKS (`/keys/jwks.json`). A logged in user can upload public keys (PEM, a certificate, a JWK or JWKS, an OpenSSH line, DER), claiming a key id or not, and have the server make key pairs for them (EC P-256, EC P-384, RSA, Ed25519; one of each type), whose private keys the server keeps and signs with when a module asks; the administrator makes the system's own key pairs. Private keys are never uploaded (an upload with one is refused) and never given out. Owners revoke their keys, administrators revoke, delete and change key ids. A key is shown only as uploaded or created by its owner's display name. Limits: 10 uploads, then one a day; one key pair a day of each type. Private keys are in a database of their own (`keystore-private.db`, 0600). The daily report has a paragraph on them. Modules sign with `keystore.sign`/`signJws` and check with `verify`/`verifyJws`; there is no endpoint that signs what it is given - IPS: a first processing step, signatures, checks the document's signatures, with keys from the key store (by key id, or by the key a signature's certificate carries, which may have been revoked here), and shows what it found at the top of the analysis view. The check itself (`ips/signatures.js`) is not written yet, and says so - IPS: a document's source view has a banner with what can be done with the copy shown (the original, or the modified copy): download it as JSON, a ZIP, or a PDF with the document attached, and share it as an SHL or a VHL. The Download link at the top of the document page has moved there. `?download=1&source=modified` (and `?_format=json&source=modified`) gives the modified copy @@ -25,7 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - IPS: a Patient Comments tab on a document, for any comments the patient wishes to make about the accuracy or appropriateness of its content (a diagnosis in the problems section, say). One comment per document, in pure markdown (CommonMark): a comment with any HTML in it is refused; everyone can see it, anyone logged in can write, replace or remove it. It is kept apart from the document and its processing results, so processing again leaves it alone; deleting the document deletes it. To keep the document's tabs on one line, National Profiles is now Jurisdictions and AI Assessment is AI Check, and the tabs are a little closer together - IPS: when a document has patient comments, the source view's banner offers "Include Patient Comments", which, like the Sign choices, applies to every download (JSON, ZIP, PDF) and share (SHL, VHL). Any patient notes section (LOINC 51855-5) in the document is removed before signing; after signing, the comments go in as the Composition's first section - code LOINC 51855-5, title "Patient's Comments", the patient as author, and the comments as narrative (status `additional`), nothing else - so they are not signed. The signatures step checks a document's signatures with any patient notes section removed, for the same reason; and a patient notes section a document arrives with becomes its patient comment, converted to markdown (new dependency: turndown), when it has none yet. `{document}/signed` and `{document}/share` take `comments` - IPS: the source view's banner also offers "Regenerate narrative": the server generates the narrative of the copy downloaded or shared as the narrative step does (the narrative tab's Generated), before it is signed. `{document}/signed` and `{document}/share` take `narrative` -- IPS: `$document` on a stored document (`GET {project}/Bundle/{id}/$document`, or POST a Parameters resource) gives the API what the source view's banner gives a browser. Parameters `source` (original | modified), `user-sign` (as the owner of the API token; 401 without one, 409 with no key pair), `system-sign`, `patient-notes` (nothing added, and no error, when there are none) and `regenerate-narrative`. By `Accept` or `_format`: the JSON (the default), `application/zip`, `application/pdf`, or an SHL (`application/smart-health-link`) or VHL (`application/verified-health-link`) - the QR code as a PNG, with the link, manifest and expiry in `X-Health-Link*` headers. The ZIP and PDF are made on the server (`ips/export.js`; the PDF is the browser's content laid out as text in the standard fonts, with the document attached). Same rate limit as sharing. Its OperationDefinition is `ips/OperationDefinition-ips-document.json`, which the CapabilityStatement refers to on GitHub +- IPS: `$document` on a stored document (`GET {project}/Bundle/{id}/$document`, or POST a Parameters resource) gives the API what the source view's banner gives a browser. Parameters `source` (original | modified), `format-type`, `user-sign` (as the owner of the API token; 401 without one, 409 with no key pair), `system-sign`, `patient-notes` (nothing added, and no error, when there are none) and `regenerate-narrative`. What comes back: `format-type` (`json`, `pdf`, `zip`, `shl`, `vhl`) when given, whatever `Accept` says; otherwise `Accept` (or `_format`): the JSON (the default), `application/zip`, `application/pdf`, or `image/png` - a VHL's QR code. An SHL or VHL answer is the QR code (`image/png`), with the link, manifest and expiry in `X-Health-Link*` headers. The ZIP and PDF are made on the server (`ips/export.js`; the PDF is the browser's content laid out as text in the standard fonts, with the document attached). Same rate limit as sharing. Its OperationDefinition is `ips/OperationDefinition-ips-document.json`, which the CapabilityStatement refers to on GitHub - Registry: a code system resolution that finds nothing says, with `unknown-host`, when no server hosts any code system on the url's host, so clients needn't ask about each of that host's code systems (the tx ecosystem IG's Unknown Hosts) - tx: the ecosystem resolver remembers an `unknown-host` answer from the registry, and doesn't ask the registry about other code systems on that host for as long as it remembers a code system it was told nothing about; the cached answers viewer shows the hosts - tx: `$validate-code` on a CodeableConcept says what the ConceptMaps the server can find say about its codings together: for each coding, the maps from its code system to the code system of another coding (packages, libraries, tx-resources, and the maps code systems imply), read forwards, both ways round. A map that says the code is `not-related-to` the other coding, or that it has no map (`noMap`), is a warning; a map that relates it only to other codes is a hint (`TRANSLATION_WARNING_*`). Several maps that say the same thing are named in one message. This is the server side of the core validator's check, with the same messages @@ -34,6 +35,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- IPS: clinical profiles no longer have a full editor (Edit all, and the New profile page): a new profile is made from its title on the list page, renamed on its own page, and its rules and guided input edited there a row at a time +- IPS: the FHIRPath function `section(system, code)` without min and max is `1..1`, as it is in the Java `DocumentFunctions` (the validator's): a document with two of the same section has none, for a rule. It was no bounds. `entry()` and `entryIn()` are still `0..*` +- IPS: clinical profiles' required section rules no longer give the section a cardinality (a `section()` with bounds is now an other rule); instead three checkboxes say what the section must be - must be asked/known (`isKnown()`), must have supporting entries (`hasData()`), about the same Patient (`sameSubject()`). One check on its own is the rule (`Bundle.section(...).isKnown()`); more than one, or any with entries, go in a `where()`. `isKnown()`: no emptyReason, or a nil known one; `hasData()`: an emptyReason, or else entries; `sameSubject()` on a section: no focus, or the focus is the Composition's subject - in `ips/fhirpath-ips.js` (with `sameSubject([other])` on resources too), as in the Java `DocumentFunctions` +- IPS: clinical profiles' section choices include the Patient Story (LOINC 81338-6), and the editor lists the sections alphabetically, with "Another code..." last - tx: LOINC `$lookup` gives a property whose value is a LOINC code (COMPONENT and the other axes, parent, child, AnswerList, Answer, answers-for) the display of that code as its `description` - tx: the HTML view of a `$lookup` response puts its properties and designations in tables of their own, Properties and Designations, below the other parameters, with a column for each part (code, value, description, language, use and so on) instead of a bulleted list in each row. Its `name` parameter is shown as Code System name; a designation's use is shown as its display (Synonym, Fully specified name...), linked to `$lookup` on its code where the server has it, with the system and code in its title; and a Coding's code (a designation's use, say) is linked to `$lookup` on it in whatever code system it is from, if the server has that code system and the code is in it - not only in the code system the response is about - Home page and dashboard graphs: in a cluster, requests per minute, turnaround time, client cache and node blocking are one line for the cluster instead of one per process: requests and client concepts summed (the shared cache counted once), turnaround averaged over the requests, node blocking the worst process's. Private memory is still drawn per process diff --git a/CONFIGURATION.md b/CONFIGURATION.md index c8299d5a..f2d45627 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -117,7 +117,8 @@ with `--role`). Their settings are in `server.cluster`, documented with the arra [cluster.md](cluster.md): the launcher's (`workers`, `maxOutstanding`, `queueSeconds`, `recycleSeconds`, the fast lane, ...) under [The launcher](cluster.md#the-launcher-clusterjs), and what the processes share -(`sharedCache`, `cacheAffinity`, `sharedCacheMaxMB`, `sharedClosure`) under +(`sharedCache`, `cacheAffinity`, `sharedCacheMaxMB`, `sharedClosure`, and `workerModules`, for +workers that serve the rest module too) under [Options](cluster.md#options). With no role, `server.cluster` is ignored. The status panel's snapshot of every process (`statusSeconds`) is under [Status](cluster.md#status). @@ -288,6 +289,7 @@ Each module has its own entry under `modules`, documented with the module: | `packages` - package server | [packages/readme.md](packages/readme.md) | | `shl` - SMART Health Links | [shl/readme.md](shl/readme.md) | | `ips` - IPS documents | [ips/readme.md](ips/readme.md) | +| `rest` - FHIR REST servers | [rest/README.md](rest/README.md#configuration) | | `testing` - test reports | [testing/readme.md](testing/readme.md) | | `folder` | [folder/readme.md](folder/readme.md) | | `npmprojector` | [npmprojector/readme.md](npmprojector/readme.md) | diff --git a/README.md b/README.md index 48f982a9..770c3d60 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ This server provides a set of server-side services that are useful for the FHIR ## Under development, prototyping * [IPS](ips/readme.md) (`ips`) - collections of International Patient Summary documents, each with its own FHIR endpoint, processing (validation, terminology checks, translation, narrative, clinical profiles) and web pages +* [REST](rest/README.md) (`rest`) - database-backed FHIR RESTful servers (SQLite or MySQL): the interactions, search, batch and transaction, AuditEvents, each endpoint configured on its own ## On the back-burner diff --git a/cluster.js b/cluster.js index 6bb0a19a..c0801d40 100644 --- a/cluster.js +++ b/cluster.js @@ -47,7 +47,7 @@ const http = require('http'); const path = require('path'); const { spawn } = require('child_process'); -const { checkInstanceCode, bindAddress, connectAddress, ROLE_TRIM_ALLOCATOR, READY } = require('./library/role'); +const { checkInstanceCode, bindAddress, connectAddress, ROLE_TRIM_ALLOCATOR, READY, workerModules } = require('./library/role'); const { ClusterMetrics, METRIC, SNAPSHOT } = require('./library/cluster-metrics'); const { PendingCounts, COUNTS, COUNTS_INTERVAL_MS } = require('./library/cluster-counts'); const { CacheFanout, ASK: CACHES_ASK, DONE: CACHES_DONE } = require('./library/cluster-caches'); @@ -178,7 +178,9 @@ function loadSettings(argv, env, config, cpu = {}) { return { port, procs, - txPaths: (tx.endpoints || []).map(e => String(e.path).replace(/\/+$/, '')), + // the paths the workers serve: the tx endpoints, and the rest module's when the workers run + // it too (server.cluster.workerModules). Every other path goes to the master + txPaths: [...(tx.endpoints || []).map(e => String(e.path).replace(/\/+$/, '')), ...restPaths(config)], drainMs: Number(cluster.drainSeconds ?? DRAIN_MS / 1000) * 1000, maxOutstanding: Number(cluster.maxOutstanding ?? MAX_OUTSTANDING), queueMs: Number(cluster.queueSeconds ?? QUEUE_MS / 1000) * 1000, @@ -201,6 +203,19 @@ function loadSettings(argv, env, config, cpu = {}) { }; } +/** + * The rest module's endpoint paths, when the workers run it (server.cluster.workerModules): + * any process can serve any rest request, since all its state is in the database. + * @param {Object} config + */ +function restPaths(config) { + const rest = config.modules && config.modules.rest; + if (!rest || !rest.enabled || !workerModules(config).includes('rest')) { + return []; + } + return (rest.endpoints || []).map(e => String(e.path).replace(/\/+$/, '')).filter(p => p); +} + // the path after the tx endpoint ('' for the endpoint itself), or null if not a tx path function txRest(url, txPaths) { let p = String(url).split('?')[0]; diff --git a/cluster.md b/cluster.md index 2097b643..7f066fff 100644 --- a/cluster.md +++ b/cluster.md @@ -71,6 +71,7 @@ as before. | | master | tx-worker | |---|---|---| | tx module (`/r4`, `/r5` and the other endpoints) | yes (may also serve tx requests) | yes | +| rest module (its endpoints), with `"workerModules": ["rest"]` | yes, and its background jobs (schema migrations, expired searches, the closure, reindexing) | yes: every request, since all its state is in its databases | | Every other module (packages, xig, registry, publisher, shl, ips, ...) | yes | no | | Logins (`/auth`, [library/auth](library/auth/README.md)) | yes | the users and sessions are in one database every process reads: a login on one is one on all (with `auth.sessionSecret` set) | | `$closure` (the closure tables) | yes | no: routed to the master (yes, with [`sharedClosure`](#options)) | @@ -525,6 +526,7 @@ both only apply with a role: `node server.js` with no role ignores them. | `server.cluster.sharedCacheMaxMB` | 256 | With `sharedCache`: the most client resources (their JSON, in MB) the file holds, every endpoint's caches together. Past it, the caches least recently used are dropped whole, and a request with a dropped cache-id gets `404` `cache-id-unknown` (`CACHE_ID_EVICTED_SIZE`, which names the cap), so the client starts a new cache. 256: the largest IG Publisher cache session in a corpus of 2,817 from builds against tx.fhir.org held 3.5 MB of resources (p99 2.8 MB, median 55 KB), so this is about 70 times the largest; `cacheMaxTotalConcepts` gives one endpoint about 40 times the largest session's concepts, and this is that room for two busy endpoints. The file on disk is larger than what it holds (indexes, and the pages SQLite keeps for reuse). Each process logs the cap as it starts. 0: no cap. | | `server.cluster.sharedClosure` | false | Every tx process answers `$closure`, on the one closure database. | | `modules.tx.closure.writeRetries` | 10 | With `sharedClosure`: how many times an add is worked out again when another process changed the table first. | +| `server.cluster.workerModules` | `["tx"]` | The modules the workers run besides tx: `"rest"` is the only other one a worker can run. With it, the launcher sends the rest module's endpoints to any process, as it does tx requests. A rest endpoint on SQLite needs every process on this one machine (SQLite's locking is unreliable on network file systems); on MySQL the workers can be anywhere. See [rest/README.md](rest/README.md#clustering). | ### Shared cache diff --git a/config-template.json b/config-template.json index 02dada68..f5d11aa2 100644 --- a/config-template.json +++ b/config-template.json @@ -556,6 +556,27 @@ "autoLoadPackages": true // , "profiles": ["http://hl7.org/fhir/uv/ips/StructureDefinition/Bundle-uv-ips"] } + }, + // Database-backed FHIR RESTful servers. See rest/README.md. config.json says only where + // each endpoint is and which database it uses: everything else about an endpoint is kept + // in its own database. Users get the rest read / write / manage roles per endpoint + "rest": { + "enabled": false, + "endpoints": [ + { + "path": "/fhir/r4", + // fixed when the database is made + "fhirVersion": "4.0.1", + // a SQLite file (relative paths resolve under the databases directory), or MySQL: + // { "type": "mysql", "host": "localhost", "database": "fhir_r4", "user": "fhirsmith", + // "passwordEnv": "FHIR_R4_DB_PASSWORD" } - never a password here: passwordEnv names + // an environment variable, passwordFile a file only the server can read + "database": { "type": "sqlite", "file": "rest/fhir-r4.db" }, + // settings written into a new database (rest/README.md, "Settings"); after that the + // database's own values are used + "initialSettings": { "name": "FHIRsmith R4 test server", "anonymous": "read", "txServer": "/tx/r4" } + } + ] } } } \ No newline at end of file diff --git a/ips/OperationDefinition-ips-document.json b/ips/OperationDefinition-ips-document.json index 57987b29..184352aa 100644 --- a/ips/OperationDefinition-ips-document.json +++ b/ips/OperationDefinition-ips-document.json @@ -9,10 +9,12 @@ "kind": "operation", "date": "2026-11-22", "publisher": "Health Intersections Pty Ltd (FHIRsmith)", - "description": "Returns a document stored in a FHIRsmith IPS project as the web page's source view gives it for download or sharing: optionally with the narrative regenerated, signed by the user and/or the system, and with the patient's comments added - in that order. Any existing patient notes section (LOINC 51855-5) is removed before signing, and the patient's comments are added after signing, as the Composition's first section (LOINC 51855-5), so they are not signed.\n\nThe response is chosen by the Accept header, or by _format (a short name or the mime type):\n\n* application/fhir+json or application/json (json - the default): the document\n* application/zip (zip): a ZIP holding the document as {name}.json\n* application/pdf (pdf): a PDF of the document's narrative, with the document attached as {name}.json\n* application/smart-health-link (shl): the document shared as a SMART Health Link; the response is the QR code as a PNG, with the link in the X-Health-Link header, the manifest URL in X-Health-Link-Manifest, and the expiry in X-Health-Link-Expires\n* application/verified-health-link (vhl): the same, as a Verifiable Health Link (GDHCN)\n\nAnything else is 406. Errors are OperationOutcomes. $document shares the rate limit of the web page's sharing and signed downloads.", + "description": "Returns a document stored in a FHIRsmith IPS project as the web page's source view gives it for download or sharing: optionally with the narrative regenerated, signed by the user and/or the system, and with the patient's comments added - in that order. Any existing patient notes section (LOINC 51855-5) is removed before signing, and the patient's comments are added after signing, as the Composition's first section (LOINC 51855-5), so they are not signed.\n\nWhat comes back is chosen by the format-type parameter, when it is given; otherwise by the Accept header (or _format, which takes the same mime types):\n\n* json - application/fhir+json or application/json (the default): the document\n* zip - application/zip: a ZIP holding the document as {name}.json\n* pdf - application/pdf: a PDF of the document's narrative, with the document attached as {name}.json\n* vhl - image/png: the document shared as a Verifiable Health Link (GDHCN); the response is the QR code as a PNG, with what it carries in the X-Health-Link header, the manifest URL in X-Health-Link-Manifest, and the expiry in X-Health-Link-Expires\n* shl - image/png, with format-type=shl: the same, as a SMART Health Link\n\nAccept: image/png without format-type gives a VHL. Anything else is 406. Errors are OperationOutcomes. $document shares the rate limit of the web page's sharing and signed downloads.", "affectsState": false, "code": "document", - "resource": ["Bundle"], + "resource": [ + "Bundle" + ], "system": false, "type": false, "instance": true, @@ -25,6 +27,14 @@ "documentation": "original (the default): the document as submitted; modified: the copy the processing pipeline made (translations, generated narrative, terminology checks). 409 if the document has not been processed yet", "type": "code" }, + { + "name": "format-type", + "use": "in", + "min": 0, + "max": "1", + "documentation": "What to return: json (the document), pdf, zip, or a QR code (image/png) - shl (a SMART Health Link) or vhl (a Verifiable Health Link, the default for a QR code). When given, it decides, whatever the Accept header (or _format) says", + "type": "code" + }, { "name": "user-sign", "use": "in", diff --git a/ips/fhirpath-ips.js b/ips/fhirpath-ips.js index bcb24887..a5d3004c 100644 --- a/ips/fhirpath-ips.js +++ b/ips/fhirpath-ips.js @@ -34,8 +34,27 @@ * usually asks a terminology server - asynchronously, so the evaluation must be * (evaluateAsync); answers are best cached (membership.js). * - * min and max are optional (together): with neither, there is no constraint; max may - * be '*'. Being outside the bounds is not an error - the item adds nothing. + * isKnown(), hasData() + * The input: sections. isKnown(): each has no emptyReason, or a nil known one + * (list-empty-reason#nilknown) - any other emptyReason is not known. hasData(): each has an + * emptyReason, or else entries. Empty on no input; false for an item that isn't a section + * of a Composition (the one above it, or the document's). + * + * sameSubject([other]) + * On a section: true when it has no focus, otherwise whether the focus is the subject of + * other - or, without other, of its Composition. On a resource: whether its subject (or + * patient) is other's - or, without other, the document's Composition's (the evaluation + * must be on a Bundle of type document). Empty when the input isn't one item, other is + * given but isn't one item, or a subject is missing (or more than one). References are the + * same when their reference strings are identical (both having one), else when their + * identifiers' system and value are (both having one); otherwise not. (other is evaluated + * as fhirpath.js does a function's argument, from the root: use %resource.) + * + * These are the Java DocumentFunctions' (org.hl7.fhir.core), which the validator runs. + * + * min and max are optional (together): with neither, section() is 1..1 (one such section: + * two of the same is none) and entry() and entryIn() are 0..* (no constraint), as in the Java + * DocumentFunctions; max may be '*'. Being outside the bounds is not an error - the item adds nothing. * * References are resolved in the Bundle the section is in: found by walking up from the * section, or else the Bundle the expression was evaluated on (the evaluation's @@ -66,10 +85,13 @@ function num(v) { return v && typeof v === 'object' && typeof v.toNumber === 'function' ? v.toNumber() : v; } -/** min and max from the arguments: min an Integer, max an Integer or '*'. */ -function bounds(fnName, min, max) { +/** + * min and max from the arguments: min an Integer, max an Integer or '*'; without them, the + * function's default (section(): 1..1; the others: 0..*), as the Java DocumentFunctions has them. + */ +function bounds(fnName, min, max, defaults = { min: 0, max: Infinity }) { if (min === undefined) { - return { min: 0, max: Infinity }; + return { ...defaults }; } min = num(min); if (!Number.isInteger(min) || min < 0) { @@ -307,13 +329,73 @@ function membersOf(ctx, fnName, nodes, url, membership) { * Composition, it returns the resource or null. membership: whether a CodeableConcept is * in a value set (a canonical) - without it, entryIn() and resourcesIn() find nothing */ +// ---- the section checks, and sameSubject() -------------------------------------------------- + +const LIST_EMPTY_REASON = 'http://terminology.hl7.org/CodeSystem/list-empty-reason'; + +/** Whether data is one of a Composition's sections, at any depth (by identity). */ +function isSectionOf(comp, data) { + const walk = (list) => Array.isArray(list) && list.some(s => s === data || (isObject(s) && walk(s.section))); + return isObject(comp) && walk(comp.section); +} + +/** + * The Composition an item is a section of, at any depth: the one above it, or the document's + * the evaluation is on (or the Composition it is on) - null when the item isn't a section of one. + */ +function sectionComposition(ctx, item) { + const data = valData(item); + if (!isObject(data) || data.resourceType) { + return null; + } + const above = item instanceof ResourceNode ? ancestor(item, 'Composition') : null; + if (above && isSectionOf(valData(above), data)) { + return valData(above); + } + const roots = Array.isArray(ctx.dataRoot) ? ctx.dataRoot : [ctx.dataRoot]; + for (const r of roots) { + const comp = compositionNode(ctx, r); + if (comp && isSectionOf(valData(comp), data)) { + return valData(comp); + } + } + return null; +} + +/** A resource's subject (or patient), when it has one: null when it has neither, or more than one (R5+ Composition.subject repeats). */ +function subjectOf(resource) { + if (!isObject(resource)) { + return null; + } + const s = resource.subject !== undefined ? resource.subject : resource.patient; + const list = Array.isArray(s) ? s : (s === undefined ? [] : [s]); + return list.length === 1 && isObject(list[0]) ? list[0] : null; +} + +/** + * Whether two references are to the same thing: identical reference strings, when both have one; + * else, when both have an identifier, the same system and value; otherwise false. + */ +function sameReference(a, b) { + const refA = typeof a.reference === 'string' ? a.reference : ''; + const refB = typeof b.reference === 'string' ? b.reference : ''; + if (refA && refB) { + return refA === refB; + } + if (isObject(a.identifier) && isObject(b.identifier)) { + const value = a.identifier.value; + return typeof value === 'string' && value !== '' && value === b.identifier.value && a.identifier.system === b.identifier.system; + } + return false; +} + function ipsFunctions(options = {}) { const resolve = typeof options.resolve === 'function' ? options.resolve : null; const membership = typeof options.membership === 'function' ? options.membership : () => false; function section(inputs, system, code, min, max) { const ctx = this; - const b = bounds('section', min, max); + const b = bounds('section', min, max, { min: 1, max: 1 }); const out = []; for (const item of inputs) { const comp = compositionNode(ctx, item); @@ -367,12 +449,75 @@ function ipsFunctions(options = {}) { const arity = { 2: ['String', 'String'], 4: ['String', 'String', 'Integer', 'Any'] }; // internalStructures: the input and output are nodes, so the paths (and the Bundle a // section is in) are known; and fhirpath.js calls the function with the context as this + // isKnown(): each input a section with no emptyReason, or a nil known one + function isKnown(inputs) { + if (inputs.length === 0) { + return []; + } + return [inputs.every(item => { + if (!sectionComposition(this, item)) { + return false; + } + const reason = valData(item).emptyReason; + return reason === undefined || hasCoding(reason, LIST_EMPTY_REASON, 'nilknown'); + })]; + } + + // hasData(): each input a section with an emptyReason, or else entries + function hasData(inputs) { + if (inputs.length === 0) { + return []; + } + return [inputs.every(item => { + if (!sectionComposition(this, item)) { + return false; + } + const s = valData(item); + return s.emptyReason !== undefined || (Array.isArray(s.entry) && s.entry.length > 0); + })]; + } + + // sameSubject([other]): as the Java DocumentFunctions.sameSubject + function sameSubject(inputs, other) { + if (inputs.length !== 1) { + return []; + } + if (other !== undefined && other.length !== 1) { + return []; + } + const item = inputs[0]; + const comp = sectionComposition(this, item); + if (comp) { + // a section: its focus, if it has one, against the Composition's subject (or other's) + const focus = valData(item).focus; + if (!isObject(focus)) { + return [true]; + } + const target = subjectOf(other !== undefined ? valData(other[0]) : comp); + return target ? [sameReference(focus, target)] : []; + } + let o; + if (other !== undefined) { + o = valData(other[0]); + } else { + const bundle = rootBundle(this); + const doc = bundle ? valData(bundle) : null; + o = doc && doc.type === 'document' ? valData(compositionNode(this, bundle)) : null; + } + const a = subjectOf(valData(item)); + const b = subjectOf(o); + return a && b ? [sameReference(a, b)] : []; + } + return { section: { fn: section, arity, internalStructures: true }, entry: { fn: entry, arity, internalStructures: true }, resources: { fn: resources, arity: { 2: ['String', 'String'], 3: ['String', 'String', 'String'] }, internalStructures: true }, entryIn: { fn: entryIn, arity: { 1: ['String'], 3: ['String', 'Integer', 'Any'] }, internalStructures: true }, - resourcesIn: { fn: resourcesIn, arity: { 1: ['String'], 2: ['String', 'String'] }, internalStructures: true } + resourcesIn: { fn: resourcesIn, arity: { 1: ['String'], 2: ['String', 'String'] }, internalStructures: true }, + isKnown: { fn: isKnown, arity: { 0: [] }, internalStructures: true }, + hasData: { fn: hasData, arity: { 0: [] }, internalStructures: true }, + sameSubject: { fn: sameSubject, arity: { 0: [], 1: ['Any'] }, internalStructures: true } }; } diff --git a/ips/ips.js b/ips/ips.js index 243df3ba..937aa30f 100644 --- a/ips/ips.js +++ b/ips/ips.js @@ -103,19 +103,14 @@ function isOn(v) { // its OperationDefinition (ips/OperationDefinition-ips-document.json), where it is on GitHub const DOCUMENT_OPERATION_DEFINITION = 'https://github.com/HealthIntersections/FHIRsmith/blob/main/ips/OperationDefinition-ips-document.json'; -// what $document gives, by the name _format takes (a short name, or the mime type) -const DOCUMENT_FORMATS = { - json: 'application/fhir+json', - zip: 'application/zip', - pdf: 'application/pdf', - shl: 'application/smart-health-link', - vhl: 'application/verified-health-link' -}; +// what $document gives (format-type), and the mime types (Accept, _format) that ask for each: +// image/png is a QR code - a VHL, unless format-type says shl +const DOCUMENT_FORMAT_TYPES = ['json', 'pdf', 'zip', 'shl', 'vhl']; const DOCUMENT_MIME = { - 'application/fhir+json': 'json', 'application/json': 'json', 'fhir+json': 'json', '*/*': 'json', 'application/*': 'json', - 'application/zip': 'zip', 'application/pdf': 'pdf', - 'application/smart-health-link': 'shl', 'application/verified-health-link': 'vhl' + 'application/fhir+json': 'json', 'application/json': 'json', 'fhir+json': 'json', json: 'json', '*/*': 'json', 'application/*': 'json', + 'application/zip': 'zip', 'application/pdf': 'pdf', 'image/png': 'vhl' }; +const DOCUMENT_ACCEPTS = 'application/fhir+json (or application/json), application/zip, application/pdf, or image/png'; const DOCUMENT_BOOLEANS = { 'user-sign': 'userSign', 'system-sign': 'systemSign', 'patient-notes': 'patientNotes', 'regenerate-narrative': 'regenerateNarrative' }; // the outcome code for each status a copy can fail with const OUTCOME_CODES = { 401: 'login', 404: 'not-supported', 409: 'conflict', 422: 'processing', 429: 'throttled', 503: 'transient' }; @@ -125,7 +120,7 @@ const OUTCOME_CODES = { 401: 'login', 404: 'not-supported', 409: 'conflict', 422 * @returns {{source: string, userSign: boolean, systemSign: boolean, patientNotes: boolean, regenerateNarrative: boolean, problems: string[]}} */ function documentParameters(req) { - const out = { source: 'original', userSign: false, systemSign: false, patientNotes: false, regenerateNarrative: false, problems: [] }; + const out = { source: 'original', formatType: null, userSign: false, systemSign: false, patientNotes: false, regenerateNarrative: false, problems: [] }; const given = []; if (req.method === 'POST') { let b = req.body; @@ -159,6 +154,12 @@ function documentParameters(req) { } else { out.problems.push(`source is original or modified, not '${v}'`); } + } else if (k === 'format-type') { + if (DOCUMENT_FORMAT_TYPES.includes(v)) { + out.formatType = v; + } else { + out.problems.push(`format-type is ${DOCUMENT_FORMAT_TYPES.join(', ')}, not '${v}'`); + } } else if (DOCUMENT_BOOLEANS[k]) { if (v === true || v === 'true') { out[DOCUMENT_BOOLEANS[k]] = true; @@ -166,17 +167,21 @@ function documentParameters(req) { out.problems.push(`${k} is true or false, not '${v}'`); } } else { - out.problems.push(`$document has no parameter '${k}' (it takes source, ${Object.keys(DOCUMENT_BOOLEANS).join(', ')})`); + out.problems.push(`$document has no parameter '${k}' (it takes source, format-type, ${Object.keys(DOCUMENT_BOOLEANS).join(', ')})`); } } return out; } -/** What $document should give: _format (a short name or mime type), else Accept (by preference). @returns {string|null} */ +/** + * What $document should give, when format-type doesn't say: _format (a mime type, or json), else + * Accept (by preference). image/png is a VHL's QR code (format-type=shl for an SHL's). + * @returns {string|null} json, zip, pdf or vhl; null for nothing it gives + */ function documentFormat(req) { const f = typeof req.query._format === 'string' ? req.query._format.trim().toLowerCase().replace(/ /g, '+') : ''; if (f) { - return DOCUMENT_FORMATS[f] ? f : (DOCUMENT_MIME[f] || null); + return DOCUMENT_MIME[f] || null; } const accept = req.get('Accept'); if (!accept) { @@ -635,15 +640,21 @@ class IpsModule { r.get('/lookup', this.session, adminJson, ...this.lookups, h('lookup', (req, res) => this.systemLookup(req, res))); r.get('/lookup-vs', this.session, adminJson, ...this.lookups, h('lookup', (req, res) => this.valueSetLookup(req, res))); r.get('/StructureDefinition', ...this.web, h('profiles', (req, res) => this.profileList(req, res))); - r.get('/StructureDefinition/new', this.session, this.csrf, admin, h('profiles', (req, res) => this.profileEditor(req, res, null))); r.post('/StructureDefinition', this.sameOrigin, this.session, json, this.csrf, adminJson, h('profiles', (req, res) => this.profileSave(req, res, null))); r.get('/StructureDefinition/:id', profile, ...this.web, h('profile', (req, res) => this.profileRead(req, res))); - r.get('/StructureDefinition/:id/edit', profile, this.session, this.csrf, admin, h('profile', (req, res) => this.profileEditor(req, res, req.profile))); + // an old link to the full editor (there is no full editor now): the profile's page + r.get('/StructureDefinition/:id/edit', profile, (req, res) => res.redirect(`${req.baseUrl}/StructureDefinition/${req.profile.id}`)); + r.post('/StructureDefinition/:id/title', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.profileRename(req, res))); r.post('/StructureDefinition/:id', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.profileSave(req, res, req.profile))); // one constraint at a time, from the profile's page: add, edit (keeping its key), delete r.post('/StructureDefinition/:id/constraint', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.constraintSave(req, res, null))); r.post('/StructureDefinition/:id/constraint/:key', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.constraintSave(req, res, req.params.key))); r.post('/StructureDefinition/:id/constraint/:key/delete', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.constraintDelete(req, res))); + // guided input, one guide at a time: add, edit, delete, and move up or down in its section + r.post('/StructureDefinition/:id/guide', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.guideSave(req, res, null))); + r.post('/StructureDefinition/:id/guide/:n', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.guideSave(req, res, req.params.n))); + r.post('/StructureDefinition/:id/guide/:n/delete', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.guideDelete(req, res))); + r.post('/StructureDefinition/:id/guide/:n/move', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.guideMove(req, res))); r.post('/StructureDefinition/:id/delete', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => { this.store.deleteProfile(req.profileId); res.redirect(req.baseUrl + '/StructureDefinition'); @@ -1715,7 +1726,8 @@ class IpsModule { /** * $document on a stored document (GET, or POST with a Parameters resource): the document as the * source view's banner gives it - signed, with the patient's comments, the narrative regenerated - * (preparedCopy) - as JSON, a ZIP, a PDF, or an SHL/VHL QR code (a PNG), by Accept or _format. + * (preparedCopy) - as JSON, a ZIP, a PDF, or an SHL/VHL QR code (image/png), by the format-type + * parameter, else _format or Accept (image/png is a VHL's QR code). * Its OperationDefinition is ips/OperationDefinition-ips-document.json. */ async documentOperation(req, res) { @@ -1728,9 +1740,10 @@ class IpsModule { if (p.problems.length > 0) { return this.sendOutcome(res, 400, 'invalid', p.problems); } - const format = documentFormat(req); + // format-type, when given, decides (over Accept and _format) + const format = p.formatType || documentFormat(req); if (!format) { - return this.sendOutcome(res, 406, 'not-supported', `$document gives ${Object.keys(DOCUMENT_FORMATS).map(k => DOCUMENT_FORMATS[k]).join(', ')}: not ${req.query._format || req.get('Accept')}`); + return this.sendOutcome(res, 406, 'not-supported', `$document gives ${DOCUMENT_ACCEPTS}: not ${req.query._format || req.get('Accept')} (or use format-type)`); } const modified = p.source === 'modified'; const doc = modified ? row.analysed : row.bundle; @@ -2540,8 +2553,9 @@ class IpsModule { const ctx = { ...this.ctx(req, res), valueSetTitle: (url) => this.valueSetTitle(url), profileTitle: (url) => this.profileTitle(url) }; // the administrator edits the rows in place, a row at a time const editor = ctx.user?.isAdmin ? { - constraints: this.editorConstraints(sd), - sections: profiles.IPS_SECTIONS, systems: profiles.SYSTEMS, resourceTypes: profiles.RESOURCE_TYPES, sectionSystem: editorSchema.LOINC, canLookup: !!this.tx + constraints: this.editorConstraints(sd), guides: profiles.guidesOf(sd), + sections: profiles.IPS_SECTIONS, systems: profiles.SYSTEMS, resourceTypes: profiles.RESOURCE_TYPES, sectionSystem: editorSchema.LOINC, canLookup: !!this.tx, + questionTypes: profiles.QUESTION_TYPES, guideResources: profiles.GUIDE_RESOURCES } : null; this.sendHtml(res, `Clinical Profile: ${sd.title}`, render.renderProfile(sd, ctx, editor), Date.now(), req); } @@ -2570,23 +2584,15 @@ class IpsModule { return vs ? (vs.title || vs.name || null) : null; } - /** The editor, for a new profile or an existing one. */ + /** A profile's constraints, with the shapes the profile page's editor shows them in. */ editorConstraints(sd) { return profiles.constraintsOf(sd).map(c => ({ ...c, shape: profiles.parseShape(c.expression), rshape: profiles.parseResourceShape(c.expression) })); } - profileEditor(req, res, sd) { - const constraints = this.editorConstraints(sd); - this.sendHtml(res, sd ? `Edit Clinical Profile: ${sd.title}` : 'New Clinical Profile', - render.renderProfileEditor(sd, this.ctx(req, res), { - profile: { id: sd ? sd.id : null, title: sd ? sd.title : '', constraints }, - sections: profiles.IPS_SECTIONS, systems: profiles.SYSTEMS, resourceTypes: profiles.RESOURCE_TYPES, sectionSystem: editorSchema.LOINC, canLookup: !!this.tx - }), Date.now(), req); - } - /** - * Save a profile from the editor ({title, constraints}), or a new one from an uploaded - * StructureDefinition ({upload}). 200/201 with {id, url}, or 422 with {problems}. + * Save a profile ({title, constraints[, guides]} - a new one can be just a title; without guides, + * a profile keeps its own), or a new one from an uploaded StructureDefinition ({upload}). + * 200/201 with {id, url}, or 422 with {problems}. */ profileSave(req, res, previous) { const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}; @@ -2602,12 +2608,13 @@ class IpsModule { input = up.input; } const checked = profiles.checkInput(input, previous); - if (checked.problems.length) { - return res.status(422).json({ problems: checked.problems }); + const guided = profiles.checkGuides(input.guides !== undefined ? input.guides : profiles.guidesOf(previous), previous); + if (checked.problems.length || guided.problems.length) { + return res.status(422).json({ problems: [...checked.problems, ...guided.problems] }); } const id = previous ? previous.id.substring('profile-'.length) : profiles.newId(); const url = previous ? previous.url : `${this.baseUrl(req)}/StructureDefinition/profile-${id}`; - const sd = profiles.build({ id, url, title: checked.title, constraints: checked.constraints }); + const sd = profiles.build({ id, url, title: checked.title, constraints: checked.constraints, guides: guided.guides }); this.store.saveProfile(id, sd); this.log.info(`IPS module: clinical profile ${sd.id} (${sd.title}) ${previous ? 'saved' : (body.upload !== undefined ? 'uploaded' : 'created')}, ${checked.constraints.length} constraints`); res.status(previous ? 200 : 201).json({ id: sd.id, url: `${req.baseUrl}/StructureDefinition/${sd.id}` }); @@ -2656,8 +2663,97 @@ class IpsModule { } saveConstraints(previous, constraints) { + this.saveProfileParts(previous, { constraints }); + } + + /** Save a profile with some of its parts changed: title, constraints, guides (each as it was when not given). */ + saveProfileParts(previous, parts) { const id = previous.id.substring('profile-'.length); - this.store.saveProfile(id, profiles.build({ id, url: previous.url, title: previous.title, constraints })); + this.store.saveProfile(id, profiles.build({ + id, url: previous.url, + title: parts.title !== undefined ? parts.title : previous.title, + constraints: parts.constraints !== undefined ? parts.constraints : profiles.constraintsOf(previous), + guides: parts.guides !== undefined ? parts.guides : profiles.guidesOf(previous) + })); + } + + /** A new title for a profile (its name follows it), back to the profile's page. */ + profileRename(req, res) { + const previous = req.profile; + const checked = profiles.checkInput({ title: req.body?.title, constraints: [] }, null); + if (checked.problems.length) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(checked.problems.join('; ')), 400); + } + this.saveProfileParts(previous, { title: checked.title }); + this.log.info(`IPS module: clinical profile ${previous.id} renamed '${checked.title}'`); + res.redirect(`${req.baseUrl}/StructureDefinition/${previous.id}`); + } + + /** The guide a request names (:n, its place in the profile's guided input), or -1. */ + guideIndex(req, guides) { + const n = /^\d{1,4}$/.test(req.params.n || '') ? parseInt(req.params.n, 10) : -1; + return n >= 0 && n < guides.length ? n : -1; + } + + /** + * Add an input guide to a profile ({guide}: section, questions, resource, code), or replace + * one (its questions keep their linkIds). 201/200 with {index}, 404 when there is no such + * guide, 422 with {problems}. + */ + guideSave(req, res, n) { + const previous = req.profile; + const guides = profiles.guidesOf(previous); + const at = n === null ? guides.length : this.guideIndex(req, guides); + if (at < 0) { + return res.status(404).json({ problems: [`The profile has no input guide ${n}`] }); + } + const guide = req.body?.guide; + // the guide by itself first, so what is wrong is said of it, not of a number in the list + const alone = profiles.checkGuides([guide], previous); + if (alone.problems.length) { + return res.status(422).json({ problems: alone.problems.map(p => p.replace(/^Input guide 1/, 'The guide')) }); + } + guides.splice(at, n === null ? 0 : 1, guide); + const checked = profiles.checkGuides(guides, previous); + if (checked.problems.length) { + return res.status(422).json({ problems: checked.problems }); + } + this.saveProfileParts(previous, { guides: checked.guides }); + this.log.info(`IPS module: clinical profile ${previous.id}: input guide ${at + 1} ${n === null ? 'added' : 'saved'}`); + res.status(n === null ? 201 : 200).json({ index: at }); + } + + /** Delete an input guide (its questions go from the Questionnaire), back to the profile's page. */ + guideDelete(req, res) { + const previous = req.profile; + const guides = profiles.guidesOf(previous); + const at = this.guideIndex(req, guides); + if (at < 0) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`The profile has no input guide ${req.params.n}`), 404); + } + guides.splice(at, 1); + this.saveProfileParts(previous, { guides }); + this.log.info(`IPS module: clinical profile ${previous.id}: input guide ${at + 1} deleted`); + res.redirect(`${req.baseUrl}/StructureDefinition/${previous.id}#guided-input`); + } + + /** Move an input guide up or down (direction) past the next one in its section, back to the profile's page. */ + guideMove(req, res) { + const previous = req.profile; + const guides = profiles.guidesOf(previous); + const at = this.guideIndex(req, guides); + if (at < 0) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`The profile has no input guide ${req.params.n}`), 404); + } + const key = (g) => `${g.section?.system}|${g.section?.code}`; + const same = guides.map((g, i) => i).filter(i => key(guides[i]) === key(guides[at])); + const k = same.indexOf(at); + const other = req.body?.direction === 'up' ? same[k - 1] : same[k + 1]; + if (other !== undefined) { + [guides[at], guides[other]] = [guides[other], guides[at]]; + this.saveProfileParts(previous, { guides }); + } + res.redirect(`${req.baseUrl}/StructureDefinition/${previous.id}#guided-input`); } // ---- the editor ---- diff --git a/ips/profile-editor.js b/ips/profile-editor.js index 547149f3..364d5b6e 100644 --- a/ips/profile-editor.js +++ b/ips/profile-editor.js @@ -12,20 +12,19 @@ * (Bundle.section(...)[.entry(...) or .entryIn(valueSet...)].exists(), a row of the first * table), rules about resources (Bundle.resources(...) or Bundle.resourcesIn(valueSet...), and * the rest: a row of the second - type, system, code or value set, the rest), and - * other rules (FHIRPath). A row's expression is made from it. Saving posts the title and the - * constraints (key, description, expression); the server checks them, and keeps the keys. - * With cfg.mode 'rows' it is the profile's own page instead: the rows are the page's tables, - * and one at a time is added or edited, in a dialog, and saved by itself. + * other rules (FHIRPath). A row's expression is made from it. The rows are the page's tables: + * one at a time is added or edited, in a dialog, and saved by itself (the server checks it, and + * keeps the keys). So is guided input (cfg.profile.guides): a guide at a time - its section, its + * questions, and the resource and code - in the same dialog, saved to cfg.urls.guide. */ (function () { 'use strict'; var cfg = window.IPS_PROFILE; - var root = document.getElementById('ips-profile-editor'); var LOINC = cfg.sectionSystem; var dirty = false; var saving = false; - // what to draw again when a row's fields change shape: the whole editor, or the row being edited - var redraw = function () { draw(); }; + // what to draw again when a row's fields change shape: the dialog (rowsMode sets it) + var redraw = function () {}; function el(tag, attrs, children) { var e = document.createElement(tag); @@ -37,12 +36,10 @@ } function changed() { dirty = true; } - // ---- the two shapes (as ips/profiles.js has them) ---- + // ---- writing the rules (the shapes are ips/profiles.js's: the page gives each rule's) ---- var STR = "'((?:[^'\\\\]|\\\\.)*)'"; - var ARGS = '\\s*' + STR + '\\s*,\\s*' + STR + "\\s*(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?"; - var CARD = "(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?"; - var SHAPE_RE = new RegExp('^\\s*Bundle\\s*\\.\\s*section\\s*\\(' + ARGS + '\\)\\s*(?:\\.\\s*(?:entry\\s*\\(' + ARGS + '\\)|entryIn\\s*\\(\\s*' + STR + '\\s*' + CARD + '\\))\\s*)?\\.\\s*exists\\s*\\(\\s*\\)\\s*$'); + var SECTION_CHECKS = ['isKnown', 'hasData', 'sameSubject']; var CANONICAL_RE = /^[a-z][a-z0-9+.-]*:[^\s|]{1,250}(\|[^\s|]{1,64})?$/i; // the system chosen for an entry or resources when they are matched by value set, not code var VS = '#vs'; @@ -53,21 +50,6 @@ }); } function quote(s) { return "'" + String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"; } - function card(min, max, hasCard) { return { min: hasCard ? parseInt(min, 10) : null, max: hasCard ? (max === undefined ? '*' : parseInt(max, 10)) : null }; } - function part(system, code, min, max, hasCard) { - var c = card(min, max, hasCard); - return { system: unquote(system), code: unquote(code), min: c.min, max: c.max }; - } - function parseShape(expression) { - var m = SHAPE_RE.exec(expression || ''); - if (!m) { return null; } - var entry = null; - if (m[5] !== undefined) { entry = part(m[5], m[6], m[7], m[8], m[7] !== undefined); } else if (m[9] !== undefined) { - var c = card(m[10], m[11], m[10] !== undefined); - entry = { valueSet: unquote(m[9]), min: c.min, max: c.max }; - } - return { section: part(m[1], m[2], m[3], m[4], m[3] !== undefined), entry: entry }; - } function cardText(p) { return p.min === null || p.min === undefined ? '' : p.min + '..' + p.max; } function parseCard(text) { if (!text || !text.trim()) { return { min: null, max: null }; } @@ -79,16 +61,6 @@ } function cardArgs(c) { return c.min !== null ? ', ' + c.min + ', ' + (c.max === '*' ? "'*'" : c.max) : ''; } function args(system, code, c) { return quote(system) + ', ' + quote(code) + cardArgs(c); } - var TYPE = "\\s*(?:,\\s*'([A-Z][A-Za-z]{1,63})'\\s*)?"; - var REST = '\\s*(\\.\\s*\\S[\\s\\S]*?)\\s*$'; - var RSHAPE_RE = new RegExp('^\\s*Bundle\\s*\\.\\s*resources\\s*\\(\\s*' + STR + '\\s*,\\s*' + STR + TYPE + '\\)' + REST); - var RSHAPE_IN_RE = new RegExp('^\\s*Bundle\\s*\\.\\s*resourcesIn\\s*\\(\\s*' + STR + TYPE + '\\)' + REST); - function parseResourceShape(expression) { - var m = RSHAPE_RE.exec(expression || ''); - if (m) { return { type: m[3] || null, system: unquote(m[1]), code: unquote(m[2]), rest: m[4] }; } - m = RSHAPE_IN_RE.exec(expression || ''); - return m ? { type: m[2] || null, valueSet: unquote(m[1]), rest: m[3] } : null; - } // ---- the rows: mode 'section' (the first table), 'resource' (the second) or 'text' ---- @@ -96,7 +68,7 @@ var shape = c.shape || null; var rshape = c.rshape || null; var r = { key: c.key || null, human: c.human || '', expression: c.expression || '', mode: shape ? 'section' : (rshape ? 'resource' : 'text') }; - tableFields(r, shape || { section: { system: LOINC, code: '', min: null, max: null }, entry: null }); + tableFields(r, shape || { section: { system: LOINC, code: '', checks: [] }, entry: null }); resourceFields(r, rshape || { type: null, system: cfg.systems[0].url, code: '', rest: '.exists()' }); return r; } @@ -135,7 +107,8 @@ var e = shape.entry; r.secSystem = shape.section.system; r.secCode = shape.section.code; - r.secCard = cardText(shape.section); + r.secChecks = {}; + SECTION_CHECKS.forEach(function (c) { r.secChecks[c] = (shape.section.checks || []).indexOf(c) >= 0; }); r.secDisplay = ''; r.entSystem = !e ? '' : (e.valueSet !== undefined ? VS : e.system); r.entCode = e && e.valueSet === undefined ? e.code : ''; @@ -147,12 +120,10 @@ /** The row's expression, from its table, or null with what is wrong. */ function tableExpression(r) { var problems = []; - var sc = parseCard(r.secCard); var ec = parseCard(r.entCard); var byVs = r.entSystem === VS; if (!r.secSystem.trim()) { problems.push('secSystem'); } if (!r.secCode.trim()) { problems.push('secCode'); } - if (!sc) { problems.push('secCard'); } if (r.entSystem.trim() || r.entCode.trim() || r.entCard.trim()) { if (byVs) { if (!CANONICAL_RE.test(r.entVs.trim())) { problems.push('entVs'); } @@ -163,13 +134,15 @@ if (!ec) { problems.push('entCard'); } } if (problems.length) { return { expression: null, problems: problems }; } - var x = 'Bundle.section(' + args(r.secSystem.trim(), r.secCode.trim(), sc) + ')'; - if (byVs) { x += '.entryIn(' + quote(r.entVs.trim()) + cardArgs(ec) + ')'; } else if (r.entSystem.trim()) { x += '.entry(' + args(r.entSystem.trim(), r.entCode.trim(), ec) + ')'; } - return { expression: x + '.exists()', problems: [] }; + // one check on its own is the rule; more than one, or any with entries, go in a where() + var checks = SECTION_CHECKS.filter(function (c) { return r.secChecks[c]; }); + var x = 'Bundle.section(' + quote(r.secSystem.trim()) + ', ' + quote(r.secCode.trim()) + ')'; + var entry = byVs ? '.entryIn(' + quote(r.entVs.trim()) + cardArgs(ec) + ')' : (r.entSystem.trim() ? '.entry(' + args(r.entSystem.trim(), r.entCode.trim(), ec) + ')' : ''); + if (!entry && checks.length === 1) { return { expression: x + '.' + checks[0] + '()', problems: [] }; } + if (checks.length) { x += '.where(' + checks.map(function (c) { return c + '()'; }).join(' and ') + ')'; } + return { expression: x + entry + '.exists()', problems: [] }; } - var state = { title: cfg.profile.title || '', rows: (cfg.profile.constraints || []).map(rowFrom) }; - // ---- a code, looked up in a system ---- function codeInput(r, codeField, displayField, systemOf, onChange) { @@ -308,6 +281,20 @@ return wrap; } + // what the section must be: asked/known (isKnown()), with supporting entries (hasData()), + // about the document's patient (sameSubject()) - checkboxes in a row + var CHECK_LABELS = { isKnown: 'must be asked/known', hasData: 'must have supporting entries', sameSubject: 'about the same Patient' }; + function sectionChecks(r, onChange) { + var row = el('div', { class: 'ips-pf-checks' }); + SECTION_CHECKS.forEach(function (c) { + var box = el('input', { type: 'checkbox' }); + box.checked = !!r.secChecks[c]; + box.addEventListener('change', function () { r.secChecks[c] = box.checked; changed(); onChange(); }); + row.appendChild(el('label', { class: 'ips-pf-check', title: c + '()' }, [box, ' ' + CHECK_LABELS[c]])); + }); + return row; + } + function cardInput(r, field, onChange) { var input = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'any', title: 'blank for any number, or min..max (1..1, 1..*)' }); input.value = r[field]; @@ -319,7 +306,9 @@ function sectionCell(r, onChange) { var cell = el('div'); var select = el('select', { class: 'form-control ips-ed-input' }); - cfg.sections.forEach(function (s) { select.appendChild(el('option', { value: s.code, text: 'Section: ' + s.title })); }); + // by title, then another code last + cfg.sections.slice().sort(function (a, b) { return a.title.localeCompare(b.title); }) + .forEach(function (s) { select.appendChild(el('option', { value: s.code, text: 'Section: ' + s.title })); }); select.appendChild(el('option', { value: '', text: 'Another code...' })); var isIps = r.secSystem === LOINC && cfg.sections.some(function (s) { return s.code === r.secCode; }); if (!r.secCode) { r.secSystem = LOINC; r.secCode = cfg.sections[0].code; isIps = true; } @@ -428,157 +417,6 @@ return cell; } - function drawRow(r, n) { - var box = el('div', { class: 'ips-pf-row' }); - var human = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'What is expected (shown to people)' }); - human.value = r.human; - human.addEventListener('input', function () { r.human = human.value; changed(); }); - var toggle = el('a', { href: '#', class: 'ips-small', text: r.mode === 'text' ? 'Edit as table' : 'Edit as FHIRPath' }); - toggle.addEventListener('click', function (e) { - e.preventDefault(); - if (r.mode !== 'text') { - var t = rowExpression(r); - if (t.expression) { r.expression = t.expression; } - r.mode = 'text'; - } else { - var shape = parseShape(r.expression); - var rshape = shape ? null : parseResourceShape(r.expression); - if (!shape && !rshape) { - window.alert('This rule is not one the tables can show: Bundle.section(...).exists(), Bundle.section(...).entry(...).exists() or .entryIn(...).exists(), or Bundle.resources(...) or Bundle.resourcesIn(...) and the rest of the rule'); - return; - } - if (shape) { tableFields(r, shape); r.mode = 'section'; } else { resourceFields(r, rshape); r.mode = 'resource'; } - } - changed(); - draw(); - }); - var remove = el('button', { type: 'button', class: 'btn btn-default ips-btn', style: 'font-size: 85%; padding: 1px 8px', text: 'Remove' }); - remove.addEventListener('click', function () { state.rows.splice(state.rows.indexOf(r), 1); changed(); draw(); }); - box.appendChild(el('div', { class: 'ips-pf-head' }, [el('b', { text: String(n) + '.' }), human, toggle, remove])); - if (r.mode === 'text') { - var text = el('textarea', { class: 'form-control ips-ed-input', rows: 2, placeholder: 'A FHIRPath expression on the document (the Bundle), true when it meets the expectation', style: 'font-family: monospace; width: 100%' }); - text.value = r.expression; - text.addEventListener('input', function () { r.expression = text.value; changed(); }); - box.appendChild(text); - return box; - } - var exprLine = el('div', { class: 'ips-pf-expr' }); - var fields = {}; - var update = function () { - var t = rowExpression(r); - exprLine.textContent = t.expression || '(incomplete)'; - Object.keys(fields).forEach(function (k) { fields[k].classList.toggle('ips-pf-bad', t.problems.indexOf(k) >= 0); }); - }; - var grid; - if (r.mode === 'section') { - var sec = sectionCell(r, update); - var ent = entryCell(r, update); - fields.secCard = cardInput(r, 'secCard', update); - fields.entCard = cardInput(r, 'entCard', update); - if (ent.code) { fields.entCode = ent.code.input; } - if (ent.vs) { fields.entVs = ent.vs.input; } - grid = el('table', { class: 'ips-pf-grid' }, [ - el('tr', {}, [el('th', { text: 'Section' }), el('th', { text: 'Cardinality' }), el('th', { text: 'Entries' }), el('th', { text: 'Cardinality' })]), - el('tr', {}, [el('td', {}, [sec]), el('td', { class: 'ips-pf-card' }, [fields.secCard]), el('td', {}, [ent]), el('td', { class: 'ips-pf-card' }, [fields.entCard])]) - ]); - } else { - var type = typeCell(r, update); - var system = systemCell(r, update); - var byVs = r.resSystem === VS; - var code = byVs ? vsInput(r, 'resVs', 'resVsTitle', update) : codeInput(r, 'resCode', 'resDisplay', function () { return r.resSystem; }, update); - var rest = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: '.exists()', style: 'font-family: monospace; width: 100%', title: 'The rest of the rule: FHIRPath on the resources found, starting with a dot' }); - rest.value = r.resRest; - rest.addEventListener('input', function () { r.resRest = rest.value; changed(); update(); }); - fields.resType = type.other; - fields.resSystem = system.url; - fields[byVs ? 'resVs' : 'resCode'] = code.input; - fields.resRest = rest; - grid = el('table', { class: 'ips-pf-grid' }, [ - el('tr', {}, [el('th', { text: 'Type' }), el('th', { text: 'System' }), el('th', { text: byVs ? 'Value set' : 'Code' }), el('th', { text: 'Rule' })]), - el('tr', {}, [el('td', { style: 'width: 16%' }, [type]), el('td', { style: 'width: 18%' }, [system]), el('td', { style: byVs ? 'width: 34%' : 'width: 22%' }, [code]), el('td', {}, [rest])]) - ]); - } - box.appendChild(grid); - box.appendChild(exprLine); - update(); - return box; - } - - var ADD_LABELS = { section: 'Add a required section/entry', resource: 'Add a rule about resources', text: 'Add another rule' }; - var MODE_OF_PART = { section: 'section', resource: 'resource', other: 'text' }; - var messages = el('div'); - - /** The rows as the page shows them: the parts in order. */ - function ordered() { - var out = []; - cfg.parts.forEach(function (p) { state.rows.forEach(function (r) { if (r.mode === MODE_OF_PART[p[0]]) { out.push(r); } }); }); - return out; - } - - function draw() { - root.innerHTML = ''; - var title = el('input', { type: 'text', class: 'form-control', placeholder: 'The profile\'s title, e.g. Cardiology referral', style: 'font-size: 110%; font-weight: bold' }); - title.value = state.title; - title.addEventListener('input', function () { state.title = title.value; changed(); }); - root.appendChild(el('div', { class: 'ips-banner' }, [el('label', { class: 'ips-small', text: 'Title' }), title])); - var n = 0; - cfg.parts.forEach(function (p) { - var mode = MODE_OF_PART[p[0]]; - root.appendChild(el('h4', { text: p[1] })); - var these = state.rows.filter(function (r) { return r.mode === mode; }); - if (!these.length) { root.appendChild(el('p', { class: 'ips-small', text: 'None.' })); } - these.forEach(function (r) { root.appendChild(drawRow(r, ++n)); }); - root.appendChild(el('div', { class: 'ips-actions-line' }, [el('button', { type: 'button', class: 'btn btn-default', text: ADD_LABELS[mode], onclick: function () { - var r = rowFrom({}); - r.mode = mode; - state.rows.push(r); - changed(); - draw(); - } })])); - }); - root.appendChild(messages); - root.appendChild(el('div', { class: 'ips-actions-line' }, [ - el('button', { type: 'button', class: 'btn btn-primary', text: 'Save', onclick: save }), ' ', - el('a', { class: 'btn btn-default', href: cfg.urls.back, text: 'Cancel' }) - ])); - } - - function show(problems, kind) { - messages.innerHTML = ''; - if (!problems.length) { return; } - var box = el('div', { class: 'alert alert-' + (kind || 'danger') }); - if (problems.length === 1) { box.textContent = problems[0]; } else { - box.appendChild(el('ul', { style: 'margin: 0' }, problems.map(function (p) { return el('li', { text: p }); }))); - } - messages.appendChild(box); - } - - function save() { - if (saving) { return; } - var problems = []; - // in the page's order, so the numbers in the server's messages are the page's - var constraints = ordered().map(function (r, i) { - var t = rowExpression(r); - if (!t.expression && r.mode !== 'text') { problems.push('Rule ' + (i + 1) + ' is incomplete (the fields in red)'); } - return { key: r.key, human: r.human, expression: t.expression || '' }; - }); - if (!state.title.trim()) { problems.unshift('The profile needs a title'); } - if (problems.length) { show(problems); return; } - saving = true; - show(['Saving...'], 'info'); - fetch(cfg.urls.save, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, - body: JSON.stringify({ title: state.title, constraints: constraints, _csrf: cfg.csrf }) }) - .then(function (res) { - return res.json().then(function (j) { return { ok: res.ok, j: j }; }, function () { return { ok: false, j: { problems: ['The server answered ' + res.status + (res.status === 403 ? ' (has your session expired? reload the page)' : '')] } }; }); - }) - .then(function (a) { - saving = false; - if (a.ok) { dirty = false; location.href = a.j.url; return; } - show(a.j.problems || ['The profile was not saved']); - }) - .catch(function (e) { saving = false; show(['The profile was not saved: ' + e.message]); }); - } - // ---- the profile's page: a rule at a time, added or edited in a dialog ---- // what must be true of the resources a rule is about: the rest of the rule, by kind @@ -651,6 +489,117 @@ return { expression: t.rest ? e.expression : null, problems: t.problems.concat(e.problems.filter(function (p) { return p !== 'resRest'; })) }; } + // ---- guided input: a guide (its section, questions, resource and code) as the dialog edits it ---- + + var UCUM = 'http://unitsofmeasure.org'; + var TYPE_LABELS = { display: 'Text to show', boolean: 'Yes / no', quantity: 'Quantity', date: 'Date', choice: 'Choice' }; + + function copyCoding(c) { return c ? { system: c.system || '', code: c.code || '', display: c.display || '' } : { system: '', code: '', display: '' }; } + function guideRow(g, index) { + g = g || {}; + var r = { mode: 'guide', index: index, key: index === null ? null : 'guide' }; + var s = g.section || {}; + r.secSystem = s.system || LOINC; + r.secCode = s.code || ''; + r.secDisplay = s.display || ''; + r.secChecks = {}; + r.questions = (g.questions || []).map(function (q) { + return { linkId: q.linkId || null, text: q.text || '', type: q.type || 'boolean', definition: q.definition || '', + answers: (q.answers || []).map(copyCoding), units: (q.units || []).map(copyCoding) }; + }); + if (!r.questions.length) { r.questions.push({ linkId: null, text: '', type: 'boolean', definition: '', answers: [], units: [] }); } + r.resource = g.resource || ''; + r.code = copyCoding(g.code); + return r; + } + function codingOut(c) { + var out = { system: (c.system || '').trim(), code: (c.code || '').trim() }; + if (c.display) { out.display = c.display; } + return out; + } + /** What the server is sent for a guide. */ + function guidePayload(r) { + var section = codingOut({ system: r.secSystem, code: r.secCode, display: r.secDisplay }); + return { + section: section, + questions: r.questions.map(function (q) { + return { linkId: q.linkId, text: q.text, type: q.type, definition: q.definition.trim(), + answers: q.type === 'choice' ? q.answers.map(codingOut) : [], units: q.type === 'quantity' ? q.units.map(codingOut) : [] }; + }), + resource: r.resource || null, + code: r.resource && r.code.code.trim() ? codingOut(r.code) : null + }; + } + /** A Coding: a system (a named one, or another by URL) and a code, looked up in it. */ + function codingPicker(c, onChange, defaultSystem) { + if (!c.system) { c.system = defaultSystem || cfg.systems[0].url; } + var cell = el('div', { class: 'ips-pf-coding' }); + var select = el('select', { class: 'form-control ips-ed-input' }); + cfg.systems.forEach(function (sy) { select.appendChild(el('option', { value: sy.url, text: sy.name })); }); + select.appendChild(el('option', { value: '*', text: 'Another system...' })); + var named = cfg.systems.some(function (sy) { return sy.url === c.system; }); + select.value = named ? c.system : '*'; + var url = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'code system URL', 'aria-label': 'Code system URL' }); + url.value = named ? '' : c.system; + url.hidden = named; + url.addEventListener('input', function () { c.system = url.value.trim(); changed(); onChange(); }); + select.addEventListener('change', function () { + url.hidden = select.value !== '*'; + c.system = select.value === '*' ? url.value.trim() : select.value; + changed(); + onChange(); + }); + cell.appendChild(el('div', { class: 'ips-pf-pair' }, [select, url])); + cell.appendChild(codeInput(c, 'code', 'display', function () { return c.system; }, onChange)); + return cell; + } + function smallButton(text, title, onclick) { + return el('button', { type: 'button', class: 'btn btn-default ips-btn', title: title, 'aria-label': title, text: text, onclick: onclick }); + } + /** A list of Codings: each with a Remove button, and an Add button. */ + function codingList(list, label, onChange, defaultSystem) { + var box = el('div'); + list.forEach(function (c, i) { + box.appendChild(el('div', { class: 'ips-pf-list-row' }, [codingPicker(c, onChange, defaultSystem), + smallButton('×', 'Remove this ' + label, function () { list.splice(i, 1); changed(); redraw(); })])); + }); + box.appendChild(smallButton('Add ' + (label === 'answer' ? 'an ' : 'a ') + label, 'Add ' + (label === 'answer' ? 'an ' : 'a ') + label, function () { + list.push({ system: '', code: '', display: '' }); + changed(); + redraw(); + })); + return box; + } + /** A question: its text, type and definition, and its answers (a choice) or units (a quantity). */ + function questionBox(r, q, i) { + var box = el('div', { class: 'ips-pf-question' }); + var text = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'The question, as people will read it', 'aria-label': 'Question ' + (i + 1) }); + text.value = q.text; + text.addEventListener('input', function () { q.text = text.value; changed(); }); + var type = el('select', { class: 'form-control ips-ed-input', style: 'flex: none; width: 9em', 'aria-label': 'Question ' + (i + 1) + ' type' }); + (cfg.questionTypes || []).forEach(function (t) { type.appendChild(el('option', { value: t, text: TYPE_LABELS[t] || t })); }); + type.value = q.type; + type.addEventListener('change', function () { q.type = type.value; changed(); redraw(); }); + var move = function (d) { return function () { var t = r.questions[i]; r.questions[i] = r.questions[i + d]; r.questions[i + d] = t; changed(); redraw(); }; }; + var head = [text, type]; + if (i > 0) { head.push(smallButton('↑', 'Move up', move(-1))); } + if (i < r.questions.length - 1) { head.push(smallButton('↓', 'Move down', move(1))); } + if (r.questions.length > 1) { head.push(smallButton('×', 'Delete this question', function () { r.questions.splice(i, 1); changed(); redraw(); })); } + box.appendChild(el('div', { class: 'ips-pf-qhead' }, head)); + var def = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'definition (optional): a path in a resource, e.g. Condition.onset[x]', 'aria-label': 'Question ' + (i + 1) + ' definition', style: 'margin-top: 4px; font-family: monospace' }); + def.value = q.definition; + def.addEventListener('input', function () { q.definition = def.value; changed(); }); + box.appendChild(def); + if (q.type === 'choice') { + box.appendChild(el('div', { class: 'ips-pf-hint', text: 'The answers to choose from:' })); + box.appendChild(codingList(q.answers, 'answer', function () {})); + } else if (q.type === 'quantity') { + box.appendChild(el('div', { class: 'ips-pf-hint', text: 'The units it can be given in (optional):' })); + box.appendChild(codingList(q.units, 'unit', function () {}, UCUM)); + } + return box; + } + function rowsMode() { var MODE = { section: 'section', resource: 'resource', other: 'text' }; var TITLES = { section: 'a required section or entry', resource: 'a rule about resources', text: 'a rule' }; @@ -709,6 +658,7 @@ var e = editing; var r = e.r; dialog.innerHTML = ''; + if (r.mode === 'guide') { drawGuideDialog(e, r); return; } var fields = {}; var exprLine = el('div', { class: 'ips-pf-expr' }); var update = function () { @@ -723,7 +673,7 @@ body.appendChild(field('Expectation', [human], 'What is expected, as people will read it.')); if (r.mode === 'section') { - body.appendChild(field('Section', [sectionCell(r, update), howMany(r, 'secCard', update, fields)])); + body.appendChild(field('Section', [sectionCell(r, update), sectionChecks(r, update)])); var ent = entryCell(r, update); if (ent.code) { fields.entCode = ent.code.input; } if (ent.vs) { fields.entVs = ent.vs.input; } @@ -795,6 +745,59 @@ if (!e.focused) { e.focused = true; human.focus(); } } + /** the dialog for a guide: its section, its questions, and the resource and code */ + function drawGuideDialog(e, r) { + var body = el('div', { class: 'ips-pf-dialog-body' }); + body.appendChild(field('Section', [sectionCell(r, function () {})], 'The section the questions are about.')); + var qs = el('div'); + r.questions.forEach(function (q, i) { qs.appendChild(questionBox(r, q, i)); }); + qs.appendChild(smallButton('Add a question', 'Add a question', function () { + r.questions.push({ linkId: null, text: '', type: 'boolean', definition: '', answers: [], units: [] }); + changed(); + redraw(); + })); + body.appendChild(field('Questions', [qs], 'In the order they are asked. The definition, if given, is the element of the resource the answer goes in.')); + var res = el('select', { class: 'form-control ips-ed-input', 'aria-label': 'Resource' }, [el('option', { value: '', text: '(none)' })]); + (cfg.guideResources || []).forEach(function (x) { res.appendChild(el('option', { value: x.code, text: x.label })); }); + res.value = r.resource; + res.addEventListener('change', function () { r.resource = res.value; changed(); redraw(); }); + body.appendChild(field('Resource', [res], 'The resource the answers make, if any.')); + if (r.resource) { + body.appendChild(field('Code', [codingPicker(r.code, function () {})], 'The resource\'s code (optional).')); + } + body.appendChild(e.msg); + var save = el('button', { type: 'button', class: 'btn btn-primary', text: 'Save', onclick: function () { saveGuide(); } }); + var cancel = el('button', { type: 'button', class: 'btn btn-default', text: 'Cancel', onclick: function () { stop(false); } }); + e.save = save; + dialog.appendChild(el('div', { class: 'ips-pf-dialog-head' }, [ + el('h4', { id: 'ips-pf-dialog-title', text: (r.index === null ? 'Add' : 'Edit') + ' guided input' }), + el('button', { type: 'button', class: 'ips-pf-dialog-x', 'aria-label': 'Close', text: '\u00d7', onclick: function () { stop(false); } }) + ])); + dialog.appendChild(body); + dialog.appendChild(el('div', { class: 'ips-pf-dialog-foot' }, [cancel, ' ', save])); + } + + function saveGuide() { + var e = editing; + if (!e || saving) { return; } + saving = true; + e.save.disabled = true; + showIn(e.msg, ['Saving...'], 'info'); + var url = cfg.urls.guide + (e.r.index === null ? '' : '/' + e.r.index); + fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ guide: guidePayload(e.r), _csrf: cfg.csrf }) }) + .then(function (res) { + return res.json().then(function (j) { return { ok: res.ok, j: j }; }, function () { return { ok: false, j: { problems: ['The server answered ' + res.status + (res.status === 403 ? ' (has your session expired? reload the page)' : '')] } }; }); + }) + .then(function (a) { + saving = false; + if (a.ok) { stop(true); location.hash = 'guided-input'; location.reload(); return; } + e.save.disabled = false; + showIn(e.msg, a.j.problems || ['The guided input was not saved']); + }) + .catch(function (x) { saving = false; e.save.disabled = false; showIn(e.msg, ['The guided input was not saved: ' + x.message]); }); + } + function start(r) { if (editing) { return; } if (r.mode === 'resource') { ruleFields(r); } @@ -843,6 +846,16 @@ if (c) { start(rowFrom(c)); } }); }); + Array.prototype.forEach.call(document.querySelectorAll('.ips-pf-edit-guide'), function (b) { + b.addEventListener('click', function () { + var n = parseInt(b.closest('td').getAttribute('data-guide'), 10); + var g = (cfg.profile.guides || [])[n]; + if (g) { start(guideRow(g, n)); } + }); + }); + Array.prototype.forEach.call(document.querySelectorAll('.ips-pf-add-guide'), function (b) { + b.addEventListener('click', function () { start(guideRow(null, null)); }); + }); Array.prototype.forEach.call(document.querySelectorAll('.ips-pf-add'), function (b) { b.addEventListener('click', function () { var r = rowFrom({}); @@ -853,5 +866,5 @@ } window.addEventListener('beforeunload', function (e) { if (dirty) { e.preventDefault(); e.returnValue = ''; } }); - if (cfg.mode === 'rows') { rowsMode(); } else { draw(); } + rowsMode(); })(); diff --git a/ips/profiles.js b/ips/profiles.js index d1afdb58..d4779188 100644 --- a/ips/profiles.js +++ b/ips/profiles.js @@ -60,8 +60,11 @@ const SYSTEMS = [ { url: 'http://unitsofmeasure.org', name: 'UCUM' } ]; -/** The IPS sections, for the editor's shortcuts and the read-only view. */ -const IPS_SECTIONS = SECTIONS.map(s => ({ code: s.code, title: s.title })); +/** + * The IPS sections, for the editor's shortcuts and the read-only view: the general editor's, and + * the Patient Story (which that editor doesn't make). + */ +const IPS_SECTIONS = [...SECTIONS.map(s => ({ code: s.code, title: s.title })), { code: '81338-6', title: 'Patient Story' }]; function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); @@ -72,8 +75,21 @@ function isObject(v) { const STR = "'((?:[^'\\\\]|\\\\.)*)'"; const ARGS = `\\s*${STR}\\s*,\\s*${STR}\\s*(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?`; const CARD = `(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?`; -// the entry part: entry(system, code [, min, max]) or entryIn(valueSet [, min, max]) -const SHAPE_RE = new RegExp(`^\\s*Bundle\\s*\\.\\s*section\\s*\\(${ARGS}\\)\\s*(?:\\.\\s*(?:entry\\s*\\(${ARGS}\\)|entryIn\\s*\\(\\s*${STR}\\s*${CARD}\\))\\s*)?\\.\\s*exists\\s*\\(\\s*\\)\\s*$`); +// a required section (and entries) rule is Bundle.section(system, code) - no bounds: a section +// with bounds is a rule of its own (other) - then the section's checks, then the entry part: +// Bundle.section(s, c).exists() the section is there +// Bundle.section(s, c).isKnown() one check (no entry part) +// Bundle.section(s, c).where(isKnown() and hasData()).exists() more than one +// Bundle.section(s, c)[.where(checks)].entry(system, code [, min, max]).exists() +// Bundle.section(s, c)[.where(checks)].entryIn(valueSet [, min, max]).exists() +const SECTION_HEAD_RE = new RegExp(`^\\s*Bundle\\s*\\.\\s*section\\s*\\(\\s*${STR}\\s*,\\s*${STR}\\s*\\)`); +// the section checks, in the order they are written +const SECTION_CHECKS = ['isKnown', 'hasData', 'sameSubject']; +const CHECK = '(isKnown|hasData|sameSubject)\\s*\\(\\s*\\)'; +const ONE_CHECK_RE = new RegExp(`^\\s*\\.\\s*${CHECK}\\s*$`); +const WHERE_RE = new RegExp(`^\\s*\\.\\s*where\\s*\\(\\s*(${CHECK.replace(/\(isKnown/, '(?:isKnown')}(?:\\s+and\\s+${CHECK.replace(/\(isKnown/, '(?:isKnown')})*)\\s*\\)`); +const ENTRY_RE = new RegExp(`^\\s*\\.\\s*(?:entry\\s*\\(${ARGS}\\)|entryIn\\s*\\(\\s*${STR}\\s*${CARD}\\))`); +const EXISTS_RE = /^\s*\.\s*exists\s*\(\s*\)\s*$/; // a value set's canonical, as entryIn() and resourcesIn() take it const CANONICAL_RE = /^[a-z][a-z0-9+.-]*:[^\s|]{1,250}(\|[^\s|]{1,64})?$/i; @@ -95,36 +111,65 @@ function part(system, code, min, max, hasCard) { return { system: unquote(system), code: unquote(code), ...card(min, max, hasCard) }; } +/** The checks named in a where(): in their order, or null when one is named twice. */ +function checksIn(list) { + const names = list.split(/\s+and\s+/).map(x => x.replace(/\s*\(\s*\)\s*$/, '').trim()); + return new Set(names).size === names.length ? SECTION_CHECKS.filter(c => names.includes(c)) : null; +} + /** * The parts of an expression in one of the two shapes, or null. - * @returns {{section: {system, code, min, max}, entry: {system, code, min, max}|{valueSet, min, max}|null}|null} - * min and max are null for no bounds; max is a number or '*'; an entry has a system and - * code, or a value set + * @returns {{section: {system, code, checks: string[]}, entry: {system, code, min, max}|{valueSet, min, max}|null}|null} + * checks are isKnown, hasData, sameSubject (in that order); an entry's min and max are null + * for no bounds, max is a number or '*'; an entry has a system and code, or a value set */ function parseShape(expression) { if (typeof expression !== 'string' || expression.length > MAX_EXPRESSION) { return null; } - const m = SHAPE_RE.exec(expression); - if (!m) { + const head = SECTION_HEAD_RE.exec(expression); + if (!head) { return null; } - const section = part(m[1], m[2], m[3], m[4], m[3] !== undefined); - let entry = null; - if (m[5] !== undefined) { - entry = part(m[5], m[6], m[7], m[8], m[7] !== undefined); - } else if (m[9] !== undefined) { - entry = { valueSet: unquote(m[9]), ...card(m[10], m[11], m[10] !== undefined) }; - if (!CANONICAL_RE.test(entry.valueSet)) { + const section = { system: unquote(head[1]), code: unquote(head[2]), checks: [] }; + if (!section.system || !section.code) { + return null; + } + let rest = expression.substring(head[0].length); + const one = ONE_CHECK_RE.exec(rest); + if (one) { + section.checks = [one[1]]; + return { section, entry: null }; + } + const where = WHERE_RE.exec(rest); + if (where) { + const checks = checksIn(where[1]); + if (!checks) { return null; } + section.checks = checks; + rest = rest.substring(where[0].length); } - for (const p of [section, entry].filter(Boolean)) { - if ((p.valueSet === undefined && (!p.system || !p.code)) || (p.min !== null && p.max !== '*' && p.max < p.min)) { + let entry = null; + const m = ENTRY_RE.exec(rest); + if (m) { + if (m[1] !== undefined) { + entry = part(m[1], m[2], m[3], m[4], m[3] !== undefined); + if (!entry.system || !entry.code) { + return null; + } + } else { + entry = { valueSet: unquote(m[5]), ...card(m[6], m[7], m[6] !== undefined) }; + if (!CANONICAL_RE.test(entry.valueSet)) { + return null; + } + } + if (entry.min !== null && entry.max !== '*' && entry.max < entry.min) { return null; } + rest = rest.substring(m[0].length); } - return { section, entry }; + return EXISTS_RE.test(rest) ? { section, entry } : null; } const TYPE = `(?:,\\s*'([A-Z][A-Za-z]{1,63})'\\s*)?`; @@ -175,11 +220,20 @@ function args(p) { return `${quote(p.system)}, ${quote(p.code)}` + cardArgs(p); } -/** The expression for a shape. */ +/** + * The expression for a shape: one check on its own is the rule (Bundle.section(...).isKnown()); + * more than one, or any with an entry part, go in a where() before it. + */ function shapeExpression(shape) { const e = shape.entry; + const checks = SECTION_CHECKS.filter(c => (shape.section.checks || []).includes(c)); + const head = `Bundle.section(${quote(shape.section.system)}, ${quote(shape.section.code)})`; + if (!e && checks.length === 1) { + return `${head}.${checks[0]}()`; + } + const where = checks.length ? `.where(${checks.map(c => `${c}()`).join(' and ')})` : ''; const entry = !e ? '' : (e.valueSet !== undefined ? `.entryIn(${quote(e.valueSet)}${cardArgs(e)})` : `.entry(${args(e)})`); - return `Bundle.section(${args(shape.section)})` + entry + '.exists()'; + return head + where + entry + '.exists()'; } /** A cardinality as written: '' for none, else 'min..max'. */ @@ -302,12 +356,13 @@ function checkInput(input, previous = null) { /** * The StructureDefinition. - * @param {{id: string, url: string, title: string, constraints: Array, date?: string}} p + * @param {{id: string, url: string, title: string, constraints: Array, guides?: Array, date?: string}} p - guides: checked (checkGuides) */ function build(p) { return { resourceType: 'StructureDefinition', id: `profile-${p.id}`, + ...guideResources(p.guides), url: p.url, name: nameFromTitle(p.title), title: p.title, @@ -339,15 +394,15 @@ function constraintsOf(sd) { // what an uploaded StructureDefinition may have: what build() makes, and the metadata a // tool might add that is replaced anyway -const UPLOAD_KEYS = new Set(['resourceType', 'id', 'meta', 'text', 'url', 'version', 'name', 'title', 'status', 'date', 'publisher', +const UPLOAD_KEYS = new Set(['resourceType', 'id', 'meta', 'text', 'contained', 'extension', 'url', 'version', 'name', 'title', 'status', 'date', 'publisher', 'fhirVersion', 'kind', 'abstract', 'type', 'baseDefinition', 'derivation', 'differential']); const ELEMENT_KEYS = new Set(['id', 'path', 'constraint']); const CONSTRAINT_KEYS = new Set(['key', 'severity', 'human', 'expression', 'source']); /** - * An uploaded StructureDefinition, as the editor's input (title and constraints, the - * keys dropped so they are assigned afresh), or the reasons it can't be taken. - * @returns {{input: {title, constraints}|null, problems: string[]}} + * An uploaded StructureDefinition, as the editor's input (title, constraints and guided input, + * the keys and linkIds dropped so they are assigned afresh), or the reasons it can't be taken. + * @returns {{input: {title, constraints, guides}|null, problems: string[]}} */ function fromUpload(sd) { const problems = []; @@ -412,8 +467,369 @@ function fromUpload(sd) { } }); } + const guided = guidesFromUpload(sd); + problems.push(...guided.problems); const title = typeof sd.title === 'string' && sd.title.trim() ? sd.title : (typeof sd.name === 'string' ? sd.name : ''); - return { input: { title, constraints: list.map(c => (isObject(c) ? { human: c.human, expression: c.expression } : c)) }, problems }; + return { input: { title, constraints: list.map(c => (isObject(c) ? { human: c.human, expression: c.expression } : c)), guides: guided.guides }, problems }; +} + +// ---- guided input ---------------------------------------------------------------------------- +// +// A profile's guided input: input-guide extensions on the StructureDefinition, each naming +// questions in the Questionnaire it contains (#Q), the section they are about (a Coding), and +// optionally the kind of resource the answers make and its code. Their order is the extensions'. + +const INPUT_GUIDE = 'http://www.healthintersections.com.au/fhir/StructureDefinition/input-guide'; +const UNIT_OPTION = 'http://hl7.org/fhir/StructureDefinition/questionnaire-unitOption'; +const Q_ID = 'Q'; +const QUESTION_TYPES = ['display', 'boolean', 'quantity', 'date', 'choice']; +// the resources a guide can make: resource type, and the class that says how it is used +const GUIDE_RESOURCES = [ + { code: 'Condition:problem', label: 'Condition (problem)' }, + { code: 'Condition:diagnosis', label: 'Condition (diagnosis)' }, + { code: 'Observation:vitals', label: 'Observation (vital signs)' }, + { code: 'MedicationStatement', label: 'MedicationStatement' }, + { code: 'AllergyIntolerance', label: 'AllergyIntolerance' } +]; +const MAX_GUIDES = 100; +const MAX_QUESTIONS = 50; +const MAX_ANSWERS = 100; +const MAX_TEXT = 1000; +// a question's definition, as the editor has it: a path in a resource (Condition.onset[x], Observation.code.text) +const DEFINITION_RE = /^([A-Z][A-Za-z]{1,63})((?:\.[a-z][A-Za-z0-9]{0,63}(?:\[x\])?){1,8})$/; +const DEFINITION_URI_RE = /^http:\/\/hl7\.org\/fhir\/StructureDefinition\/([A-Z][A-Za-z]{1,63})#(\1(?:\.[a-z][A-Za-z0-9]{0,63}(?:\[x\])?){1,8})$/; + +/** A question's definition as stored: http://hl7.org/fhir/StructureDefinition/{Type}#{path}. */ +function definitionUri(path) { + const m = DEFINITION_RE.exec(path); + return m ? `http://hl7.org/fhir/StructureDefinition/${m[1]}#${path}` : null; +} + +/** A stored definition as the editor shows it (the path), or null when it isn't one of ours. */ +function definitionPath(uri) { + const m = typeof uri === 'string' ? DEFINITION_URI_RE.exec(uri) : null; + return m ? m[2] : null; +} + +/** A new linkId: random, so one is never used again for another question. */ +function newLinkId(used) { + let id; + do { + id = 'q' + crypto.randomBytes(4).toString('hex'); + } while (used.has(id)); + return id; +} + +/** A Coding as given: {system, code[, display]}, or null when it isn't one. */ +function codingOf(c) { + if (!isObject(c)) { + return null; + } + const system = typeof c.system === 'string' ? c.system.trim() : ''; + const code = typeof c.code === 'string' ? c.code.trim() : ''; + if (!system || !code || system.length > 255 || code.length > 255) { + return null; + } + const display = typeof c.display === 'string' && c.display.trim() ? c.display.trim().substring(0, MAX_TEXT) : null; + return display ? { system, code, display } : { system, code }; +} + +/** The contained Questionnaire, or null. */ +function questionnaireOf(sd) { + return (Array.isArray(sd?.contained) ? sd.contained : []).find(r => isObject(r) && r.resourceType === 'Questionnaire' && r.id === Q_ID) || null; +} + +/** A Questionnaire item as the editor has a question. */ +function questionOf(item) { + const ext = Array.isArray(item.extension) ? item.extension : []; + return { + linkId: item.linkId, + text: typeof item.text === 'string' ? item.text : '', + type: item.type, + definition: item.definition !== undefined ? (definitionPath(item.definition) || item.definition) : '', + answers: (Array.isArray(item.answerOption) ? item.answerOption : []).map(a => a?.valueCoding).filter(isObject), + units: ext.filter(e => isObject(e) && e.url === UNIT_OPTION).map(e => e.valueCoding).filter(isObject) + }; +} + +/** The sub-extensions of an extension with a url. */ +function subs(ext, url) { + return (Array.isArray(ext?.extension) ? ext.extension : []).filter(e => isObject(e) && e.url === url); +} + +/** + * A profile's guided input, as the editor has it, in order. + * @returns {Array<{section: Coding, questions: Array<{linkId, text, type, definition, answers, units}>, resource: string|null, code: Coding|null}>} + */ +function guidesOf(sd) { + const items = new Map(); + for (const item of Array.isArray(questionnaireOf(sd)?.item) ? questionnaireOf(sd).item : []) { + if (isObject(item) && typeof item.linkId === 'string') { + items.set(item.linkId, item); + } + } + return (Array.isArray(sd?.extension) ? sd.extension : []).filter(e => isObject(e) && e.url === INPUT_GUIDE).map(ext => ({ + section: subs(ext, 'section')[0]?.valueCoding || null, + questions: subs(ext, 'question').map(e => items.get(e.valueId)).filter(Boolean).map(questionOf), + resource: subs(ext, 'resource')[0]?.valueCode || null, + code: subs(ext, 'code')[0]?.valueCoding || null + })); +} + +/** + * Check guided input from the editor (or an upload), and give each question its linkId: one it + * already has in the profile it replaces is kept, the others get new ones. + * @param {*} list - the guides + * @param {Object|null} previous - the StructureDefinition being replaced + * @returns {{guides: Array, problems: string[]}} + */ +function checkGuides(list, previous = null) { + const problems = []; + if (list === undefined || list === null) { + return { guides: [], problems }; + } + if (!Array.isArray(list)) { + return { guides: [], problems: ['The guided input must be a list'] }; + } + if (list.length > MAX_GUIDES) { + problems.push(`There can be no more than ${MAX_GUIDES} input guides`); + } + const known = new Set(guidesOf(previous).flatMap(g => g.questions.map(q => q.linkId))); + const used = new Set(); + const guides = []; + list.slice(0, MAX_GUIDES).forEach((g, gi) => { + const at = `Input guide ${gi + 1}`; + if (!isObject(g)) { + problems.push(`${at} is not an object`); + return; + } + const section = codingOf(g.section); + if (!section) { + problems.push(`${at} has no section (a system and code)`); + } + const resource = typeof g.resource === 'string' && g.resource ? g.resource : null; + if (resource && !GUIDE_RESOURCES.some(r => r.code === resource)) { + problems.push(`${at} makes a resource this server doesn't know: '${resource}' (${GUIDE_RESOURCES.map(r => r.code).join(', ')})`); + } + let code = null; + if (g.code !== undefined && g.code !== null && g.code !== '') { + code = codingOf(g.code); + if (!code) { + problems.push(`${at} has a code that isn't a system and code`); + } else if (!resource) { + problems.push(`${at} has a code, but no resource: the code is the resource's`); + } + } + const qs = Array.isArray(g.questions) ? g.questions : []; + if (qs.length === 0) { + problems.push(`${at} has no questions`); + } else if (qs.length > MAX_QUESTIONS) { + problems.push(`${at} has more than ${MAX_QUESTIONS} questions`); + } + const questions = []; + qs.slice(0, MAX_QUESTIONS).forEach((q, qi) => { + const qat = `${at}, question ${qi + 1}`; + if (!isObject(q)) { + problems.push(`${qat} is not an object`); + return; + } + const text = typeof q.text === 'string' ? q.text.trim() : ''; + if (!text) { + problems.push(`${qat} has no text`); + } else if (text.length > MAX_TEXT) { + problems.push(`${qat}'s text is longer than ${MAX_TEXT} characters`); + } + const type = q.type; + if (!QUESTION_TYPES.includes(type)) { + problems.push(`${qat} has no type (${QUESTION_TYPES.join(', ')})`); + } + const definition = typeof q.definition === 'string' ? q.definition.trim() : ''; + if (definition && !DEFINITION_RE.test(definition)) { + problems.push(`${qat}'s definition is not a path in a resource, like Condition.onset[x]`); + } + const answers = []; + for (const a of Array.isArray(q.answers) ? q.answers.slice(0, MAX_ANSWERS) : []) { + const c = codingOf(a); + if (c) { + answers.push(c); + } else { + problems.push(`${qat} has an answer that isn't a system and code`); + } + } + const units = []; + for (const u of Array.isArray(q.units) ? q.units.slice(0, MAX_ANSWERS) : []) { + const c = codingOf(u); + if (c) { + units.push(c); + } else { + problems.push(`${qat} has a unit that isn't a system and code`); + } + } + if (type === 'choice' && answers.length === 0) { + problems.push(`${qat} is a choice, but has no answers to choose from`); + } + if (type !== 'choice' && answers.length) { + problems.push(`${qat} has answers, but only a choice can have them`); + } + if (type !== 'quantity' && units.length) { + problems.push(`${qat} has units, but only a quantity can have them`); + } + let linkId = typeof q.linkId === 'string' && known.has(q.linkId) && !used.has(q.linkId) ? q.linkId : null; + if (!linkId) { + linkId = newLinkId(new Set([...known, ...used])); + } + used.add(linkId); + questions.push({ linkId, text, type, definition, answers, units }); + }); + guides.push({ section, questions, resource, code: resource ? code : null }); + }); + return { guides, problems }; +} + +/** The contained Questionnaire and the input-guide extensions for guided input (none for none). */ +function guideResources(guides) { + if (!Array.isArray(guides) || guides.length === 0) { + return {}; + } + const item = guides.flatMap(g => g.questions.map(q => { + const it = {}; + if (q.units && q.units.length) { + it.extension = q.units.map(u => ({ url: UNIT_OPTION, valueCoding: u })); + } + it.linkId = q.linkId; + if (q.definition) { + it.definition = definitionUri(q.definition); + } + it.text = q.text; + it.type = q.type; + if (q.answers && q.answers.length) { + it.answerOption = q.answers.map(a => ({ valueCoding: a })); + } + return it; + })); + return { + contained: [{ resourceType: 'Questionnaire', id: Q_ID, status: 'active', item }], + extension: guides.map(g => ({ + url: INPUT_GUIDE, + extension: [ + { url: 'questionnaire', valueCanonical: `#${Q_ID}` }, + ...g.questions.map(q => ({ url: 'question', valueId: q.linkId })), + { url: 'section', valueCoding: g.section }, + ...(g.resource ? [{ url: 'resource', valueCode: g.resource }] : []), + ...(g.resource && g.code ? [{ url: 'code', valueCoding: g.code }] : []) + ] + })) + }; +} + +const Q_KEYS = new Set(['resourceType', 'id', 'status', 'item']); +const ITEM_KEYS = new Set(['extension', 'linkId', 'definition', 'text', 'type', 'answerOption']); +const GUIDE_SUBS = new Set(['questionnaire', 'question', 'section', 'resource', 'code']); + +/** + * An uploaded profile's guided input, as the editor's (linkIds dropped, so they are assigned + * afresh), and what is wrong with it: anything more than this server makes is refused, as is a + * guide naming a question the Questionnaire doesn't have. + */ +function guidesFromUpload(sd) { + const problems = []; + const exts = sd.extension === undefined ? [] : sd.extension; + if (!Array.isArray(exts) || exts.some(e => !isObject(e) || e.url !== INPUT_GUIDE)) { + problems.push(`Its only extensions may be input guides (${INPUT_GUIDE})`); + return { guides: [], problems }; + } + const contained = sd.contained === undefined ? [] : sd.contained; + if (!Array.isArray(contained) || contained.length > 1 || (contained.length === 1 && !(isObject(contained[0]) && contained[0].resourceType === 'Questionnaire' && contained[0].id === Q_ID))) { + problems.push(`It may contain only the input guides' Questionnaire (#${Q_ID})`); + return { guides: [], problems }; + } + if (exts.length && !contained.length) { + problems.push(`It has input guides, but no Questionnaire (#${Q_ID})`); + return { guides: [], problems }; + } + const q = contained[0]; + const items = new Map(); + if (q) { + const extraQ = Object.keys(q).filter(k => !Q_KEYS.has(k)); + if (extraQ.length) { + problems.push(`Its Questionnaire has more than input guides use: ${extraQ.join(', ')}`); + } + (Array.isArray(q.item) ? q.item : []).forEach((item, i) => { + if (!isObject(item) || typeof item.linkId !== 'string') { + problems.push(`Its Questionnaire's item ${i + 1} has no linkId`); + return; + } + const extra = Object.keys(item).filter(k => !ITEM_KEYS.has(k)); + if (extra.length) { + problems.push(`Question '${item.linkId}' has more than input guides use: ${extra.join(', ')}`); + } + if ((Array.isArray(item.extension) ? item.extension : []).some(e => !isObject(e) || e.url !== UNIT_OPTION)) { + problems.push(`Question '${item.linkId}' has an extension other than ${UNIT_OPTION}`); + } + if ((Array.isArray(item.answerOption) ? item.answerOption : []).some(a => !isObject(a) || Object.keys(a).some(k => k !== 'valueCoding'))) { + problems.push(`Question '${item.linkId}' has an answer that isn't a Coding`); + } + if (item.definition !== undefined && !definitionPath(item.definition)) { + problems.push(`Question '${item.linkId}' has a definition that isn't http://hl7.org/fhir/StructureDefinition/{type}#{path}`); + } + items.set(item.linkId, item); + }); + } + const guides = exts.map((ext, i) => { + const at = `Input guide ${i + 1}`; + const all = Array.isArray(ext.extension) ? ext.extension : []; + const odd = all.filter(e => !isObject(e) || !GUIDE_SUBS.has(e.url)); + if (odd.length || Object.keys(ext).some(k => k !== 'url' && k !== 'extension')) { + problems.push(`${at} has more than questionnaire, question, section, resource and code`); + } + if (subs(ext, 'questionnaire').length !== 1 || subs(ext, 'questionnaire')[0].valueCanonical !== `#${Q_ID}`) { + problems.push(`${at} must name the Questionnaire #${Q_ID}, once`); + } + for (const u of ['section', 'resource', 'code']) { + if (subs(ext, u).length > 1) { + problems.push(`${at} has more than one ${u}`); + } + } + const questions = []; + for (const e of subs(ext, 'question')) { + const item = items.get(e.valueId); + if (!item) { + problems.push(`${at} names question '${e.valueId}', which the Questionnaire doesn't have`); + } else { + const qn = questionOf(item); + delete qn.linkId; + questions.push(qn); + } + } + return { + section: subs(ext, 'section')[0]?.valueCoding, + questions, + resource: subs(ext, 'resource')[0]?.valueCode || null, + code: subs(ext, 'code')[0]?.valueCoding || null + }; + }); + return { guides, problems }; +} + +/** + * The order the guided input is shown in: grouped by section - the IPS sections in their + * order first, then the others as they first appear - and in a section, the guides' own order. + * @returns {Array<{section: Coding, guides: Array<{guide, index}>}>} index: the guide's place in the profile + */ +function guideGroups(guides, ipsOrder) { + const groups = new Map(); + guides.forEach((guide, index) => { + const key = `${guide.section?.system}|${guide.section?.code}`; + if (!groups.has(key)) { + groups.set(key, { section: guide.section, guides: [], first: index }); + } + groups.get(key).guides.push({ guide, index }); + }); + const rank = (g) => { + const i = g.section?.system === LOINC ? ipsOrder.indexOf(g.section.code) : -1; + return i >= 0 ? i : ipsOrder.length + g.first; + }; + return [...groups.values()].sort((a, b) => rank(a) - rank(b)); } /** @@ -499,7 +915,8 @@ function describeResource(r, titleOf) { } module.exports = { - SYSTEMS, IPS_SECTIONS, RESOURCE_TYPES, BUNDLE, MAX_CONSTRAINTS, ID_RE, migrate, + SYSTEMS, IPS_SECTIONS, SECTION_CHECKS, RESOURCE_TYPES, + INPUT_GUIDE, UNIT_OPTION, QUESTION_TYPES, GUIDE_RESOURCES, guidesOf, checkGuides, guideGroups, definitionUri, definitionPath, BUNDLE, MAX_CONSTRAINTS, ID_RE, migrate, parseResourceShape, resourceShapeExpression, kindOf, describeResource, parseShape, shapeExpression, parseCard, cardText, expressionProblem, nameFromTitle, newId, checkInput, build, constraintsOf, fromUpload, describePart diff --git a/ips/readme.md b/ips/readme.md index f5fcfe32..dfb50b59 100644 --- a/ips/readme.md +++ b/ips/readme.md @@ -101,20 +101,21 @@ CapabilityStatement): GET /ips/{code}/Bundle/{id}/$document?source=modified&system-sign=true&patient-notes=true POST /ips/{code}/Bundle/{id}/$document (a Parameters resource) -Parameters: `source` (`original`, the default, or `modified`), and the booleans `user-sign` -(as the owner of the API token in `Authorization: Bearer` - 401 without one, 409 if they have -no key pair to sign with), `system-sign`, `patient-notes` (the patient's comments; nothing -added, and no error, when there are none) and `regenerate-narrative`. The copy is made as the -web page makes it: any patient notes section (LOINC 51855-5) removed, the narrative regenerated, -signed, then the patient's comments added as the first section (not signed). What comes back is -chosen by `Accept`, or `_format` (a short name or the mime type): `application/fhir+json` or -`application/json` (`json`, the default), `application/zip` (`zip`), `application/pdf` -(`pdf`), `application/smart-health-link` (`shl`) or `application/verified-health-link` -(`vhl`); anything else is 406. The ZIP and the PDF are made on the server (`ips/export.js`): -the PDF is the same content as the browser's - the title, the patient, the date and each -section's narrative, with the document attached - laid out as text in the standard PDF fonts -(tables as rows of cells, no images; characters outside Windows-1252 show as `?`). An SHL or -VHL answer is the QR code as a PNG, with the link it carries in `X-Health-Link`, the manifest in +Parameters: `source` (`original`, the default, or `modified`), `format-type` (below), and the +booleans `user-sign` (as the owner of the API token in `Authorization: Bearer` - 401 without one, +409 if they have no key pair to sign with), `system-sign`, `patient-notes` (the patient's +comments; nothing added, and no error, when there are none) and `regenerate-narrative`. The copy +is made as the web page makes it: any patient notes section (LOINC 51855-5) removed, the +narrative regenerated, signed, then the patient's comments added as the first section (not +signed). What comes back is chosen by `format-type` when it is given - `json`, `pdf`, `zip`, +`shl` or `vhl` - whatever `Accept` says; otherwise by `Accept` (or `_format`, which takes the same +mime types): `application/fhir+json` or `application/json` (the default), `application/zip`, +`application/pdf`, or `image/png` (a VHL's QR code; `format-type=shl` for an SHL's); anything +else is 406. The ZIP and the PDF are made on the server (`ips/export.js`): the PDF is the same +content as the browser's - the title, the patient, the date and each section's narrative, with +the document attached - laid out as text in the standard PDF fonts (tables as rows of cells, no +images; characters outside Windows-1252 show as `?`). An SHL or VHL answer is the QR code as a +PNG (`image/png`), with the link it carries in `X-Health-Link`, the manifest in `X-Health-Link-Manifest` and the expiry in `X-Health-Link-Expires`. `$document` shares the rate limit of sharing and of the web page's signed downloads. @@ -779,7 +780,7 @@ come back as a list for the page to show. A clinical profile says what a kind of clinical document is expected to contain. It is a StructureDefinition: a profile on Bundle (the document) with one element, the root, whose constraints are the expectations. Each constraint has a description and a FHIRPath expression on the document. Profiles are shared across all projects (`/ips/StructureDefinition`). Everyone can see them; only the administrator creates, edits, uploads and deletes them. -The administrator edits only the title and the constraints. The server sets everything else: +The administrator edits only the title, the constraints and the guided input (below). The server sets everything else: - the id: `profile-` plus a random private id; - the url: `[base]/ips/StructureDefinition/profile-{id}`, fixed when the profile is made; @@ -790,10 +791,23 @@ The administrator edits only the title and the constraints. The server sets ever Most expectations take one of two shapes, using the module's own [FHIRPath functions](#fhirpath-functions): ``` -Bundle.section(system, code [, min, max]).exists() -Bundle.section(system, code [, min, max]).entry(system, code [, min, max]).exists() +Bundle.section(system, code).exists() +Bundle.section(system, code).isKnown() +Bundle.section(system, code).where(isKnown() and sameSubject()).exists() +Bundle.section(system, code)[.where(checks)].entry(system, code [, min, max]).exists() ``` +The section has no bounds (more than one of the same section is a corner case IPS documents +don't have: a `section()` with bounds is an other rule). What it must be is up to three checks, +in this order: `isKnown()` (must be asked/known), `hasData()` (must have supporting entries) +and `sameSubject()` (about the same Patient). One check on its own is the rule; more than one, +or any with an entry part, go in a `where()`. `isKnown()`: the section has no emptyReason, or a +nil known one (`list-empty-reason#nilknown`) - any other emptyReason is not known. `hasData()`: +the section has an emptyReason, or else entries. `sameSubject()` on a section: it has no focus, +or its focus is the Composition's subject. On no section they give nothing (so the rule fails), +and on anything that isn't a section, false. They are the Java `DocumentFunctions`' (the +validator's) as well as `ips/fhirpath-ips.js`'s. + Rules about the resources in the document, whatever section they are in, take a third shape: ``` @@ -802,20 +816,59 @@ Bundle.resources(system, code [, type]).{the rest of the rule} Entries and resources can be matched by value set instead of by one code: `Bundle.section(...).entryIn(valueSet [, min, max]).exists()`, and `Bundle.resourcesIn(valueSet [, type])...`. Sections are always matched by code. An example rule: `Bundle.resources('http://snomed.info/sct', '38341003', 'Condition').all(clinicalStatus.coding.code = 'active')`. -The editor (`/ips/StructureDefinition/new`, or Edit on a profile) is in three parts, and so is the page that shows a profile: +A new profile is made on the list page (`/ips/StructureDefinition`) from just a title (`POST /ips/StructureDefinition` with `{title}`), and its rules and guided input are added on its own page, which is in four parts: -- **Required sections and entries:** the first two shapes, each a row of a table with four columns (the section, its cardinality, the entry code and its cardinality). +- **Required sections and entries:** the first shape, each a row of a table: the section, with its checks as three checkboxes in a row (must be asked/known, must have supporting entries, about the same Patient), the entry code and its cardinality. - **Rules about resources:** the third shape, each a row of a table with four columns (the type, which is optional, the system, the code, and the rest of the rule as FHIRPath starting with a dot). - **Other rules:** any other FHIRPath. +- **Guided input:** below. -The page that shows a profile is the same for everyone. Its first part is a table of three columns: the **Expectation** (the description), the **Section** (an IPS section by its title, or `system|code`) and the **Entry** (`Code is system|code`, or `Code is in` a value set, by its title, or its URL when the title isn't known). A code system is shown by name when it is a known one. A cardinality, `[m..n]`, follows a section or an entry unless it is `1..1` or not given (none means at least one). The second part is also a table of three columns: the **Expectation**, the **Resource Set** (the type, as `MedicationAdministrations where` or `Any resource where`, then the code as in the Entry column) and the **Rule**, which is the rest of the expression in words where it is one of these: `.exists()` is "Must be present somewhere"; `.all(sameSubject())` is "Patient must match the Document"; `.x.exists()` and `.x.y.exists()` are "Must have an x" and "Must have an x.y" (no deeper); `.conformsTo(url)` (or `.all(conformsTo(url))`) is "Conform to" the profile, named by its title when it is one of the clinical profiles or by its jurisdiction and package when it is a national profile; and `.category.hasCoding(system, code [, version])` (or inside `.all()`) is "Has category system|code". Any other rest is shown as FHIRPath, and so are the other rules. On the same page the administrator edits the rules one at a time: each row has Edit and Delete, and each part has an Add button. Add and Edit open a dialog for the one rule - the expectation, then the parts of the rule, each with what it means (for a rule about resources, what must be true of them is a choice: present somewhere, the patient matches the document's, an element, conformance to a profile, a category, or other FHIRPath), and the FHIRPath it makes - and Save stores that one rule by itself (`POST /ips/StructureDefinition/{id}/constraint` to add, `.../constraint/{key}` to change, `.../constraint/{key}/delete` to delete). An edited rule keeps its key. The full editor is still there (Edit all), for the title, or for many changes at once. +The page that shows a profile is the same for everyone. Its first part is a table of three columns: the **Expectation** (the description), the **Section** (an IPS section by its title, or `system|code`) and the **Entry** (`Code is system|code`, or `Code is in` a value set, by its title, or its URL when the title isn't known). A code system is shown by name when it is a known one. A section's checks follow it, in words (must be asked/known, must have supporting entries, about the same Patient). A cardinality, `[m..n]`, follows an entry unless it is `1..1` or not given (none means at least one). The second part is also a table of three columns: the **Expectation**, the **Resource Set** (the type, as `MedicationAdministrations where` or `Any resource where`, then the code as in the Entry column) and the **Rule**, which is the rest of the expression in words where it is one of these: `.exists()` is "Must be present somewhere"; `.all(sameSubject())` is "Patient must match the Document"; `.x.exists()` and `.x.y.exists()` are "Must have an x" and "Must have an x.y" (no deeper); `.conformsTo(url)` (or `.all(conformsTo(url))`) is "Conform to" the profile, named by its title when it is one of the clinical profiles or by its jurisdiction and package when it is a national profile; and `.category.hasCoding(system, code [, version])` (or inside `.all()`) is "Has category system|code". Any other rest is shown as FHIRPath, and so are the other rules. On the same page the administrator edits the rules one at a time: each row has Edit and Delete, and each part has an Add button. Add and Edit open a dialog for the one rule - the expectation, then the parts of the rule, each with what it means (for a rule about resources, what must be true of them is a choice: present somewhere, the patient matches the document's, an element, conformance to a profile, a category, or other FHIRPath), and the FHIRPath it makes - and Save stores that one rule by itself (`POST /ips/StructureDefinition/{id}/constraint` to add, `.../constraint/{key}` to change, `.../constraint/{key}/delete` to delete). An edited rule keeps its key. Rename changes the title (`POST .../title`; the name follows it). There is no full editor any more: an old link to one (`.../edit`) lands on the profile's page. A rule moves between the parts when it is switched between table and FHIRPath, and it lands in the part whose shape it fits. A section is one of the IPS sections, or any code in any system. An entry or resource code is a code in a named code system (SNOMED CT, LOINC, ICD-10...) or in any other given by URL, and it is looked up on the terminology server (`GET /ips/lookup?system=&q=`, for the administrator only). Choosing "In a value set..." as the system matches entries or resources by value set instead. The code box becomes a value set search (`GET /ips/lookup-vs?q=`, for the administrator only): this module's own value sets that match the title come first, then the terminology server's (a `ValueSet?title=` search). A suggestion shows its title, with its URL underneath. A canonical can also be typed or pasted in, with `|version` to pin a version. When the editor opens, it looks up the title of each value set by URL (`?url=`). If the terminology server doesn't know a value set, it says so as a warning, not an error: the value set has to be known when documents are checked, not when the profile is saved. A cardinality is blank (no bounds) or `min..max`, where max may be `*`. Before a profile is saved, every expression is parsed and run once against an empty document. That catches unknown functions and wrong numbers of arguments as well as syntax errors. -A profile can be downloaded as JSON (`?download=1`), and a downloaded profile can be uploaded again as a new profile, with a new id, url and keys. An upload must be no more than a profile like this: a profile on Bundle with no snapshot, and one differential element (the root) carrying constraints that have only a key, an `error` severity, a description, an expression and a source. Anything more is rejected, with the reasons. A profile downloaded when clinical profiles were on Composition is accepted and moved onto Bundle, as profiles already stored are when the server starts: `Composition.section(...)` becomes `Bundle.section(...)`, and any other `Composition.x` becomes `Bundle.entry.resource.ofType(Composition).x`. +A profile can be downloaded as JSON (`?download=1`), and a downloaded profile can be uploaded again as a new profile, with a new id, url and keys. An upload must be no more than a profile like this: a profile on Bundle with no snapshot, and one differential element (the root) carrying constraints that have only a key, an `error` severity, a description, an expression and a source - and guided input, as below. Anything more is rejected, with the reasons. A profile downloaded when clinical profiles were on Composition is accepted and moved onto Bundle, as profiles already stored are when the server starts: `Composition.section(...)` becomes `Bundle.section(...)`, and any other `Composition.x` becomes `Bundle.entry.resource.ofType(Composition).x`. As FHIR: `GET /ips/StructureDefinition` is a searchset of them all, and `GET /ips/StructureDefinition/{id}` is one of them. +### Guided input + +Guided input is questions for the people filling a document in, about a section. When a profile +has any, it contains a Questionnaire (`#Q`), and has an extension +`http://www.healthintersections.com.au/fhir/StructureDefinition/input-guide` for each guide, in +order, with these sub-extensions: + +- `questionnaire` (canonical, 1..1): `#Q`; +- `question` (id, 1..*): the linkIds of its questions in the Questionnaire, in order. The server + makes them (`q` and 8 random hex digits, so one is never used again), keeps a question's linkId + for as long as the question is kept, and takes a question's item out of the Questionnaire when + the question goes (and the Questionnaire, when the last guide goes). People never see them; +- `section` (Coding, 1..1): the section the questions are about - one of the IPS sections, or any + code, as `system|code`, so sections other than the IPS ones can be guided too; +- `resource` (code, 0..1): what the answers make - `Condition:problem`, `Condition:diagnosis`, + `Observation:vitals`, `MedicationStatement` or `AllergyIntolerance` (the class after the colon + changes how it is used); +- `code` (Coding, 0..1): the resource's code - only with a resource. + +A question has text, a type - `display`, `boolean`, `quantity`, `date` or `choice` - and +optionally a definition: a path in a resource (`Condition.onset[x]`), kept in the +Questionnaire as `http://hl7.org/fhir/StructureDefinition/Condition#Condition.onset[x]`. A +choice has its answers (Codings, as `answerOption`); a quantity may name its units (Codings, +UCUM by default, as `questionnaire-unitOption` extensions). + +The page shows the guided input as a table - Section, Questions (each with its type), Resource, +Code - grouped by section: the IPS sections in the IPS order, then other sections as they first +appear; in a section, the guides' own order. The administrator adds, edits and deletes a guide at +a time, and moves it up or down within its section (`POST .../guide` to add, `.../guide/{n}` to +change, `.../guide/{n}/delete`, `.../guide/{n}/move` with `direction` up or down - n is the +guide's place among the extensions). The dialog has the section (the same chooser as the rules), +the questions (added, deleted and moved up and down; answers and units with the code system and +code lookup), the resource, and its code. Saving a profile's rules or title leaves its guided +input as it is. An upload keeps its guided input, with new linkIds; anything more than this - an +extension other than input-guide, a contained resource other than `#Q`, more in the +Questionnaire or its items than the above, or a guide naming a question the Questionnaire +doesn't have - is refused. + ## National profiles A national profile is the profile a national implementation guide defines for an IPS document. Each has five parts: @@ -901,14 +954,16 @@ runaway statement would otherwise hold the server. ## FHIRPath functions -`ips/fhirpath-ips.js` adds two functions to fhirpath.js, for expressions on IPS documents: +`ips/fhirpath-ips.js` adds these functions to fhirpath.js, for expressions on IPS documents (the Java `DocumentFunctions` in org.hl7.fhir.core, which the validator runs, has the same): - `section(system, code [, min, max])`: the input is documents (Bundles) or Compositions. On a document it moves into the document's Composition by itself, which is why a clinical profile's rules, evaluated on the document, can say `Bundle.section(...)`. For each input, it returns the Composition's sections, nested ones included, whose `code` has a coding with that system and code. - `resources(system, code [, type])`: the input is documents, or anything in one (a Composition, say). It returns every resource in the document whose `code`, `medicationCodeableConcept` or `vaccineCode` has a coding with that system and code, and that is of the given type when a type is given. - `entryIn(valueSet [, min, max])` and `resourcesIn(valueSet [, type])`: as `entry()` and `resources()`, but they match a code in a value set (a canonical, with or without `|version`) rather than one given code. A resource is in when any coding of its code is. These two ask a terminology server, so the evaluation must be asynchronous (`evaluateAsync`), with a `membership` function in the options. A `MembershipSession` (`ips/membership.js`, made by the module's `membershipSession()`) provides one: it asks `ValueSet/$validate-code` with the CodeableConcept, only for what a rule actually reaches. Within a session, each question is asked once, and there's a budget of 500 per document. Definite answers are also kept in the module's cache, so the next document doesn't ask again. When the server can't answer (it doesn't know the value set, say), the answer is "not a member" for that run, and the session's `unresolved()` lists the value set and the server's message, so a rule that failed for that reason can be told apart from one that plainly failed. The module's own value sets (`ips/valuesets/`) are sent with the question, so any server can answer for them; any other value set must be one the server knows. - `entry(system, code [, min, max])`: the input is sections, usually from `section()`. For each one, it returns its resolved entries whose `code`, `medicationCodeableConcept` or `vaccineCode` has a coding with that system and code. `medicationReference` is not followed. +- `isKnown()` and `hasData()`: the input is sections. `isKnown()` is true when each has no `emptyReason`, or a nil known one (`list-empty-reason#nilknown`); `hasData()` when each has an `emptyReason`, or else entries. Empty on no input; false for anything that isn't a section of a Composition. +- `sameSubject([other])`: on a section, true when it has no `focus`, else whether the focus is the subject of `other` (or, without it, of the section's Composition); on a resource, whether its `subject` (or `patient`) is `other`'s (or, without it, the document's Composition's). References are the same when their reference strings are, else when their identifiers' system and value are. Empty when the input or `other` isn't one item, or a subject is missing. -`min` and `max` are optional (both or neither), and `max` may be `'*'`. The bounds apply to each input item: when the number found is outside them, that item adds nothing. That isn't an error. References are resolved in the Bundle the section is in, or failing that the Bundle the expression was evaluated on: +`min` and `max` are optional (both or neither), and `max` may be `'*'`. Without them, `section()` is `1..1` - a document with two of the same section has none, for a rule - and `entry()` and `entryIn()` are `0..*` (no bounds), as in the Java `DocumentFunctions`. The bounds apply to each input item: when the number found is outside them, that item adds nothing. That isn't an error. References are resolved in the Bundle the section is in, or failing that the Bundle the expression was evaluated on: - absolute `fullUrl`s (`urn:uuid:`, `http…`) match as they are; - a relative `Type/id` is resolved against the base of the Composition's `fullUrl`, or matched by type and id when there's no usable base; diff --git a/ips/render.js b/ips/render.js index d5b12d9d..30ee2e15 100644 --- a/ips/render.js +++ b/ips/render.js @@ -24,7 +24,7 @@ const { checkNarrative } = require('../library/narrative-check'); const { tokenConfigured } = require('../library/request-token'); const { STATUSES } = require('./search'); const profiles = require('./profiles'); -const { terminologyOf, systemName, describeVersion, linkForSystem, linkForCode, isExternalSystem } = require('./terminology'); +const { terminologyOf, systemName, describeVersion, linkForSystem, linkForCode, isExternalSystem, SECTION_ORDER } = require('./terminology'); const { issueSummary, checkOf, translationOf } = require('./pipeline'); const { jurisdiction } = require('./jurisdictions'); const { summaryOf, STEP_TIMINGS_SAMPLE } = require('./store'); @@ -161,6 +161,7 @@ const STYLE = ` .ips-pf-grid td.ips-pf-card { width: 7em; } .ips-pf-grid .ips-ed-input { width: 100%; box-sizing: border-box; } .ips-pf-pair { display: flex; gap: 4px; } + .ips-pf-checks { display: flex; flex-wrap: wrap; gap: 6px 20px; margin-top: 6px; } .ips-pf-check { font-weight: normal; margin: 0; white-space: nowrap; } .ips-pf-pair select { max-width: 13em; } .ips-pf-display { font-size: 85%; color: #555; margin-top: 2px; min-height: 1em; } .ips-pf-expr { font-family: monospace; font-size: 85%; color: #666; margin-top: 4px; word-break: break-all; } @@ -171,7 +172,11 @@ const STYLE = ` .ips-pf-rule td.ips-pf-actions { padding-top: 1px; padding-bottom: 1px; } .ips-pf-part-head { display: flex; align-items: baseline; gap: 12px; margin-top: 18px; } .ips-pf-part-head h4 { margin: 0 0 6px; } - .ips-pf-part-head .ips-pf-add { font-size: 80%; padding: 0 8px; line-height: 1.6; } + .ips-pf-part-head .ips-pf-add, .ips-pf-part-head .ips-pf-add-guide { font-size: 80%; padding: 0 8px; line-height: 1.6; } + .ips-pf-questions { margin: 0; padding-left: 18px; } .ips-pf-guides td { vertical-align: top; } + .ips-pf-rename { display: inline-block; } .ips-pf-rename summary { list-style: none; display: inline-block; } .ips-pf-rename summary::-webkit-details-marker { display: none; } + .ips-pf-question { border: 1px solid #dee2e6; border-radius: 4px; padding: 6px 8px; margin-bottom: 6px; } .ips-pf-qhead { display: flex; gap: 4px; align-items: center; } + .ips-pf-list-row { display: flex; gap: 4px; align-items: flex-start; margin-bottom: 4px; } .ips-pf-rule .ips-pf-actions .btn { font-size: 75%; padding: 0 5px; line-height: 1.5; border-radius: 3px; vertical-align: baseline; } .ips-pf-how { align-items: center; gap: 8px; margin-top: 6px; } .ips-pf-how input { width: 7em; flex: none; } .ips-pf-how .ips-pf-hint { margin: 0; } .ips-pf-dialog { width: min(760px, 95vw); max-height: 90vh; padding: 0; border: 1px solid #bbb; border-radius: 6px; box-shadow: 0 8px 30px rgba(0,0,0,0.3); } @@ -528,9 +533,9 @@ function projectDocs(project, ctx) { '' + `` + `` + - `' + ``); + } + }; + const link = `${base}/${encodeURIComponent(r.resourceType)}/${encodeURIComponent(r.id)}`; + add('Id', `${escape(r.id)}`); + if (r.meta) { + add('Version', r.meta.versionId ? `${escape(r.meta.versionId)} (history)` : null); + add('Updated', r.meta.lastUpdated ? escape(fmtDate(Date.parse(r.meta.lastUpdated))) : null); + add('Profiles', (r.meta.profile || []).map(p => `${escape(p)}`).join('
')); + add('Tags', (r.meta.tag || []).map(t => escape(`${t.system ? t.system + '|' : ''}${t.code}${t.display ? ' (' + t.display + ')' : ''}`)).join('
')); + add('Security', (r.meta.security || []).map(t => escape(`${t.system ? t.system + '|' : ''}${t.code}`)).join('
')); + } + if (typeof r.url === 'string') { + add('URL', `${escape(r.url)}${r.version ? ' version ' + escape(r.version) : ''}`); + } + const ids = Array.isArray(r.identifier) ? r.identifier : r.identifier ? [r.identifier] : []; + add('Identifiers', ids.filter(i => i && i.value).map(i => escape(`${i.system ? i.system + '|' : ''}${i.value}`)).join('
')); + add('Name', escape(displayOf(r))); + if (typeof r.status === 'string') { + add('Status', escape(r.status)); + } + for (const k of ['subject', 'patient', 'encounter']) { + const ref = r[k]; + if (ref && typeof ref.reference === 'string') { + const p = /^([A-Z][A-Za-z]+)\/([A-Za-z0-9\-.]{1,64})$/.exec(ref.reference); + add(k.charAt(0).toUpperCase() + k.slice(1), p ? `${escape(ref.display || ref.reference)}` : escape(ref.display || ref.reference)); + } + } + return `
Request
POST ${purl}/Bundlesubmit a document${submitNote(project)}; the response is the stored document, with its id
GET ${purl}/Bundle/{id}read a document - JSON for a FHIR client, this web page for a browser (?_format=json forces JSON, ?download=1 downloads it)
GET ${purl}/Bundle/{id}/$document?...the document as the source view gives it for download or sharing: parameters source (original | modified), ` + + `
GET ${purl}/Bundle/{id}/$document?...the document as the source view gives it for download or sharing: parameters source (original | modified), format-type (json | pdf | zip | shl | vhl), ` + 'user-sign (as the owner of the API token in Authorization: Bearer), system-sign, patient-notes, regenerate-narrative (true | false); ' + - 'by Accept (or _format) the JSON, application/zip, application/pdf, or the QR code (a PNG) of an SHL (application/smart-health-link) or VHL (application/verified-health-link) - ' + + 'the JSON, a ZIP, a PDF, or the QR code (image/png) of an SHL or VHL: by format-type, else Accept (or _format) - image/png is a VHL\'s - ' + 'OperationDefinition
GET ${purl}/Bundle?...search: Bundle's search parameters (_id, identifier, _lastUpdated, composition), chained to the Composition and Patient as ` + 'composition.date, composition.title, composition.patient.name, composition.patient.gender, composition.patient.birthdate, composition.patient.identifier, ...; ' + @@ -1998,7 +2003,8 @@ function renderProfiles(list, ctx) { h += '
Clinical profiles
'; if (ctx.user?.isAdmin) { h += '
' + - `New profile ` + + ' ' + + ' ' + '' + '
'; } @@ -2021,6 +2027,17 @@ function renderProfiles(list, ctx) { h += ``; - h += ``; - return h; -} - // ---- the SHL viewer -------------------------------------------------------------------------- const TRACE_LEVELS = { @@ -3267,5 +3315,5 @@ module.exports = { analysisOk, renderHome, renderProjects, renderProject, renderSubmit, renderSettings, renderDocument, assembledNarrative, renderStructure, renderAnalysis, renderTerminology, renderTranslation, renderGenerated, renderAi, renderPatientComments, PATIENT_COMMENT_MAX, renderValidation, renderNational, renderShare, renderCompose, renderComposeChoice, renderPatientEditor, renderPatients, renderPatient, renderProfileChecks, - renderProfiles, renderProfile, renderProfileEditor, renderNationalProfiles, renderReports, renderReportDefinition, renderReportEditor, renderProjectReports, renderProjectReport, renderQueue, renderViewerStart, renderView, VIEWS, viewOf + renderProfiles, renderProfile, renderNationalProfiles, renderReports, renderReportDefinition, renderReportEditor, renderProjectReports, renderProjectReport, renderQueue, renderViewerStart, renderView, VIEWS, viewOf }; diff --git a/library/config-check.js b/library/config-check.js index b5ec1cec..1fbb3650 100644 --- a/library/config-check.js +++ b/library/config-check.js @@ -153,7 +153,9 @@ const SERVER = obj({ sharedCache: bool(), sharedCacheMaxMB: num({ min: 0 }), cacheAffinity: bool(), - sharedClosure: bool() + sharedClosure: bool(), + // the modules the workers run besides tx (library/role.js) + workerModules: arr(str({ values: ['tx', 'rest'] })) }) }); @@ -465,6 +467,31 @@ const MODULES = { trust: arr(obj({ kid: str({ nonEmpty: true }), name: str(), certFile: str({ nonEmpty: true }), certificate: str({ nonEmpty: true }) })) }), validator: validatorSpec + }), + // rest/README.md: where each endpoint is and which database it uses; the rest of an + // endpoint's settings are in its database + rest: obj({ + enabled: bool(), + packageServers: arr(url()), + endpoints: arr(obj({ + path: str({ required: true, pattern: /^\/[A-Za-z0-9/_-]*$/, patternText: 'a path like /fhir/r4' }), + fhirVersion: str({ pattern: /^\d+\.\d+(\.\d+)?(-[A-Za-z0-9.]+)?$/, patternText: 'a FHIR version like 4.0.1' }), + baseUrl: url(), + database: obj({ + type: str({ values: ['sqlite', 'mysql'], required: true }), + file: str({ nonEmpty: true }), + host: str({ nonEmpty: true }), + port: port(), + database: str({ nonEmpty: true }), + user: str({ nonEmpty: true }), + password: retired('MySQL passwords don\'t go in config.json: use passwordEnv (an environment variable) or passwordFile'), + passwordEnv: str({ nonEmpty: true }), + passwordFile: str({ nonEmpty: true }), + connections: int({ min: 1 }) + }, { required: true }), + initialSettings: any(), + types: any() + })) }) }; diff --git a/library/fhir-search-values.js b/library/fhir-search-values.js index 3f64416f..efaa60ef 100644 --- a/library/fhir-search-values.js +++ b/library/fhir-search-values.js @@ -8,25 +8,102 @@ * The value-level parts of FHIR search that every module with a search implements the * same way: date ranges, the comparison prefixes, comma-separated values, and LIKE * escaping. The SQL that uses them is each module's own (testing/search.js, - * ips/search.js). + * ips/search.js, rest/search/sql.js). + * + * Every date value is a half-open range of instants [lo, hi) in epoch milliseconds, and + * every prefix is one comparison between two ranges (see dateClause, and the rest + * module's design: "Date and time search"). * * @module library/fhir-search-values */ const PREFIXES = ['eq', 'ne', 'gt', 'lt', 'ge', 'le', 'sa', 'eb', 'ap']; +// seconds may be 60: a leap second, which FHIR allows const DATE_RE = /^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?)?)?$/; +// the smallest and largest instants a JavaScript date can hold: the ends of an open +// Period. Stored as numbers, never as NULL, so an open-ended Period still compares +const MIN_INSTANT = -8.64e15; +const MAX_INSTANT = 8.64e15; + +const DAY_MS = 86400000; + +/** + * UTC milliseconds for a date and time in UTC. Unlike Date.UTC, a year from 0 to 99 is that + * year, not 1900 to 1999. + */ +function utc(year, month, day, h = 0, mi = 0, s = 0, ms = 0) { + const d = new Date(0); + d.setUTCFullYear(year, month, day); + d.setUTCHours(h, mi, s, ms); + return d.getTime(); +} + +const offsetFormats = new Map(); + +/** + * The offset of a time zone from UTC at an instant, in milliseconds (local - UTC). + * @param {number} instant - epoch ms + * @param {string} timeZone - an IANA zone name + */ +function zoneOffset(instant, timeZone) { + if (!timeZone || timeZone === 'UTC' || timeZone === 'Etc/UTC') { + return 0; + } + let fmt = offsetFormats.get(timeZone); + if (!fmt) { + fmt = new Intl.DateTimeFormat('en-US', { + timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', + hour: 'numeric', minute: 'numeric', second: 'numeric', era: 'short' + }); + offsetFormats.set(timeZone, fmt); + } + const p = {}; + for (const part of fmt.formatToParts(new Date(instant))) { + p[part.type] = part.value; + } + let year = parseInt(p.year, 10); + if (p.era === 'BC' || p.era === 'B') { + year = 1 - year; + } + const local = utc(year, parseInt(p.month, 10) - 1, parseInt(p.day, 10), + parseInt(p.hour, 10), parseInt(p.minute, 10), parseInt(p.second, 10)); + return local - (instant - (((instant % 1000) + 1000) % 1000)); +} + +/** + * The UTC instant of a wall-clock time in a time zone. Daylight saving changes are taken + * from the time zone database, so local midnight on the day a change happens is right. + * @param {number} wall - the wall-clock time as if it were UTC (from utc()) + * @param {string} timeZone + */ +function wallToInstant(wall, timeZone) { + if (!timeZone || timeZone === 'UTC' || timeZone === 'Etc/UTC') { + return wall; + } + // two rounds: the offset at the first guess, then at the answer it gives + let t = wall - zoneOffset(wall, timeZone); + t = wall - zoneOffset(t, timeZone); + return t; +} + /** * The range of instants a FHIR date, dateTime or instant covers, as [lo, hi) in epoch - * milliseconds. "2026" covers the whole year; "2026-09-24T10:00:00.5Z" covers 100ms. - * A time with no zone is taken as UTC (FHIR requires a zone, but search values often - * leave it off). + * milliseconds. "2026" covers the whole year; "2026-09-24T10:00:00.5Z" covers 100ms; + * milliseconds are the finest grain. + * + * A value with no zone - a date, a partial date, or a time without one - is taken in the + * given time zone (UTC by default): "2026-09-24" runs from local midnight to local + * midnight, which is 23 or 25 hours on a day with a daylight saving change. + * + * A leap second (23:59:60) is the last second of that minute. * * @param {string} value + * @param {string} [timeZone] - an IANA time zone name; UTC if absent * @returns {{lo: number, hi: number}|null} null if the value isn't a date */ -function dateRange(value) { +function dateRange(value, timeZone) { if (typeof value !== 'string') { return null; } @@ -37,28 +114,57 @@ function dateRange(value) { const [, y, mo, d, h, mi, s, frac, tz] = m; const year = parseInt(y, 10); if (!mo) { - return { lo: Date.UTC(year, 0, 1), hi: Date.UTC(year + 1, 0, 1) }; + return { + lo: wallToInstant(utc(year, 0, 1), timeZone), + hi: wallToInstant(utc(year + 1, 0, 1), timeZone) + }; } const month = parseInt(mo, 10) - 1; if (month < 0 || month > 11) { return null; } if (!d) { - return { lo: Date.UTC(year, month, 1), hi: Date.UTC(year, month + 1, 1) }; + return { + lo: wallToInstant(utc(year, month, 1), timeZone), + hi: wallToInstant(utc(year, month + 1, 1), timeZone) + }; } const day = parseInt(d, 10); - if (day < 1 || day > new Date(Date.UTC(year, month + 1, 0)).getUTCDate()) { + if (day < 1 || day > new Date(utc(year, month + 1, 0)).getUTCDate()) { return null; } if (!h) { - return { lo: Date.UTC(year, month, day), hi: Date.UTC(year, month, day + 1) }; + return { + lo: wallToInstant(utc(year, month, day), timeZone), + hi: wallToInstant(utc(year, month, day + 1), timeZone) + }; } - const zone = tz || 'Z'; - const text = `${y}-${mo}-${d}T${h}:${mi}:${s || '00'}${frac || ''}${zone}`; - const lo = Date.parse(text); - if (Number.isNaN(lo) || parseInt(h, 10) > 23 || parseInt(mi, 10) > 59 || (s && parseInt(s, 10) > 59)) { + const hour = parseInt(h, 10); + const minute = parseInt(mi, 10); + let second = s ? parseInt(s, 10) : 0; + if (hour > 23 || minute > 59 || second > 60 || (second === 60 && !(hour === 23 && minute === 59))) { return null; } + if (second === 60) { + // a leap second: the last second of the minute + second = 59; + } + const millis = frac ? Math.floor(parseFloat('0' + frac) * 1000) : 0; + const wall = utc(year, month, day, hour, minute, second, millis); + let lo; + if (tz && tz !== 'Z') { + const sign = tz[0] === '-' ? -1 : 1; + const oh = parseInt(tz.substring(1, 3), 10); + const om = parseInt(tz.substring(4, 6), 10); + if (oh > 14 || om > 59) { + return null; + } + lo = wall - sign * (oh * 3600000 + om * 60000); + } else if (tz === 'Z') { + lo = wall; + } else { + lo = wallToInstant(wall, timeZone); + } let width; if (!s) { width = 60000; @@ -71,6 +177,59 @@ function dateRange(value) { return { lo, hi: lo + width }; } +/** + * The range a Period covers: from the start's lo to the end's hi, open where either is + * missing. A Period ending "2013-01-21" runs to the end of that day. + * @param {{start?: string, end?: string}} period + * @param {string} [timeZone] + * @returns {{lo: number, hi: number}|null} + */ +function periodRange(period, timeZone) { + if (!period || (!period.start && !period.end)) { + return null; + } + const start = period.start ? dateRange(period.start, timeZone) : null; + const end = period.end ? dateRange(period.end, timeZone) : null; + if ((period.start && !start) || (period.end && !end)) { + return null; + } + return { lo: start ? start.lo : MIN_INSTANT, hi: end ? end.hi : MAX_INSTANT }; +} + +/** + * The range for `ap`: the value's range widened on each side by 10% of the distance + * between it and now, and never by less than a day. + * @param {{lo: number, hi: number}} range + * @param {number} [now] - epoch ms + */ +function approxDateRange(range, now = Date.now()) { + const mid = (range.lo + range.hi) / 2; + const widen = Math.max(DAY_MS, Math.abs(now - mid) * 0.1); + return { lo: range.lo - widen, hi: range.hi + widen }; +} + +/** + * The range a decimal number covers by its precision: "1.5" is [1.45, 1.55), "100" is + * [99.5, 100.5). An exponent counts too: "1e2" is [50, 150). + * @param {string|number} text + * @returns {{lo: number, hi: number, value: number}|null} + */ +function numberRange(text) { + const s = String(text).trim(); + const m = /^([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(s); + if (!m) { + return null; + } + const value = Number(s); + if (!Number.isFinite(value)) { + return null; + } + const decimals = m[3] ? m[3].length : 0; + const exponent = m[4] ? parseInt(m[4], 10) : 0; + const half = 0.5 * Math.pow(10, exponent - decimals); + return { lo: value - half, hi: value + half, value }; +} + /** * Take the comparison prefix (eq, ge, ...) off a date or number search value. * @returns {{prefix: string, rest: string}} prefix is 'eq' when there is none @@ -88,6 +247,14 @@ function escapeLike(value) { return value.replace(/[\\%_]/g, (c) => '\\' + c); } +/** + * Escape a value for use in a LIKE pattern with ESCAPE '!'. MySQL treats a backslash in a + * string literal as an escape too, so a LIKE meant for both SQLite and MySQL uses '!'. + */ +function escapeLikeBang(value) { + return value.replace(/[!%_]/g, (c) => '!' + c); +} + /** * Split a parameter value on commas, honouring \, as an escaped comma. */ @@ -112,7 +279,17 @@ function splitValues(value) { /** * SQL comparing a stored [lo, hi) range (two column expressions) against a search - * range, for a comparison prefix. + * range, for a comparison prefix. From the specification's definitions: + * + * eq the search range fully contains the resource range lo >= pLo and hi <= pHi + * ne it does not not (eq) + * gt the range above the search value overlaps hi > pHi + * lt the range below the search value overlaps lo < pLo + * ge [pLo, +infinity) overlaps hi > pLo + * le (-infinity, pHi) overlaps lo < pHi + * sa no overlap, and the resource range is above lo >= pHi + * eb no overlap, and the resource range is below hi <= pLo + * ap the ranges overlap (the caller widens the search range: approxDateRange) * * @param {{lo: string, hi: string}} cols - column expressions * @param {string} prefix @@ -135,4 +312,26 @@ function dateClause(cols, prefix, range) { return null; } -module.exports = { PREFIXES, dateRange, splitPrefix, escapeLike, splitValues, dateClause }; +/** + * The same comparisons as dateClause, in JavaScript: whether a resource range matches a + * search range. For tests, and for checking values in memory. + */ +function rangeMatches(prefix, resource, search) { + switch (prefix) { + case 'eq': return resource.lo >= search.lo && resource.hi <= search.hi; + case 'ne': return !(resource.lo >= search.lo && resource.hi <= search.hi); + case 'gt': return resource.hi > search.hi; + case 'lt': return resource.lo < search.lo; + case 'ge': return resource.hi > search.lo; + case 'le': return resource.lo < search.hi; + case 'sa': return resource.lo >= search.hi; + case 'eb': return resource.hi <= search.lo; + case 'ap': return resource.lo < search.hi && resource.hi > search.lo; + } + return false; +} + +module.exports = { + PREFIXES, MIN_INSTANT, MAX_INSTANT, dateRange, periodRange, approxDateRange, numberRange, splitPrefix, + escapeLike, escapeLikeBang, splitValues, dateClause, rangeMatches, zoneOffset, wallToInstant +}; diff --git a/library/role.js b/library/role.js index f5f653e2..4fc3b31a 100644 --- a/library/role.js +++ b/library/role.js @@ -13,15 +13,43 @@ * - master: every configured module, every background job, $closure and the syndication * feed. The VSAC provider syncs and, after each sync, bumps a generation counter that the * workers watch. - * - tx-worker: the tx module only. No background jobs, no statistics database, no $closure - * or syndication store (those requests go to the master), and the VSAC provider only - * reads what the master's sync wrote. + * - tx-worker: the modules in server.cluster.workerModules - the tx module by default, and + * the rest module if it is listed (["tx", "rest"]). No background jobs, no statistics + * database, no $closure or syndication store (those requests go to the master), the VSAC + * provider only reads what the master's sync wrote, and the rest module's endpoints wait + * for the master's schema migrations and leave its jobs to the master. * * @module library/role */ const ROLES = ['master', 'tx-worker']; +// the modules a worker can run (server.cluster.workerModules): those whose state is all in +// files or databases every process can share. The tx module is always one of them +const WORKER_MODULES = ['tx', 'rest']; +const DEFAULT_WORKER_MODULES = ['tx']; + +/** + * The modules a worker runs: server.cluster.workerModules, checked. + * @param {Object} config + * @returns {string[]} + */ +function workerModules(config) { + const list = config.server && config.server.cluster && config.server.cluster.workerModules; + if (list === undefined || list === null) { + return DEFAULT_WORKER_MODULES; + } + if (!Array.isArray(list) || list.some(m => typeof m !== 'string')) { + throw new Error('server.cluster.workerModules must be a list of module names, e.g. ["tx", "rest"]'); + } + for (const m of list) { + if (!WORKER_MODULES.includes(m)) { + throw new Error(`server.cluster.workerModules: a worker can't run the ${m} module (only ${WORKER_MODULES.join(' and ')})`); + } + } + return list.includes('tx') ? list : ['tx', ...list]; +} + /** * An instance code goes in front of every cache-id the process issues, and a front door * routes on it (nginx.md's map on "^tx1\."). It has to be 1-16 letters and digits: the @@ -172,9 +200,10 @@ function applyRole(config, role) { const interval = stats.intervalMinutes > 0 ? stats.intervalMinutes * 60 : 600; config.stats = { ...stats, sampleSeconds: Math.min(ROLE_SAMPLE_SECONDS, interval) }; } + const keep = workerModules(config); if (role.role === 'tx-worker') { for (const [name, mod] of Object.entries(config.modules)) { - if (name !== 'tx' && mod) { + if (!keep.includes(name) && mod) { mod.enabled = false; } } @@ -190,8 +219,8 @@ function describeRole(role, config) { const code = config.modules.tx.instanceCode; return role.role === 'master' ? `Role: master (instance code ${code}): all modules, background jobs, $closure` - : `Role: tx-worker (instance code ${code}): the tx module only, no background jobs`; + : `Role: tx-worker (instance code ${code}): the ${workerModules(config).join(' and ')} module${workerModules(config).length > 1 ? 's' : ''} only, no background jobs`; } -module.exports = { parseRole, applyRole, describeRole, checkInstanceCode, bindAddress, connectAddress, DEFAULT_BIND_ADDRESS, +module.exports = { parseRole, applyRole, describeRole, workerModules, WORKER_MODULES, checkInstanceCode, bindAddress, connectAddress, DEFAULT_BIND_ADDRESS, DEFAULT_SHARED_CACHE_MAX_MB, ROLE_TRIM_ALLOCATOR, ROLE_SAMPLE_SECONDS, READY, ROLES }; diff --git a/package-lock.json b/package-lock.json index a0c1a7df..c1011018 100644 --- a/package-lock.json +++ b/package-lock.json @@ -32,6 +32,7 @@ "jose": "^5.10.0", "liquidjs": "^10.25.5", "lusca": "^1.7.0", + "mysql2": "^3.24.6", "natural": "^8.1.1", "node-cron": "^4.6.0", "nodemailer": "^10.2.0", @@ -2527,7 +2528,6 @@ "version": "26.1.1", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz", "integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==", - "devOptional": true, "license": "MIT", "dependencies": { "undici-types": "~8.3.0" @@ -3372,6 +3372,15 @@ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "license": "MIT" }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/axios": { "version": "1.20.0", "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", @@ -5451,6 +5460,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -5992,6 +6010,12 @@ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "license": "MIT" }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, "node_modules/is-stream": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", @@ -7148,6 +7172,12 @@ "node": ">= 12.0.0" } }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -7158,6 +7188,21 @@ "yallist": "^3.0.2" } }, + "node_modules/lru.min": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz", + "integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, "node_modules/lusca": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/lusca/-/lusca-1.7.0.tgz", @@ -7499,6 +7544,39 @@ "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", "license": "ISC" }, + "node_modules/mysql2": { + "version": "3.24.6", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz", + "integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.3", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.5.1" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/napi-build-utils": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", @@ -9061,6 +9139,21 @@ "node": ">= 10.x" } }, + "node_modules/sql-escaper": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.9.1.tgz", + "integrity": "sha512-4p522TVYaJXTbMlYgAwacjyg3EJyYe9KYWYlYJVwZG1YjtzxU5m5iSzsZoGI69Po7j3i/2tKlpZQi7uvhTL+WA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" + } + }, "node_modules/sqlite3": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/sqlite3/-/sqlite3-6.0.1.tgz", @@ -9807,7 +9900,6 @@ "version": "8.3.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", - "devOptional": true, "license": "MIT" }, "node_modules/universalify": { diff --git a/package.json b/package.json index 85131c6f..f9315852 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "jose": "^5.10.0", "liquidjs": "^10.25.5", "lusca": "^1.7.0", + "mysql2": "^3.24.6", "natural": "^8.1.1", "node-cron": "^4.6.0", "nodemailer": "^10.2.0", diff --git a/rest/README.md b/rest/README.md new file mode 100644 index 00000000..7d0e1268 --- /dev/null +++ b/rest/README.md @@ -0,0 +1,170 @@ +# The rest module + +Database-backed FHIR RESTful servers inside FHIRsmith. Each endpoint has its own FHIR version, +definitions, data and users' roles, and keeps its state in SQLite or MySQL. Processes cache +very little: any process can serve any request, so the module runs under the cluster like the +tx module. + +The design is in the design document (*FHIRsmith REST module: design*); this file is how to +run it. + +## What it does + +- JSON only (XML gets 415 or 406) +- read, vread, create, update, patch (JSON Patch), delete, history, search, capabilities, + batch and transaction, with conditional create, update, patch and delete +- search: every parameter type and the usual modifiers and prefixes, chains and `_has` (3 + levels), composites, `_filter`, `_list`, `_sort`, `_include` and `_revinclude` (with + `:iterate`), `_summary`, `_elements`, `_total`, and paging through stored results +- `:below` and `:above` on tokens through a closure table, kept up to date with the endpoint's + terminology server's `$closure`; `:in` and `:not-in` through its `$expand` +- `$meta`, `$meta-add`, `$meta-delete`, and `Patient/[id]/$everything` +- AuditEvents for writes (and, if set, reads and failures), stored on the endpoint +- a subscription queue (`SubscriptionQueue`), filled by every write; nothing delivers it yet +- users and roles from the server's logins (library/auth) + +What search supports, parameter by parameter, is in [search.md](search.md). + +Not yet: XML, subscription delivery, validation on write, SMART on FHIR, asynchronous +operations, `$lastn`, `_text` and `_content`, FHIRPath Patch, admin pages. + +## Configuration + +config.json says only where each endpoint is and which database it uses: + +```json +"rest": { + "enabled": true, + "endpoints": [ + { "path": "/fhir/r4", "fhirVersion": "4.0.1", + "database": { "type": "sqlite", "file": "rest/fhir-r4.db" }, + "initialSettings": { "name": "R4 test server", "anonymous": "read" } }, + { "path": "/fhir/r5", "fhirVersion": "5.0.0", + "database": { "type": "mysql", "host": "localhost", "database": "fhir_r5", + "user": "fhirsmith", "passwordEnv": "FHIR_R5_DB_PASSWORD" } } + ] +} +``` + +| Setting | | +|---|---| +| `path` | Where the endpoint is on this server. | +| `fhirVersion` | The FHIR version (3.0, 4.0, 4.3 or 5.0). Fixed when the database is made; a different one later is an error. | +| `database` | `{ "type": "sqlite", "file" }` (relative to the databases folder), or `{ "type": "mysql", "host", "port", "database", "user", "passwordEnv" or "passwordFile", "connections" }`. Never a password in config.json: `passwordEnv` names an environment variable, `passwordFile` a file only the server can read. Two endpoints can't share a database. | +| `baseUrl` | The endpoint's public URL, if it isn't `https://{hostName}{path}`: references to it are local references. | +| `initialSettings` | Settings (below) written into a new database. A setting already in the database is never changed from here: the log warns at start-up when the two differ. | +| `types` | Per-type settings (below) for types not in the database yet. | +| `modules.rest.packageServers` | The package servers definitions are fetched from (packages2.fhir.org, then packages.fhir.org). | + +The database's tables are made, and later brought up to date, when the server starts (on the +master, under a lock). A MySQL database must exist, with a user that can create tables in it, +`utf8mb4`. + +## Settings + +Everything else about an endpoint is in its own database: the `Config` table (`Name`, `Value`) +and, per resource type, `Types.Settings` (JSON). There are no admin pages yet: change them in +the database, and bump the `generation` row in `Config` (every process reloads within a second +when it changes). + +| `Config` | Default | | +|---|---|---| +| `name`, `description` | | For the CapabilityStatement. | +| `packages` | `[]` | IG packages (`id#version`, JSON list) whose search parameters and compartments are loaded, after the core package. | +| `idStrategy` | `key` | Server-assigned ids: `key` (the resource's database key: short) or `uuid`. | +| `createOnUpdate` | true | PUT to a new id creates. | +| `checkReferences` | true | A write whose references to this endpoint don't resolve gets 422. | +| `txServer` | | The terminology server for `:in`, `:not-in` and the closure: a path on this server (the tx module's endpoint, in process) or a URL. | +| `audit` | `writes` | AuditEvents: `off`, `writes`, or `all` (reads and failures too). | +| `defaultCount`, `maxCount` | 50, 500 | Page sizes. | +| `searchMaxResults` | 20000 | The most results a search keeps for paging. | +| `searchKeepMinutes` | 30 | How long stored results are kept. | +| `timeZone` | the server's | For dates without a zone (an IANA name). | +| `compress` | true | Resources are stored gzipped. | +| `transactionMaxEntries` | 1000 | The biggest transaction. | +| `anonymous` | `none` | `read`: anyone can read (a public server); `write`: anyone can read and write (a sandbox). | +| `customSearchParameters` | false | SearchParameter resources stored on the endpoint are used too. | +| `conditionalDeleteMax` | 1 | The most resources a conditional delete deletes. | + +| `Types.Settings` | Default | | +|---|---|---| +| `versionAware` | false | Updates and patches need `If-Match`. | +| `interactions` | all | The interactions allowed: `read`, `vread`, `update`, `patch`, `delete`, `history-instance`, `history-type`, `create`, `search-type`. | +| `conditionalCreate`, `conditionalUpdate`, `conditionalDelete` | true | | + +`Types.Supported` 0 takes a type off the endpoint. + +## Transactions + +A transaction is all or nothing: every entry is written in one database transaction, and any +failure leaves the database as it was, with the failing entry's OperationOutcome (naming the +entry). Before anything is written: + +- every write entry is given the one resource it changes. A POST gets a new id; a conditional + create, update, patch or delete is searched once, here. **A resource may be changed by only + one entry**: two that change the same one (directly, or through what a conditional resolves + to) fail the transaction, with 400. So do two conditional creates with the same criteria +- conditional references (`Patient?identifier=x`) are searched: exactly one match, else 412 +- every write entry's fullUrl (a `urn:uuid:`, or an absolute URL) is mapped to its resource, + and references to it are rewritten wherever they are the whole value of an element, and in + narratives in `` and `` only, matching exactly or up to a `#`. A + `urn:uuid:` or `urn:oid:` reference left over points at nothing: 400 +- references with the `resolve-as-version-specific` extension get the version the transaction + writes (the extension is removed) + +Then the entries run: deletes, creates, updates and patches, reads (which see the writes). +Reference checks wait until every entry is written: a reference to a resource that won't exist +(or that the transaction deletes, or to a version that doesn't exist) fails with 422. The +response has an entry for each entry, in the request's order. + +Posting a Bundle needs only read: each entry is checked for what it does. In a batch, each +entry runs on its own, and an entry can't refer to another by its fullUrl. + +The tests (`tests/rest/transaction-rules.test.js`, `tests/rest/transaction-fuzz.test.js`) +check each rule, and also run random transactions against a model of these rules +(`FHIRSMITH_FUZZ_ROUNDS`, `FHIRSMITH_FUZZ_SEED` to repeat a run). + +## Web pages + +A browser that opens an endpoint's URLs (`Accept: text/html`, or `?_format=html`) gets pages +over the same API, with the same access checks: + +- the endpoint (`[base]`): what it is, the resource types with how many of each, and the + CapabilityStatement +- a type (`[base]/Patient`): how many there are, and a search form built from its search + parameters +- search results, history and `$everything`, as tables that link to each resource +- a resource: what identifies it (id, version, identifiers, name, status, subject...), its + narrative (unless it carries active content), and its JSON + +`?_format=json` gets the JSON in a browser. The pages only read: every change goes through the +API. + +## Access + +Users, logins and API tokens are the server's ([library/auth](../library/auth/README.md)). The +module's roles, given per endpoint (or for all) on the users page: + +| Role | Allows | +|---|---| +| read | read, vread, search, history, capabilities, `$meta`, `$everything` | +| write | create, update, patch, delete, batch, transaction, `$meta-add`, `$meta-delete` (and read) | +| manage | (and read and write) the endpoint's settings, when there are pages for them | + +Administrators have them all. Software sends an API token (`Authorization: Bearer fhs_...`). + +## Clustering + +Under the cluster (cluster.md), the master migrates the schema and runs the jobs: deleting +expired searches, the closure, and reindexing when definitions change. Workers serve the +endpoints when `server.cluster.workerModules` includes `"rest"`: everything is in the +database, so any process can serve any request, including the next page of a search another +ran. With SQLite every process must be on one machine, and writes take turns through one lock; +MySQL scales writes, and its workers can be on several machines. + +## Tests + +`npm test -- tests/rest` runs the module's tests on SQLite, and on MySQL when +`FHIRSMITH_TEST_MYSQL` says where (`host:port/database:user`, with the password in +`FHIRSMITH_TEST_MYSQL_PASSWORD`); without it the MySQL half is skipped, with a notice. The +database is emptied first: use one for testing only. diff --git a/rest/access.js b/rest/access.js new file mode 100644 index 00000000..d7721b3b --- /dev/null +++ b/rest/access.js @@ -0,0 +1,94 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Who may do what. Every decision goes through decide(), which returns + * { allowed, compartments }: compartments is null (no limit) or a list of compartments + * ("Patient/123") the request is limited to. With roles only it is always null; it is there so + * SMART on FHIR can be added without touching the interactions. + * + * Roles (library/auth, module 'rest', scoped by endpoint path): + * read read, vread, search, history, capabilities, read operations + * write create, update, patch, delete, batch, transaction, writing operations + * manage the endpoint's settings, types, custom search parameters, reindexing + * + * An endpoint can allow anonymous read ('read') or read and write ('write'). + * + * @module rest/access + */ + +const { forbidden, unauthorised } = require('./library/errors'); + +const MODULE = 'rest'; +const READ = 'read'; +const WRITE = 'write'; +const MANAGE = 'manage'; + +// 'bundle': posting a batch or transaction needs only read; each entry is then checked for +// what it does +const READ_INTERACTIONS = new Set(['read', 'vread', 'search-type', 'search-system', 'history-instance', 'history-type', 'history-system', + 'capabilities', 'operation-read', 'bundle']); + +/** + * Which role an interaction needs. + * @param {string} interaction + */ +function roleFor(interaction) { + if (READ_INTERACTIONS.has(interaction)) { + return READ; + } + if (interaction === 'manage') { + return MANAGE; + } + return WRITE; +} + +/** + * The access decision. + * @param {Object|null} principal - from auth.principal(req), or null for nobody + * @param {Object} endpoint - { path, settings } + * @param {string} interaction + * @returns {{allowed: boolean, compartments: string[]|null, reason?: string}} + */ +function decide(principal, endpoint, interaction) { + const role = roleFor(interaction); + const anonymous = endpoint.settings.anonymous || 'none'; + if (role === READ && (anonymous === 'read' || anonymous === 'write')) { + return { allowed: true, compartments: null }; + } + if (role === WRITE && anonymous === 'write') { + return { allowed: true, compartments: null }; + } + if (!principal) { + return { allowed: false, compartments: null, reason: 'login' }; + } + const scope = endpoint.path; + // write implies read; manage implies both + const roles = role === READ ? [READ, WRITE, MANAGE] : role === WRITE ? [WRITE, MANAGE] : [MANAGE]; + for (const r of roles) { + if (principal.has(MODULE, r, scope)) { + return { allowed: true, compartments: null }; + } + } + return { allowed: false, compartments: null, reason: 'forbidden' }; +} + +/** + * Check access, throwing 401 or 403. + * @returns {{allowed: true, compartments: string[]|null}} + */ +function check(principal, endpoint, interaction) { + const d = decide(principal, endpoint, interaction); + if (!d.allowed) { + if (d.reason === 'login') { + throw unauthorised(`You need to log in (or send an API token) to ${interaction === 'capabilities' ? 'use' : interaction} on this endpoint`); + } + throw forbidden(`You don't have permission to ${interaction} on this endpoint`); + } + return d; +} + +module.exports = { decide, check, roleFor, MODULE, READ, WRITE, MANAGE }; diff --git a/rest/audit/audit.js b/rest/audit/audit.js new file mode 100644 index 00000000..081f26e4 --- /dev/null +++ b/rest/audit/audit.js @@ -0,0 +1,109 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * AuditEvents. The endpoint asks the factory for the builder for its FHIR version, and the + * interactions only ever use that builder. For now one common builder serves R4 and R5 (it + * knows the few places they differ); a version-specific builder can replace it later without + * changing any caller. + * + * Writes are audited in the write's own transaction (the version points at the AuditEvent); + * reads, when the endpoint audits them, are buffered and written together every second or + * so, since on SQLite each one would otherwise queue for the write lock. + * + * @module rest/audit/audit + */ + +const DCM = 'http://dicom.nema.org/resources/ontology/DCM'; +const AUDIT_TYPE = 'http://terminology.hl7.org/CodeSystem/audit-event-type'; +const RESTFUL = 'http://hl7.org/fhir/restful-interaction'; + +// FHIR AuditEvent.action: C R U D E +const ACTIONS = { + create: 'C', read: 'R', vread: 'R', update: 'U', patch: 'U', delete: 'D', 'search-type': 'E', 'search-system': 'E', + 'history-instance': 'R', 'history-type': 'R', 'history-system': 'R', capabilities: 'R', batch: 'E', transaction: 'E', operation: 'E' +}; + +class CommonAuditBuilder { + /** + * @param {string} fhirVersion + */ + constructor(fhirVersion) { + this.r5 = String(fhirVersion).startsWith('5') || String(fhirVersion).startsWith('6'); + } + + /** + * @param {Object} e + * @param {string} e.interaction - a restful-interaction code (read, create, search-type...) + * @param {number} e.status - the HTTP status of the response + * @param {string} [e.outcomeText] + * @param {Object|null} e.principal - { id, login, name } or null + * @param {string} [e.ip] + * @param {string} [e.what] - Type/id[/_history/vid] or a query + * @param {string} [e.query] + * @param {string} e.source - the endpoint's URL + * @param {number} [e.time] + * @returns {Object} an AuditEvent + */ + build(e) { + const recorded = new Date(e.time || Date.now()).toISOString(); + const outcome = e.status < 400 ? '0' : e.status < 500 ? '4' : '8'; + const action = ACTIONS[e.interaction] || 'E'; + const who = e.principal + ? { display: e.principal.name || e.principal.login || String(e.principal.id), identifier: { system: 'urn:fhirsmith:user', value: String(e.principal.login || e.principal.id) } } + : { display: 'anonymous' }; + const agent = { requestor: true, who }; + if (e.ip) { + agent.network = this.r5 ? { address: e.ip } : { address: e.ip, type: '2' }; + } + const subtype = { system: RESTFUL, code: e.interaction }; + const ev = { resourceType: 'AuditEvent' }; + if (this.r5) { + ev.category = [{ coding: [{ system: AUDIT_TYPE, code: 'rest', display: 'RESTful Operation' }] }]; + ev.code = { coding: [subtype] }; + ev.action = action; + ev.recorded = recorded; + ev.outcome = { code: { system: 'http://terminology.hl7.org/CodeSystem/audit-event-severity', code: e.status < 400 ? 'informational' : 'error' } }; + if (e.outcomeText) { + ev.outcome.detail = [{ text: e.outcomeText }]; + } + ev.agent = [agent]; + ev.source = { observer: { display: e.source } }; + } else { + ev.type = { system: AUDIT_TYPE, code: 'rest', display: 'RESTful Operation' }; + ev.subtype = [subtype]; + ev.action = action; + ev.recorded = recorded; + ev.outcome = outcome; + if (e.outcomeText) { + ev.outcomeDesc = e.outcomeText; + } + ev.agent = [agent]; + ev.source = { observer: { display: e.source }, type: [{ system: 'http://terminology.hl7.org/CodeSystem/security-source-type', code: '3' }] }; + } + if (e.what || e.query) { + const entity = {}; + if (e.what) { + entity.what = { reference: e.what }; + } + if (e.query) { + entity.query = Buffer.from(e.query, 'utf8').toString('base64'); + } + ev.entity = [entity]; + } + return ev; + } +} + +/** + * The builder for a FHIR version. + * @param {string} fhirVersion + */ +function auditBuilder(fhirVersion) { + return new CommonAuditBuilder(fhirVersion); +} + +module.exports = { auditBuilder, CommonAuditBuilder, ACTIONS, DCM }; diff --git a/rest/database/index.js b/rest/database/index.js new file mode 100644 index 00000000..c0537aca --- /dev/null +++ b/rest/database/index.js @@ -0,0 +1,94 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The rest module's database interface. Everything else in the module talks to the + * database through this, the same way for SQLite and MySQL: + * + * await db.read(async (q) => { ... }) a connection for reading + * await db.write(async (q) => { ... }) a transaction: committed if the function returns, + * rolled back if it throws, and run again on a + * deadlock, a busy database, or an error marked + * `retryable` + * q.all(sql, params) / q.get(sql, params) / q.run(sql, params) -> { changes, lastId } + * + * SQL uses `?` placeholders, and is the same for both engines except where it goes through + * q.dialect (insertIgnore, concat). Errors from a unique index violation have `unique` set. + * + * @module rest/database + */ + +const path = require('path'); +const fs = require('fs'); +const { SqliteDatabase } = require('./sqlite'); +const { MysqlDatabase } = require('./mysql'); +const { migrate, waitForSchema, SCHEMA_VERSION } = require('./schema'); + +/** + * The MySQL password: from the environment variable passwordEnv names, or the file + * passwordFile names. Never from config.json itself. + * @param {Object} cfg - the endpoint's database configuration + */ +function mysqlPassword(cfg) { + if (cfg.passwordEnv) { + const v = process.env[cfg.passwordEnv]; + if (v === undefined) { + throw new Error(`The database password environment variable ${cfg.passwordEnv} is not set`); + } + return v; + } + if (cfg.passwordFile) { + return fs.readFileSync(cfg.passwordFile, 'utf8').replace(/\r?\n$/, ''); + } + if (cfg.password !== undefined) { + throw new Error('Database passwords don\'t go in config.json: use passwordEnv or passwordFile'); + } + return undefined; +} + +/** + * Open an endpoint's database. + * @param {Object} cfg - { type: 'sqlite', file } or { type: 'mysql', host, port, database, user, passwordEnv | passwordFile, connections } + * @param {Object} options + * @param {string} options.databasesDir - where a relative SQLite file goes + * @param {boolean} [options.master] - bring the schema up to date (else wait for it) + * @param {function(string)} [options.log] + */ +async function openDatabase(cfg, options = {}) { + if (!cfg || !cfg.type) { + throw new Error('An endpoint needs a database: { "type": "sqlite", "file": ... } or { "type": "mysql", ... }'); + } + let db; + if (cfg.type === 'sqlite') { + if (!cfg.file) { + throw new Error('A sqlite database needs a file'); + } + const file = path.isAbsolute(cfg.file) ? cfg.file : path.join(options.databasesDir || '.', cfg.file); + fs.mkdirSync(path.dirname(file), { recursive: true }); + db = new SqliteDatabase(file); + } else if (cfg.type === 'mysql') { + if (!cfg.database || !cfg.user) { + throw new Error('A mysql database needs a database and a user'); + } + db = new MysqlDatabase({ ...cfg, password: mysqlPassword(cfg) }); + } else { + throw new Error(`Unknown database type '${cfg.type}': use sqlite or mysql`); + } + await db.open(); + try { + if (options.master !== false) { + await migrate(db, options.log); + } else { + await waitForSchema(db); + } + } catch (err) { + await db.close(); + throw err; + } + return db; +} + +module.exports = { openDatabase, SCHEMA_VERSION }; diff --git a/rest/database/lookups.js b/rest/database/lookups.js new file mode 100644 index 00000000..a64e762d --- /dev/null +++ b/rest/database/lookups.js @@ -0,0 +1,199 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Interned values: systems and URIs (Spaces), concepts (Concepts) and tags (Tags). Each is + * inserted with insert-or-ignore and read back, so no process allocates keys. + * + * Keys are cached in the process, but only for rows that were already there: a row this + * transaction inserted isn't committed yet, and if the transaction rolls back, a cached key + * for it would point at nothing. + * + * @module rest/database/lookups + */ + +const MAX_CACHE = 200000; +const CHUNK = 200; + +class KeyCache { + constructor() { + this.map = new Map(); + } + + get(k) { + return this.map.get(k); + } + + set(k, v) { + if (this.map.size >= MAX_CACHE) { + this.map.clear(); + } + this.map.set(k, v); + } +} + +function chunks(list, n = CHUNK) { + const out = []; + for (let i = 0; i < list.length; i += n) { + out.push(list.slice(i, i + n)); + } + return out; +} + +class Lookups { + constructor() { + this.spaces = new KeyCache(); + this.concepts = new KeyCache(); + this.tags = new KeyCache(); + } + + /** + * Keys for systems/URIs, making those that don't exist (when q is in a transaction). + * @param {Object} q + * @param {string[]} uris + * @param {boolean} [create] - make missing ones (false: just look them up) + * @returns {Promise>} + */ + async spaceKeys(q, uris, create = true) { + const out = new Map(); + const missing = []; + for (const u of new Set(uris.filter(x => x))) { + const k = this.spaces.get(u); + if (k !== undefined) { + out.set(u, k); + } else { + missing.push(u); + } + } + if (missing.length === 0) { + return out; + } + const fresh = new Set(); + if (create) { + for (const c of chunks(missing)) { + // which of these are new: they are not cached when found + const existing = await q.all(`SELECT Uri FROM Spaces WHERE Uri IN (${c.map(() => '?').join(', ')})`, c); + const have = new Set(existing.map(r => r.Uri)); + const toAdd = c.filter(u => !have.has(u)); + if (toAdd.length) { + await q.run(q.dialect.insertIgnore('Spaces', ['Uri']) + toAdd.map(() => '(?)').join(', '), toAdd); + toAdd.forEach(u => fresh.add(u)); + } + } + } + for (const c of chunks(missing)) { + const rows = await q.all(`SELECT SpaceKey, Uri FROM Spaces WHERE Uri IN (${c.map(() => '?').join(', ')})`, c); + for (const r of rows) { + out.set(r.Uri, Number(r.SpaceKey)); + if (!fresh.has(r.Uri)) { + this.spaces.set(r.Uri, Number(r.SpaceKey)); + } + } + } + return out; + } + + /** One space key, or null (looked up only) */ + async spaceKey(q, uri) { + if (!uri) { + return null; + } + const m = await this.spaceKeys(q, [uri], false); + return m.has(uri) ? m.get(uri) : null; + } + + /** + * Keys for concepts (spaceKey, code), making missing ones, flagged as not yet in the + * closure. + * @param {Object} q + * @param {Array<[number, string]>} pairs + * @param {boolean} [create] + * @returns {Promise>} "spaceKey|code" -> key + */ + async conceptKeys(q, pairs, create = true) { + const out = new Map(); + const missing = []; + const seen = new Set(); + for (const [s, c] of pairs) { + const k = s + '|' + c; + if (seen.has(k)) { + continue; + } + seen.add(k); + const v = this.concepts.get(k); + if (v !== undefined) { + out.set(k, v); + } else { + missing.push([s, c]); + } + } + if (missing.length === 0) { + return out; + } + const fresh = new Set(); + for (const c of chunks(missing, 100)) { + const where = c.map(() => '(SpaceKey = ? AND Code = ?)').join(' OR '); + const args = c.flat(); + const existing = await q.all(`SELECT ConceptKey, SpaceKey, Code FROM Concepts WHERE ${where}`, args); + const have = new Map(existing.map(r => [r.SpaceKey + '|' + r.Code, Number(r.ConceptKey)])); + for (const [k, v] of have) { + out.set(k, v); + this.concepts.set(k, v); + } + const toAdd = c.filter(([s, code]) => !have.has(s + '|' + code)); + if (toAdd.length && create) { + await q.run(q.dialect.insertIgnore('Concepts', ['SpaceKey', 'Code', 'InClosure']) + toAdd.map(() => '(?, ?, 0)').join(', '), toAdd.flat()); + toAdd.forEach(([s, code]) => fresh.add(s + '|' + code)); + const rows = await q.all(`SELECT ConceptKey, SpaceKey, Code FROM Concepts WHERE ${toAdd.map(() => '(SpaceKey = ? AND Code = ?)').join(' OR ')}`, toAdd.flat()); + for (const r of rows) { + out.set(r.SpaceKey + '|' + r.Code, Number(r.ConceptKey)); + } + } + } + return out; + } + + /** + * Keys for tags (kind 1 tag, 2 security label, 3 profile), making missing ones. + * @param {Object} q + * @param {Array<{kind: number, system: string, code: string, display?: string}>} tags + * @returns {Promise} + */ + async tagKeys(q, tags) { + const keys = []; + for (const t of tags) { + const k = `${t.kind}|${t.system}|${t.code}`; + let v = this.tags.get(k); + if (v === undefined) { + let row = await q.get('SELECT TagKey FROM Tags WHERE Kind = ? AND TagSystem = ? AND Code = ?', [t.kind, t.system, t.code]); + if (row) { + v = Number(row.TagKey); + this.tags.set(k, v); + } else { + await q.run(q.dialect.insertIgnore('Tags', ['Kind', 'TagSystem', 'Code', 'Display']) + '(?, ?, ?, ?)', + [t.kind, t.system, t.code, t.display ? String(t.display).substring(0, 255) : null]); + row = await q.get('SELECT TagKey FROM Tags WHERE Kind = ? AND TagSystem = ? AND Code = ?', [t.kind, t.system, t.code]); + v = Number(row.TagKey); + } + } + keys.push(v); + } + return keys; + } + + /** A tag's key, or null (looked up only) */ + async tagKey(q, kind, system, code) { + const k = `${kind}|${system}|${code}`; + const v = this.tags.get(k); + if (v !== undefined) { + return v; + } + const row = await q.get('SELECT TagKey FROM Tags WHERE Kind = ? AND TagSystem = ? AND Code = ?', [kind, system, code]); + return row ? Number(row.TagKey) : null; + } +} + +module.exports = { Lookups, chunks }; diff --git a/rest/database/mysql.js b/rest/database/mysql.js new file mode 100644 index 00000000..a5dc045b --- /dev/null +++ b/rest/database/mysql.js @@ -0,0 +1,217 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The MySQL implementation of the rest module's database interface (database/index.js), + * through `mysql2` with a connection pool. + * + * Transactions run at READ COMMITTED, to avoid the gap locks REPEATABLE READ takes on index + * ranges, which cause deadlocks between concurrent writers. A deadlock (1213) or lock wait + * timeout (1205) runs the whole transaction again, as does an error marked retryable. + * + * @module rest/database/mysql + */ + +const mysql = require('mysql2/promise'); + +const WRITE_RETRIES = 4; +const ER_LOCK_DEADLOCK = 1213; +const ER_LOCK_WAIT_TIMEOUT = 1205; +const ER_DUP_ENTRY = 1062; + +class MysqlQuery { + constructor(conn, dialect) { + this.conn = conn; + this.dialect = dialect; + this.inTransaction = false; + this.locks = []; + } + + /** + * Take a named lock (GET_LOCK) for the rest of the transaction: released after the commit + * or rollback. For conditional creates, where two requests could both find nothing. + * @param {string} name + */ + async lock(name) { + const [rows] = await this.conn.query('SELECT GET_LOCK(?, 30) AS got', [name]); + if (!rows[0] || Number(rows[0].got) !== 1) { + const e = new Error(`Unable to get the lock ${name}`); + e.busy = true; + throw e; + } + this.locks.push(name); + } + + async releaseLocks() { + for (const name of this.locks.splice(0)) { + try { + await this.conn.query('SELECT RELEASE_LOCK(?)', [name]); + } catch (ignore) { + // the connection may be gone, and the lock with it + } + } + } + + async all(sql, params = []) { + try { + const [rows] = await this.conn.query(sql, params); + return rows; + } catch (err) { + throw wrapError(err, sql); + } + } + + async get(sql, params = []) { + const rows = await this.all(sql, params); + return rows[0]; + } + + async run(sql, params = []) { + try { + const [res] = await this.conn.query(sql, params); + return { changes: res.affectedRows, lastId: res.insertId }; + } catch (err) { + throw wrapError(err, sql); + } + } + + async exec(sql) { + try { + await this.conn.query(sql); + } catch (err) { + throw wrapError(err, sql); + } + } +} + +function wrapError(err, sql) { + if (err && err.errno === ER_DUP_ENTRY) { + err.unique = true; + } + if (err && (err.errno === ER_LOCK_DEADLOCK || err.errno === ER_LOCK_WAIT_TIMEOUT)) { + err.busy = true; + } + if (err && sql && !err.sql) { + err.sql = sql; + } + return err; +} + +const DIALECT = { + name: 'mysql', + insertIgnore: (table, cols) => `INSERT IGNORE INTO ${table} (${cols.join(', ')}) VALUES `, + concat: (a, b) => `CONCAT(${a}, ${b})`, + // locks the rows a write reads, so concurrent writers to one resource queue rather than retry + forUpdate: ' FOR UPDATE', + maxParams: 60000 +}; + +class MysqlDatabase { + /** + * @param {Object} cfg - host, port, database, user, password, connections + */ + constructor(cfg) { + this.cfg = cfg; + this.dialect = DIALECT; + this.pool = null; + } + + async open() { + this.pool = mysql.createPool({ + host: this.cfg.host || 'localhost', + port: this.cfg.port || 3306, + user: this.cfg.user, + password: this.cfg.password, + database: this.cfg.database, + connectionLimit: this.cfg.connections || 10, + charset: 'utf8mb4', + supportBigNumbers: true, + bigNumberStrings: false, + decimalNumbers: true, + multipleStatements: false, + timezone: 'Z' + }); + // fail now, not on the first request, if the server can't be reached + const conn = await this.pool.getConnection(); + conn.release(); + } + + async read(fn) { + const conn = await this.pool.getConnection(); + try { + return await fn(new MysqlQuery(conn, DIALECT)); + } finally { + conn.release(); + } + } + + async write(fn) { + let attempt = 0; + for (;;) { + attempt++; + const conn = await this.pool.getConnection(); + const q = new MysqlQuery(conn, DIALECT); + try { + await conn.query('SET TRANSACTION ISOLATION LEVEL READ COMMITTED'); + await conn.beginTransaction(); + q.inTransaction = true; + const result = await fn(q); + await conn.commit(); + return result; + } catch (err) { + try { + await conn.rollback(); + } catch (ignore) { + // the connection may be gone + } + const e = wrapError(err); + if ((e.busy || e.retryable) && attempt < WRITE_RETRIES) { + await delay(attempt * 50 + Math.floor(Math.random() * 50)); + continue; + } + throw e; + } finally { + q.inTransaction = false; + await q.releaseLocks(); + conn.release(); + } + } + } + + /** + * Run fn holding the schema lock (a named lock, since MySQL's DDL isn't transactional), + * with a connection outside any transaction. + */ + async withSchemaLock(fn) { + const conn = await this.pool.getConnection(); + try { + const [rows] = await conn.query('SELECT GET_LOCK(?, 120) AS got', ['fhirsmith_rest_schema']); + if (!rows[0] || rows[0].got !== 1) { + throw new Error('Unable to get the schema lock on the database within 2 minutes'); + } + try { + return await fn(new MysqlQuery(conn, DIALECT)); + } finally { + await conn.query('SELECT RELEASE_LOCK(?)', ['fhirsmith_rest_schema']); + } + } finally { + conn.release(); + } + } + + async close() { + if (this.pool) { + await this.pool.end(); + this.pool = null; + } + } +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +module.exports = { MysqlDatabase }; diff --git a/rest/database/schema.js b/rest/database/schema.js new file mode 100644 index 00000000..9f6c61b6 --- /dev/null +++ b/rest/database/schema.js @@ -0,0 +1,299 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The rest module's tables, written once and turned into DDL for SQLite or MySQL. + * + * - Every key is made by the database (autoincrement), never counted in a process. + * - Times are BIGINT milliseconds since the epoch, UTC. + * - Text is compared as binary (utf8mb4_bin in MySQL, SQLite's default): ids, codes and + * systems are case-sensitive. Case-insensitive search uses copies normalised in JavaScript. + * - The index tables are one per search parameter type, all keyed by ResourceKey and + * ParamKey; GroupNo and Comp tie together the components of a composite parameter. + * + * Column types: key (the table's autoincrement primary key), bigint, int, double, + * str(n), text, blob. + * + * @module rest/database/schema + */ + +const SCHEMA_VERSION = 1; + +// columns every index table has +const INDEX_COMMON = [ + ['ResourceKey', 'bigint', { notNull: true }], + ['ParamKey', 'bigint', { notNull: true }], + ['GroupNo', 'int'], + ['Comp', 'int'] +]; + +const TABLES = [ + { + name: 'Config', + columns: [['Name', 'str(64)', { notNull: true }], ['Value', 'text']], + primaryKey: ['Name'] + }, + { + name: 'Types', + columns: [['TypeKey', 'key'], ['Name', 'str(64)', { notNull: true }], ['Supported', 'int', { notNull: true }], ['Settings', 'text']], + indexes: [{ name: 'SK_Types_Name', columns: ['Name'], unique: true }] + }, + { + name: 'Ids', + columns: [['ResourceKey', 'key'], ['TypeKey', 'bigint', { notNull: true }], ['Id', 'str(64)', { notNull: true }], + ['MostRecent', 'bigint'], ['Deleted', 'int', { notNull: true }]], + indexes: [{ name: 'SK_Ids_Id', columns: ['TypeKey', 'Id'], unique: true }, { name: 'SK_Ids_TypeDel', columns: ['TypeKey', 'Deleted', 'ResourceKey'] }] + }, + { + name: 'Versions', + columns: [['VersionKey', 'key'], ['ResourceKey', 'bigint', { notNull: true }], ['VersionId', 'int', { notNull: true }], + ['LastUpdated', 'bigint', { notNull: true }], ['Operation', 'int', { notNull: true }], ['UserId', 'str(128)'], + ['AuditKey', 'bigint'], ['Compressed', 'int', { notNull: true }], ['Content', 'blob']], + indexes: [{ name: 'SK_Versions_ResVer', columns: ['ResourceKey', 'VersionId'], unique: true }, + { name: 'SK_Versions_Updated', columns: ['LastUpdated'] }] + }, + { + name: 'Tags', + columns: [['TagKey', 'key'], ['Kind', 'int', { notNull: true }], ['TagSystem', 'str(255)', { notNull: true }], + ['Code', 'str(255)', { notNull: true }], ['Display', 'str(255)']], + indexes: [{ name: 'SK_Tags_Code', columns: ['Kind', 'TagSystem', 'Code'], unique: true }] + }, + { + name: 'VersionTags', + columns: [['VersionKey', 'bigint', { notNull: true }], ['TagKey', 'bigint', { notNull: true }]], + primaryKey: ['VersionKey', 'TagKey'], + indexes: [{ name: 'SK_VersionTags_Tag', columns: ['TagKey', 'VersionKey'] }] + }, + { + name: 'SearchParams', + columns: [['ParamKey', 'key'], ['Url', 'str(512)', { notNull: true }], ['Code', 'str(128)', { notNull: true }], + ['Type', 'str(16)', { notNull: true }], ['Bases', 'text'], ['Expression', 'text'], ['Hash', 'str(64)', { notNull: true }], + ['Reindex', 'int', { notNull: true }]], + indexes: [{ name: 'SK_SearchParams_Url', columns: ['Url'], unique: true }] + }, + { + name: 'Spaces', + columns: [['SpaceKey', 'key'], ['Uri', 'str(512)', { notNull: true }]], + indexes: [{ name: 'SK_Spaces_Uri', columns: ['Uri'], unique: true }] + }, + { + name: 'IndexStrings', + columns: [...INDEX_COMMON, ['Norm', 'str(255)', { notNull: true }], ['Exact', 'str(1024)', { notNull: true }]], + indexes: [{ name: 'SK_IndexStrings_Value', columns: ['ParamKey', 'Norm', 'ResourceKey'] }, { name: 'SK_IndexStrings_Res', columns: ['ResourceKey'] }] + }, + { + name: 'IndexTokens', + columns: [...INDEX_COMMON, ['SpaceKey', 'bigint'], ['Code', 'str(255)', { notNull: true }], ['Implicit', 'int', { notNull: true }], + ['ConceptKey', 'bigint'], ['TextNorm', 'str(255)'], ['TypeSpaceKey', 'bigint'], ['TypeCode', 'str(255)']], + indexes: [{ name: 'SK_IndexTokens_Value', columns: ['ParamKey', 'Code', 'SpaceKey', 'ResourceKey'] }, + { name: 'SK_IndexTokens_Concept', columns: ['ParamKey', 'ConceptKey'] }, + { name: 'SK_IndexTokens_Res', columns: ['ResourceKey'] }] + }, + { + name: 'IndexDates', + columns: [...INDEX_COMMON, ['Lo', 'bigint', { notNull: true }], ['Hi', 'bigint', { notNull: true }]], + indexes: [{ name: 'SK_IndexDates_Lo', columns: ['ParamKey', 'Lo'] }, { name: 'SK_IndexDates_Hi', columns: ['ParamKey', 'Hi'] }, + { name: 'SK_IndexDates_Res', columns: ['ResourceKey'] }] + }, + { + name: 'IndexNumbers', + columns: [...INDEX_COMMON, ['Lo', 'double', { notNull: true }], ['Hi', 'double', { notNull: true }], ['Value', 'double', { notNull: true }]], + indexes: [{ name: 'SK_IndexNumbers_Lo', columns: ['ParamKey', 'Lo'] }, { name: 'SK_IndexNumbers_Res', columns: ['ResourceKey'] }] + }, + { + name: 'IndexQuantities', + columns: [...INDEX_COMMON, ['Lo', 'double', { notNull: true }], ['Hi', 'double', { notNull: true }], ['Value', 'double', { notNull: true }], + ['SpaceKey', 'bigint'], ['Unit', 'str(128)'], ['CanonLo', 'double'], ['CanonHi', 'double'], ['CanonUnit', 'str(128)']], + indexes: [{ name: 'SK_IndexQuantities_Lo', columns: ['ParamKey', 'Lo'] }, { name: 'SK_IndexQuantities_Canon', columns: ['ParamKey', 'CanonUnit', 'CanonLo'] }, + { name: 'SK_IndexQuantities_Res', columns: ['ResourceKey'] }] + }, + { + name: 'IndexReferences', + columns: [...INDEX_COMMON, ['TargetKey', 'bigint'], ['TargetType', 'str(64)'], ['TargetId', 'str(64)'], ['TargetVersion', 'str(64)'], + ['Url', 'str(512)'], ['UrlVersion', 'str(64)'], ['IdentSpaceKey', 'bigint'], ['IdentValue', 'str(255)']], + indexes: [{ name: 'SK_IndexReferences_Target', columns: ['ParamKey', 'TargetKey'] }, + { name: 'SK_IndexReferences_TargetId', columns: ['TargetId', 'TargetType', 'ParamKey'] }, + { name: 'SK_IndexReferences_Url', columns: ['ParamKey', 'Url'] }, + { name: 'SK_IndexReferences_Ident', columns: ['ParamKey', 'IdentValue'] }, + { name: 'SK_IndexReferences_TargetKey', columns: ['TargetKey'] }, + { name: 'SK_IndexReferences_Res', columns: ['ResourceKey'] }] + }, + { + name: 'IndexUris', + columns: [...INDEX_COMMON, ['Value', 'str(512)', { notNull: true }]], + indexes: [{ name: 'SK_IndexUris_Value', columns: ['ParamKey', 'Value'] }, { name: 'SK_IndexUris_Res', columns: ['ResourceKey'] }] + }, + { + name: 'Compartments', + columns: [['ResourceKey', 'bigint', { notNull: true }], ['CompType', 'str(64)', { notNull: true }], ['CompId', 'str(64)', { notNull: true }], + ['CompKey', 'bigint']], + indexes: [{ name: 'SK_Compartments_Comp', columns: ['CompType', 'CompId', 'ResourceKey'] }, { name: 'SK_Compartments_Res', columns: ['ResourceKey'] }] + }, + { + name: 'Searches', + columns: [['SearchKey', 'key'], ['SearchId', 'str(32)', { notNull: true }], ['Query', 'text'], ['Total', 'int'], + ['StoredCount', 'int', { notNull: true }], ['UserId', 'str(128)'], ['Created', 'bigint', { notNull: true }], ['Expires', 'bigint', { notNull: true }]], + indexes: [{ name: 'SK_Searches_Id', columns: ['SearchId'], unique: true }, { name: 'SK_Searches_Expires', columns: ['Expires'] }] + }, + { + name: 'SearchEntries', + columns: [['SearchKey', 'bigint', { notNull: true }], ['Pos', 'int', { notNull: true }], ['ResourceKey', 'bigint', { notNull: true }]], + primaryKey: ['SearchKey', 'Pos'] + }, + { + name: 'Concepts', + columns: [['ConceptKey', 'key'], ['SpaceKey', 'bigint', { notNull: true }], ['Code', 'str(255)', { notNull: true }], + ['InClosure', 'int', { notNull: true }]], + indexes: [{ name: 'SK_Concepts_Code', columns: ['SpaceKey', 'Code'], unique: true }, { name: 'SK_Concepts_Closure', columns: ['InClosure'] }] + }, + { + name: 'Closures', + columns: [['ClosureKey', 'key'], ['Name', 'str(128)', { notNull: true }], ['Version', 'str(64)']], + indexes: [{ name: 'SK_Closures_Name', columns: ['Name'], unique: true }] + }, + { + name: 'ClosureEntries', + columns: [['ClosureKey', 'bigint', { notNull: true }], ['SubsumesKey', 'bigint', { notNull: true }], ['SubsumedKey', 'bigint', { notNull: true }]], + primaryKey: ['ClosureKey', 'SubsumesKey', 'SubsumedKey'], + indexes: [{ name: 'SK_ClosureEntries_Subsumed', columns: ['ClosureKey', 'SubsumedKey'] }] + }, + { + name: 'SubscriptionQueue', + columns: [['QueueKey', 'key'], ['ResourceKey', 'bigint', { notNull: true }], ['VersionKey', 'bigint', { notNull: true }], + ['PreviousVersionKey', 'bigint'], ['Operation', 'int', { notNull: true }], ['Entered', 'bigint', { notNull: true }], ['Handled', 'bigint']], + indexes: [{ name: 'SK_SubscriptionQueue_Handled', columns: ['Handled'] }] + } +]; + +const INDEX_TABLES = ['IndexStrings', 'IndexTokens', 'IndexDates', 'IndexNumbers', 'IndexQuantities', 'IndexReferences', 'IndexUris']; + +function columnType(type, dialect) { + const m = /^str\((\d+)\)$/.exec(type); + if (dialect === 'sqlite') { + if (m || type === 'text') { + return 'TEXT'; + } + return { key: 'INTEGER PRIMARY KEY AUTOINCREMENT', bigint: 'INTEGER', int: 'INTEGER', double: 'REAL', blob: 'BLOB' }[type]; + } + if (m) { + return `VARCHAR(${m[1]})`; + } + return { key: 'BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY', bigint: 'BIGINT', int: 'INT', double: 'DOUBLE', text: 'MEDIUMTEXT', blob: 'LONGBLOB' }[type]; +} + +/** + * The statements that create a table and its indexes. + * @param {Object} table - from TABLES + * @param {string} dialect - 'sqlite' or 'mysql' + * @returns {string[]} + */ +function tableDDL(table, dialect) { + const cols = table.columns.map(([name, type, opts]) => { + let s = `${name} ${columnType(type, dialect)}`; + if (opts && opts.notNull && type !== 'key') { + s += ' NOT NULL'; + } + return s; + }); + if (table.primaryKey) { + cols.push(`PRIMARY KEY (${table.primaryKey.join(', ')})`); + } + let create = `CREATE TABLE ${table.name} (${cols.join(', ')})`; + if (dialect === 'mysql') { + create += ' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin'; + } + const out = [create]; + for (const ix of table.indexes || []) { + out.push(`CREATE ${ix.unique ? 'UNIQUE ' : ''}INDEX ${ix.name} ON ${table.name} (${ix.columns.join(', ')})`); + } + return out; +} + +/** + * The schema's migrations, by version: each a function(q) that brings the schema from the + * version before to this one. Version 1 creates everything. + */ +const MIGRATIONS = { + 1: async (q) => { + for (const table of TABLES) { + for (const sql of tableDDL(table, q.dialect.name)) { + await q.exec(sql); + } + } + } +}; + +async function tableExists(q, name) { + if (q.dialect.name === 'sqlite') { + const row = await q.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", [name]); + return !!row; + } + const row = await q.get('SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [name]); + return !!row; +} + +/** + * The schema version of the database, 0 if it has no tables yet. + * @param {Object} q - a query object + */ +async function schemaVersion(q) { + if (!(await tableExists(q, 'Config'))) { + return 0; + } + const row = await q.get("SELECT Value FROM Config WHERE Name = 'schemaVersion'"); + return row ? parseInt(row.Value, 10) : 0; +} + +/** + * Bring the database's schema up to date, holding the schema lock. Run by the master (or a + * process with no role) at start. + * @param {Object} db - an open database + * @param {function(string)} [log] + * @returns {Promise} the version it was at + */ +async function migrate(db, log = () => {}) { + return db.withSchemaLock(async (q) => { + const from = await schemaVersion(q); + if (from > SCHEMA_VERSION) { + throw new Error(`The database's schema is version ${from}, newer than this server knows (${SCHEMA_VERSION}): upgrade the server`); + } + for (let v = from + 1; v <= SCHEMA_VERSION; v++) { + log(`Migrating the database schema to version ${v}`); + await MIGRATIONS[v](q); + if (v === 1) { + await q.run("INSERT INTO Config (Name, Value) VALUES ('schemaVersion', ?)", [String(v)]); + } else { + await q.run("UPDATE Config SET Value = ? WHERE Name = 'schemaVersion'", [String(v)]); + } + } + return from; + }); +} + +/** + * Wait until the master has brought the schema to this server's version. A worker never + * changes the schema; it refuses a schema newer than it knows. + * @param {Object} db + * @param {number} [timeoutMs] + */ +async function waitForSchema(db, timeoutMs = 120000) { + const start = Date.now(); + for (;;) { + const v = await db.read(schemaVersion); + if (v === SCHEMA_VERSION) { + return; + } + if (v > SCHEMA_VERSION) { + throw new Error(`The database's schema is version ${v}, newer than this server knows (${SCHEMA_VERSION}): upgrade the server`); + } + if (Date.now() - start > timeoutMs) { + throw new Error(`The database's schema is version ${v}; waited ${timeoutMs / 1000}s for the master to bring it to ${SCHEMA_VERSION}`); + } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } +} + +module.exports = { SCHEMA_VERSION, TABLES, INDEX_TABLES, tableDDL, migrate, waitForSchema, schemaVersion }; diff --git a/rest/database/sqlite.js b/rest/database/sqlite.js new file mode 100644 index 00000000..480e1c57 --- /dev/null +++ b/rest/database/sqlite.js @@ -0,0 +1,231 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The SQLite implementation of the rest module's database interface (database/index.js). + * + * It uses the async `sqlite3` driver, not `better-sqlite3`: a synchronous driver blocks the + * process for the length of every query, and a slow search would stop every other request + * on the process. + * + * - WAL mode, so readers don't block the writer, with a busy timeout. + * - One writer at a time across all processes: within a process, writes queue for the one + * write connection; across processes, BEGIN IMMEDIATE takes the write lock at the start of + * the transaction (a transaction that starts as a reader and upgrades fails with + * SQLITE_BUSY under load instead of waiting). + * - Reads come from a small pool, and a connection never runs two queries at once (see + * library/sqlite-pool.js for why). + * + * @module rest/database/sqlite + */ + +const sqlite3 = require('sqlite3'); + +const READERS = 4; +const BUSY_TIMEOUT_MS = 30000; +const WRITE_RETRIES = 5; + +function openConnection(file, mode) { + return new Promise((resolve, reject) => { + const db = new sqlite3.Database(file, mode, (err) => err ? reject(err) : resolve(db)); + }); +} + +/** + * One connection, as the database interface's query object: all, get, run, exec. + */ +class SqliteQuery { + constructor(db, dialect) { + this.db = db; + this.dialect = dialect; + this.inTransaction = false; + } + + all(sql, params = []) { + return new Promise((resolve, reject) => { + this.db.all(sql, params, (err, rows) => err ? reject(wrapError(err, sql)) : resolve(rows)); + }); + } + + get(sql, params = []) { + return new Promise((resolve, reject) => { + this.db.get(sql, params, (err, row) => err ? reject(wrapError(err, sql)) : resolve(row)); + }); + } + + run(sql, params = []) { + return new Promise((resolve, reject) => { + this.db.run(sql, params, function (err) { + if (err) { + reject(wrapError(err, sql)); + } else { + resolve({ changes: this.changes, lastId: this.lastID }); + } + }); + }); + } + + /** A named lock: nothing to do, since a SQLite write transaction holds the database's write lock */ + async lock() {} + + exec(sql) { + return new Promise((resolve, reject) => { + this.db.exec(sql, (err) => err ? reject(wrapError(err, sql)) : resolve()); + }); + } +} + +function wrapError(err, sql) { + if (err && /UNIQUE constraint failed|PRIMARY KEY must be unique/i.test(err.message)) { + err.unique = true; + } + if (err && (err.code === 'SQLITE_BUSY' || err.code === 'SQLITE_LOCKED')) { + err.busy = true; + } + if (err && sql && !err.sql) { + err.sql = sql; + } + return err; +} + +const DIALECT = { + name: 'sqlite', + insertIgnore: (table, cols) => `INSERT OR IGNORE INTO ${table} (${cols.join(', ')}) VALUES `, + concat: (a, b) => `(${a} || ${b})`, + // a write transaction already holds the database's write lock + forUpdate: '', + // the most ? in one statement (SQLITE_MAX_VARIABLE_NUMBER is 32766 in current builds) + maxParams: 30000 +}; + +class SqliteDatabase { + /** + * @param {string} file - the database file + */ + constructor(file) { + this.file = file; + this.dialect = DIALECT; + this.readers = []; + this.free = []; + this.waiting = []; + this.writer = null; + this.writeQueue = Promise.resolve(); + } + + async open() { + const w = await openConnection(this.file, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE); + w.configure('busyTimeout', BUSY_TIMEOUT_MS); + this.writer = new SqliteQuery(w, DIALECT); + await this.writer.exec('PRAGMA journal_mode = WAL'); + await this.writer.exec('PRAGMA synchronous = NORMAL'); + for (let i = 0; i < READERS; i++) { + // read-write connections that only read: a read-only one may not see a schema change + // another connection makes (library/sqlite-pool.js) + const r = await openConnection(this.file, sqlite3.OPEN_READWRITE); + r.configure('busyTimeout', BUSY_TIMEOUT_MS); + const q = new SqliteQuery(r, DIALECT); + this.readers.push(q); + this.free.push(q); + } + } + + acquire() { + if (this.free.length > 0) { + return Promise.resolve(this.free.pop()); + } + return new Promise((resolve) => this.waiting.push(resolve)); + } + + release(q) { + const next = this.waiting.shift(); + if (next) { + next(q); + } else { + this.free.push(q); + } + } + + /** + * Run fn with a connection for reading. + * @param {function(SqliteQuery): Promise<*>} fn + */ + async read(fn) { + const q = await this.acquire(); + try { + return await fn(q); + } finally { + this.release(q); + } + } + + /** + * Run fn in a write transaction: committed if it returns, rolled back if it throws, and run + * again if the database is busy or fn throws an error marked retryable. + * @param {function(SqliteQuery): Promise<*>} fn + */ + write(fn) { + const run = async () => { + let attempt = 0; + for (;;) { + attempt++; + const q = this.writer; + try { + await q.exec('BEGIN IMMEDIATE'); + } catch (err) { + if (err.busy && attempt < WRITE_RETRIES) { + await delay(attempt * 50); + continue; + } + throw err; + } + q.inTransaction = true; + try { + const result = await fn(q); + await q.exec('COMMIT'); + return result; + } catch (err) { + try { + await q.exec('ROLLBACK'); + } catch (ignore) { + // the transaction may already be gone + } + if ((err.busy || err.retryable) && attempt < WRITE_RETRIES) { + await delay(attempt * 50); + continue; + } + throw err; + } finally { + q.inTransaction = false; + } + } + }; + // one transaction at a time on the write connection + const result = this.writeQueue.then(run, run); + this.writeQueue = result.then(() => undefined, () => undefined); + return result; + } + + /** + * Run fn holding the schema lock: for SQLite, a write transaction (DDL is transactional). + */ + async withSchemaLock(fn) { + return this.write(fn); + } + + async close() { + const all = [this.writer, ...this.readers].filter(q => q); + await Promise.all(all.map(q => new Promise((resolve) => q.db.close(() => resolve())))); + this.readers = []; + this.free = []; + this.writer = null; + } +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +module.exports = { SqliteDatabase }; diff --git a/rest/endpoint/endpoint.js b/rest/endpoint/endpoint.js new file mode 100644 index 00000000..b05f30c6 --- /dev/null +++ b/rest/endpoint/endpoint.js @@ -0,0 +1,654 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * One FHIR endpoint: its database, settings, definitions, and the express router that serves + * it. Every request goes the same way: + * + * request.js the HTTP request (or Bundle entry) as a FHIR request, and its interaction + * access.js whether the user may do it, and with what compartment limits + * interaction inside a database transaction (interactions/, search/, operations/) + * respond() the result in the negotiated format (format.js) + * + * What changes rarely is cached in the process: settings, Types, the definitions with their + * compiled expressions, and Spaces and Tags keys. The Config table's generation number is + * compared with the database's at most once a second, and everything reloads when it + * changes. Resources and search results are never cached. + * + * @module rest/endpoint/endpoint + */ + +const express = require('express'); +const crypto = require('crypto'); +const { openDatabase } = require('../database'); +const settingsStore = require('./settings'); +const { Definitions, loadDerived, corePackage, majorMinor } = require('../indexing/definitions'); +const { Indexer } = require('../indexing/indexer'); +const { Lookups } = require('../database/lookups'); +const { Store } = require('../store'); +const { Searcher } = require('../search/search'); +const { shape } = require('../search/shape'); +const { auditBuilder } = require('../audit/audit'); +const { Terminology } = require('../terminology'); +const { FhirError, notFound, notAllowed, forbidden, operationOutcome } = require('../library/errors'); +const format = require('../format'); +const request = require('../request'); +const access = require('../access'); +const crud = require('../interactions/crud'); +const { history } = require('../interactions/history'); +const { capabilities } = require('../interactions/capabilities'); +const { bundle } = require('../interactions/bundle'); +const { findOperation } = require('../operations/operations'); +const { RestWeb, wantsHtml } = require('../web'); + +const GENERATION_CHECK_MS = 1000; +const AUDIT_FLUSH_MS = 1000; +const MAX_AUDIT_BUFFER = 5000; +const REINDEX_BATCH = 200; + +// the role an interaction needs, by what access.js calls it +const ACCESS_NAMES = { + 'conditional-update': 'update', 'conditional-delete': 'delete', 'conditional-patch': 'patch' +}; + +class Endpoint { + /** + * @param {Object} cfg - one entry of modules.rest.endpoints: { path, database, fhirVersion, + * baseUrl?, initialSettings?, types? } + * @param {Object} options + * @param {string} options.databasesDir + * @param {boolean} options.master - runs migrations and the background jobs + * @param {Object} options.log - a logger (info, warn, error, debug) + * @param {Object} [options.packageManager] - library/package-manager PackageManager + * @param {string} [options.cacheFolder] - where derived definitions are cached + * @param {Object} [options.derived] - definitions already derived (tests) + * @param {Function} [options.app] - the express app, for a terminology server on this server + * @param {function(Object): Promise} [options.principal] - who a request is + * @param {string} [options.hostName] + */ + constructor(cfg, options) { + if (!cfg || typeof cfg.path !== 'string' || !/^\/[A-Za-z0-9/_-]*$/.test(cfg.path)) { + throw new Error(`A rest endpoint needs a path like /fhir/r4, not '${cfg && cfg.path}'`); + } + this.cfg = cfg; + this.path = cfg.path.replace(/\/+$/, ''); + this.options = options; + this.log = options.log; + this.master = options.master !== false; + this.startedAt = Date.now(); + this.timers = []; + this.auditBuffer = []; + this.lastGenerationCheck = 0; + this.generation = null; + this.bundleReturnsResources = true; + this.terminology = null; + } + + // ---- start up and refresh ---- + + async open() { + const cfg = this.cfg; + this.db = await openDatabase(cfg.database, { databasesDir: this.options.databasesDir, master: this.master, log: (m) => this.log.info(m) }); + // the FHIR version is fixed when the database is made + const initial = { ...(cfg.initialSettings || {}) }; + if (cfg.fhirVersion) { + initial.fhirVersion = cfg.fhirVersion; + } + if (this.master) { + await settingsStore.seed(this.db, initial, []); + } + let loaded = await settingsStore.load(this.db); + if (!loaded.endpoint.fhirVersion) { + throw new Error(`The rest endpoint ${this.path} has no FHIR version: give fhirVersion in its configuration`); + } + if (cfg.fhirVersion && majorMinor(cfg.fhirVersion) !== majorMinor(loaded.endpoint.fhirVersion)) { + throw new Error(`The rest endpoint ${this.path}'s database is FHIR ${loaded.endpoint.fhirVersion}, but the configuration says ${cfg.fhirVersion}`); + } + this.warnOverridden(cfg.initialSettings || {}, loaded.endpoint); + await this.loadDefinitions(loaded.endpoint); + if (this.master) { + await settingsStore.seed(this.db, {}, [...this.definitions.resourceTypes], cfg.types || {}); + } + await this.apply(await settingsStore.load(this.db)); + this.web = new RestWeb(this); + if (this.master) { + this.startJobs(); + } + this.auditTimer = setInterval(() => { + this.flushAudits().catch(e => this.log.error(`Rest ${this.path}: writing AuditEvents failed: ${e.message}`)); + }, AUDIT_FLUSH_MS); + this.auditTimer.unref(); + loaded = null; + this.log.info(`Rest endpoint ${this.path}: FHIR ${this.settings.fhirVersion}, ${this.typeKeys.size} types, ${this.definitions.byUrl.size} search parameters, ` + + `${this.cfg.database.type} database${this.master ? '' : ' (worker)'}`); + } + + /** + * initialSettings are only written into a new database: say so when the database has + * something else, since the configuration then looks like it says what the endpoint does + */ + warnOverridden(initial, current) { + for (const [name, value] of Object.entries(initial)) { + if (!(name in current)) { + continue; + } + const a = JSON.stringify(Array.isArray(value) ? value : String(value)); + const b = JSON.stringify(Array.isArray(current[name]) ? current[name] : String(current[name])); + if (a !== b) { + this.log.warn(`Rest ${this.path}: initialSettings.${name} is ${a} in config.json, but the database has ${b}, which is what is used ` + + '(initialSettings are only written into a new database: change the Config table, and bump its generation row)'); + } + } + } + + async loadDefinitions(endpointSettings) { + const fhirVersion = endpointSettings.fhirVersion; + let derived = this.options.derived; + if (!derived) { + const packages = [corePackage(fhirVersion), ...(endpointSettings.packages || [])]; + derived = await loadDerived({ fhirVersion, packages, packageManager: this.options.packageManager, cacheFolder: this.options.cacheFolder }); + } + let custom = []; + if (endpointSettings.customSearchParameters) { + custom = await this.storedSearchParameters(); + } + const defs = new Definitions(derived, custom, (level, msg) => this.log[level === 'warn' ? 'warn' : 'debug'](`Rest ${this.path}: ${msg}`)); + const hasResources = await this.db.read(async (q) => !!(await q.get('SELECT ResourceKey FROM Ids WHERE MostRecent IS NOT NULL LIMIT 1'))); + const changed = await defs.sync(this.db, this.master, hasResources); + const reload = !!this.definitions; + this.definitions = defs; + if (reload && this.master && changed.added + changed.changed > 0) { + // the workers pick up the new definitions' keys + await this.db.write(q => settingsStore.bumpGeneration(q)); + this.log.info(`Rest ${this.path}: ${changed.added} new and ${changed.changed} changed search parameters: reindexing`); + } + } + + async storedSearchParameters() { + const out = []; + await this.db.read(async (q) => { + const t = await q.get('SELECT TypeKey FROM Types WHERE Name = ?', ['SearchParameter']); + if (!t) { + return; + } + const rows = await q.all('SELECT v.Compressed, v.Content FROM Ids i JOIN Versions v ON v.VersionKey = i.MostRecent WHERE i.TypeKey = ? AND i.Deleted = 0', [t.TypeKey]); + const { decode } = require('../store'); + for (const r of rows) { + const sp = decode(r); + if (sp && sp.status !== 'retired') { + out.push(sp); + } + } + }); + return out; + } + + async apply(loaded) { + this.generation = loaded.generation; + this.settings = loaded.endpoint; + this.types = loaded.types; + this.typeKeys = loaded.typeKeys; + this.timeZone = this.settings.timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone; + this.baseUrl = this.cfg.baseUrl || (this.options.hostName ? `https://${this.options.hostName}${this.path}` : null); + if (!this.lookups) { + this.lookups = new Lookups(); + } + this.indexer = new Indexer({ definitions: this.definitions, lookups: this.lookups, typeKeys: this.typeKeys, timeZone: this.timeZone, + baseUrls: [this.baseUrl].filter(x => x), checkReferences: this.settings.checkReferences, log: (l, m) => this.log.debug(m) }); + this.store = new Store(this); + this.searcher = new Searcher(this); + this.audit = auditBuilder(this.settings.fhirVersion); + this.terminology = null; + if (this.settings.txServer) { + try { + this.terminology = new Terminology(this.settings.txServer, { app: this.options.app, log: this.log, closureName: await this.closureName() }); + } catch (e) { + this.log.error(`Rest ${this.path}: txServer: ${e.message}`); + } + } + } + + async closureName() { + const row = await this.db.read(q => q.get('SELECT Name FROM Closures ORDER BY ClosureKey LIMIT 1')); + return row ? row.Name : 'fhirsmith-rest-' + crypto.randomBytes(8).toString('hex'); + } + + /** Reload when the settings' generation has changed (at most once a second) */ + async refresh() { + const now = Date.now(); + if (now - this.lastGenerationCheck < GENERATION_CHECK_MS) { + return; + } + this.lastGenerationCheck = now; + const g = await this.db.read(q => settingsStore.readGeneration(q)); + if (g !== this.generation) { + const loaded = await settingsStore.load(this.db); + const packagesChanged = JSON.stringify(loaded.endpoint.packages) !== JSON.stringify(this.settings.packages) || + loaded.endpoint.customSearchParameters !== this.settings.customSearchParameters; + if (packagesChanged || loaded.endpoint.customSearchParameters) { + await this.loadDefinitions(loaded.endpoint); + } else { + // the reindexing flags may have changed + const hasResources = true; + await this.definitions.sync(this.db, false, hasResources); + } + await this.apply(loaded); + this.log.info(`Rest ${this.path}: settings reloaded (generation ${g})`); + } + } + + // ---- helpers for the interactions ---- + + inRead(ctx, fn) { + return ctx && ctx.q ? fn(ctx.q) : this.db.read(fn); + } + + inWrite(ctx, fn) { + return ctx && ctx.q ? fn(ctx.q) : this.db.write(fn); + } + + typeSettings(type) { + return this.types.get(type) || { supported: false }; + } + + typeSupported(type) { + const t = this.types.get(type); + return !!(t && t.supported); + } + + /** + * Check a type exists, is supported, and allows an interaction (405 if not). + */ + checkType(type, interaction) { + if (!this.typeKeys.has(type)) { + throw notFound(`Unknown resource type ${type}`); + } + const t = this.typeSettings(type); + if (!t.supported) { + throw notFound(`The resource type ${type} is not supported on this endpoint`); + } + if (interaction && !settingsStore.typeAllows(t, interaction)) { + throw notAllowed(`${interaction} is not allowed for ${type} on this endpoint`); + } + } + + userId(freq) { + const p = freq.principal; + return p ? String(p.login || p.id) : null; + } + + /** The access name of a request's interaction */ + accessInteraction(freq) { + if (freq.interaction === 'operation') { + try { + return findOperation(freq).read ? 'operation-read' : 'operation'; + } catch (e) { + return 'operation'; + } + } + return ACCESS_NAMES[freq.interaction] || freq.interaction; + } + + /** + * SQL limiting resource keys to the request's compartments, or null for no limit. + */ + compartmentFilter(acc, keyExpr) { + if (!acc || !acc.compartments) { + return null; + } + if (acc.compartments.length === 0) { + return { sql: '1 = 0', args: [] }; + } + const parts = []; + const args = []; + for (const c of acc.compartments) { + const [type, id] = c.split('/'); + parts.push('(ac.CompType = ? AND ac.CompId = ?)'); + args.push(type, id); + } + return { sql: `EXISTS (SELECT 1 FROM Compartments ac WHERE ac.ResourceKey = ${keyExpr} AND (${parts.join(' OR ')}))`, args }; + } + + /** Throw 403 if a resource is outside the request's compartments */ + async checkCompartments(q, acc, resourceKey) { + const f = this.compartmentFilter(acc, 'Ids.ResourceKey'); + if (!f) { + return; + } + const row = await q.get(`SELECT 1 AS ok FROM Ids WHERE ResourceKey = ? AND ${f.sql}`, [resourceKey, ...f.args]); + if (!row) { + throw forbidden('The resource is outside the compartments you have access to'); + } + } + + /** Keep the keys inside the request's compartments */ + async filterKeysByAccess(q, acc, keys) { + const f = this.compartmentFilter(acc, 'i.ResourceKey'); + if (!f || !keys.length) { + return keys; + } + const rows = await q.all(`SELECT i.ResourceKey FROM Ids i WHERE i.ResourceKey IN (${keys.map(() => '?').join(', ')}) AND ${f.sql}`, [...keys, ...f.args]); + const ok = new Set(rows.map(r => Number(r.ResourceKey))); + return keys.filter(k => ok.has(k)); + } + + /** _summary / _elements on a resource */ + shapeResource(resource, freq, control) { + const c = control || { + summary: request.param(freq, '_summary') || null, + elements: request.param(freq, '_elements') ? request.param(freq, '_elements').split(',').map(s => s.trim()).filter(s => s) : null + }; + if (!c.summary && !(c.elements && c.elements.length)) { + return resource; + } + return shape(resource, c, this.definitions); + } + + /** + * Take the lock for a conditional create or update (MySQL; SQLite's write lock already + * serialises them). + */ + async conditionalLock(q, type, params) { + const norm = params.map(([n, v]) => `${n}=${v}`).sort().join('&'); + const name = 'fhirsmith_rest_' + crypto.createHash('sha256').update(`${this.path}|${type}|${norm}`).digest('hex').substring(0, 40); + await q.lock(name); + } + + // ---- audit ---- + + auditing(kind) { + const a = this.settings.audit; + return a === 'all' || (a === 'writes' && kind === 'write'); + } + + /** + * Record an AuditEvent for a write, in the write's transaction, and point the version at it. + */ + async auditWrite(q, freq, interaction, status, what, versionKey) { + if (!this.auditing('write') || !this.typeSupported('AuditEvent')) { + return; + } + const ev = this.audit.build({ interaction, status, principal: freq.principal, ip: freq.ip, what, source: freq.base }); + const r = await this.store.put(q, { type: 'AuditEvent', id: null, resource: ev, mustCreate: true, userId: this.userId(freq), deferChecks: true }); + if (versionKey) { + await this.store.setAudit(q, versionKey, r.resourceKey); + } + } + + /** An AuditEvent for later (reads, and failures): written by flushAudits */ + auditLater(freq, interaction, status, outcomeText) { + if (!this.typeSupported('AuditEvent') || this.auditBuffer.length >= MAX_AUDIT_BUFFER) { + return; + } + const what = freq.type ? `${freq.type}${freq.id ? '/' + freq.id : ''}${freq.vid ? '/_history/' + freq.vid : ''}` : undefined; + const query = freq.params && freq.params.length ? freq.params.map(([n, v]) => `${n}=${v}`).join('&') : undefined; + this.auditBuffer.push({ + ev: this.audit.build({ interaction, status, outcomeText, principal: freq.principal, ip: freq.ip, what: freq.id ? what : undefined, + query: freq.id ? undefined : (what ? what + (query ? '?' + query : '') : query), source: freq.base, time: Date.now() }), + userId: this.userId(freq) + }); + } + + async flushAudits() { + if (!this.auditBuffer.length) { + return; + } + const list = this.auditBuffer.splice(0); + await this.db.write(async (q) => { + for (const a of list) { + await this.store.put(q, { type: 'AuditEvent', id: null, resource: a.ev, mustCreate: true, userId: a.userId, deferChecks: true }); + } + }); + } + + // ---- requests ---- + + /** + * Run a FHIR request. + * @param {Object} freq - from request.js + * @param {Object} ctx - { access, q?, reservation?, reserved?, deferChecks? } + * @returns {Promise<{status: number, resource?: Object, headers?: Object, outcome?: Object, write?: boolean}>} + */ + async dispatch(freq, ctx) { + switch (freq.interaction) { + case 'read': return crud.read(this, freq, ctx); + case 'vread': return crud.vread(this, freq, ctx); + case 'create': return crud.create(this, freq, ctx); + case 'update': return crud.update(this, freq, ctx); + case 'conditional-update': return crud.conditionalUpdate(this, freq, ctx); + case 'patch': return crud.patch(this, freq, ctx); + case 'conditional-patch': return crud.conditionalPatch(this, freq, ctx); + case 'delete': return crud.remove(this, freq, ctx); + case 'conditional-delete': return crud.conditionalDelete(this, freq, ctx); + case 'history-instance': + case 'history-type': + case 'history-system': + return history(this, freq, ctx); + case 'search-type': + case 'search-system': + return this.searcher.search(freq, ctx); + case 'capabilities': return capabilities(this, freq, ctx); + case 'bundle': + if (ctx.q) { + throw new FhirError(400, 'invalid', 'A Bundle can\'t contain another batch or transaction'); + } + return bundle(this, freq); + case 'operation': { + const op = findOperation(freq); + if (freq.type) { + this.checkType(freq.type, null); + } + return op.run(this, freq, ctx); + } + } + throw notAllowed(`${freq.interaction} is not supported`); + } + + /** The express router for the endpoint */ + router() { + const r = express.Router(); + const limit = this.options.maxBody || '50mb'; + // bodies the server's own parsers don't take: JSON Patch, and _search forms + r.use(express.raw({ type: ['application/json-patch+json'], limit })); + r.use(express.text({ type: ['application/x-www-form-urlencoded'], limit })); + r.all(/.*/, (req, res) => { + this.handle(req, res).catch((e) => { + this.log.error(`Rest ${this.path}: ${e.stack || e.message}`); + if (!res.headersSent) { + res.status(500).end(); + } + }); + }); + return r; + } + + baseFor(req) { + return this.cfg.baseUrl || `${req.protocol}://${req.get('host')}${req.baseUrl}`; + } + + async handle(req, res) { + const start = Date.now(); + let freq = null; + let interaction = 'unknown'; + try { + await this.refresh(); + format.responseFormat(req); + const principal = this.options.principal ? await this.options.principal(req) : null; + const isPatch = req.method === 'PATCH'; + const body = ['POST', 'PUT', 'PATCH'].includes(req.method) && !(req.method === 'POST' && /\/_search\/?(\?|$)/.test(req.originalUrl)) + ? format.requestBody(req, { patch: isPatch }) : null; + freq = request.fromHttp(req, body, principal, this.baseFor(req)); + interaction = freq.interaction; + const acc = access.check(principal, this, this.accessInteraction(freq)); + if (wantsHtml(req)) { + // a browser: the same interaction, as a page (web.js) + await this.web.page(req, res, freq, acc, start); + return; + } + const result = await this.dispatch(freq, { access: acc }); + if (this.auditing('all') && !result.write && freq.interaction !== 'bundle') { + this.auditLater(freq, freq.interaction === 'operation' ? 'operation' : freq.interaction, result.status); + } + this.respond(req, res, freq, result); + } catch (e) { + if (!(e instanceof FhirError)) { + this.log.error(`Rest ${this.path}: ${req.method} ${req.originalUrl} failed: ${e.stack || e.message}`); + } + const fe = e instanceof FhirError ? e : new FhirError(500, 'exception', 'Internal error'); + if (freq && this.settings && this.settings.audit !== 'off' && fe.status !== 401) { + this.auditLater(freq, freq.interaction === 'bundle' ? 'transaction' : interaction, fe.status, fe.message); + } + if (wantsHtml(req) && this.web) { + this.web.error(req, res, fe, start); + } else { + this.sendError(req, res, fe); + } + } finally { + if (this.options.stats) { + this.options.stats.countRequest(interaction, Date.now() - start); + } + } + } + + sendError(req, res, fe) { + res.status(fe.status); + for (const [k, v] of Object.entries(fe.headers || {})) { + res.set(k, v); + } + if (fe.status === 401) { + res.set('WWW-Authenticate', 'Bearer'); + } + res.set('Content-Type', format.FHIR_JSON + '; charset=utf-8'); + res.send(format.serialise(req, fe.outcome())); + } + + respond(req, res, freq, result) { + res.status(result.status); + for (const [k, v] of Object.entries(result.headers || {})) { + res.set(k, v); + } + if (result.status === 304) { + res.end(); + return; + } + let body = null; + if (result.write) { + const pr = request.preferReturn(freq); + if (pr === 'minimal') { + body = null; + } else if (pr === 'OperationOutcome') { + body = operationOutcome([result.outcome || { severity: 'information', code: 'informational', diagnostics: 'Done' }]); + } else { + body = result.resource || (result.outcome ? operationOutcome([result.outcome]) : null); + } + } else if (result.resource) { + body = result.shape ? this.shapeResource(result.resource, freq) : result.resource; + } else if (result.outcome) { + body = operationOutcome([result.outcome]); + } + if (body === null || req.method === 'HEAD') { + if (body !== null) { + res.set('Content-Type', format.FHIR_JSON + '; charset=utf-8'); + } + res.end(); + return; + } + res.set('Content-Type', format.FHIR_JSON + '; charset=utf-8'); + res.send(format.serialise(req, body)); + } + + // ---- background jobs (the master) ---- + + startJobs() { + const every = (ms, name, fn) => { + let running = false; + const t = setInterval(() => { + if (running) { + return; + } + running = true; + fn().catch(e => this.log.error(`Rest ${this.path}: ${name} failed: ${e.message}`)).finally(() => { + running = false; + }); + }, ms); + t.unref(); + this.timers.push(t); + }; + every(5 * 60 * 1000, 'search cleanup', () => this.searcher.cleanup()); + every(5000, 'closure update', async () => { + if (this.terminology) { + await this.terminology.updateClosure(this); + } + }); + every(2000, 'reindexing', async () => { + // the master notices new definitions (a custom SearchParameter) here, not only on requests + await this.refresh(); + await this.reindexBatch(); + }); + } + + /** + * Reindex a batch of resources, while search parameters are marked for reindexing. Each + * batch is its own transaction, so requests keep being served. + * @returns {Promise} how many resources were reindexed + */ + async reindexBatch() { + if (!this.definitions.reindexing || this.definitions.reindexing.size === 0) { + return 0; + } + const fromRow = await this.db.read(q => q.get('SELECT Value FROM Config WHERE Name = ?', ['reindexFrom'])); + const from = fromRow ? Number(fromRow.Value) : 0; + const rows = await this.db.read(q => q.all(`SELECT ResourceKey FROM Ids WHERE ResourceKey > ? AND Deleted = 0 AND MostRecent IS NOT NULL ORDER BY ResourceKey LIMIT ${REINDEX_BATCH}`, [from])); + const { decode } = require('../store'); + await this.db.write(async (q) => { + for (const r of rows) { + const v = await q.get('SELECT v.Compressed, v.Content FROM Ids i JOIN Versions v ON v.VersionKey = i.MostRecent WHERE i.ResourceKey = ? AND i.Deleted = 0', [r.ResourceKey]); + const resource = v ? decode(v) : null; + if (resource) { + await this.indexer.index(q, { resourceKey: Number(r.ResourceKey), resource, deferChecks: true }); + } + } + if (rows.length) { + const last = String(rows[rows.length - 1].ResourceKey); + const u = await q.run('UPDATE Config SET Value = ? WHERE Name = ?', [last, 'reindexFrom']); + if (!u.changes) { + await q.run('INSERT INTO Config (Name, Value) VALUES (?, ?)', ['reindexFrom', last]); + } + } else { + // done: clear the flags, and tell every process + await q.run('UPDATE SearchParams SET Reindex = 0 WHERE Reindex = 1'); + await q.run('DELETE FROM Config WHERE Name = ?', ['reindexFrom']); + await settingsStore.bumpGeneration(q); + } + }); + if (!rows.length) { + this.definitions.reindexing = new Set(); + this.log.info(`Rest ${this.path}: reindexing finished`); + } + return rows.length; + } + + async close() { + for (const t of this.timers) { + clearInterval(t); + } + this.timers = []; + if (this.auditTimer) { + clearInterval(this.auditTimer); + } + try { + await this.flushAudits(); + } catch (e) { + this.log.error(`Rest ${this.path}: writing AuditEvents failed: ${e.message}`); + } + if (this.db) { + await this.db.close(); + this.db = null; + } + } +} + +module.exports = { Endpoint }; diff --git a/rest/endpoint/settings.js b/rest/endpoint/settings.js new file mode 100644 index 00000000..12397e86 --- /dev/null +++ b/rest/endpoint/settings.js @@ -0,0 +1,225 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * An endpoint's settings. config.json says where the endpoint is and which database it uses; + * everything else is in the endpoint's own database: the Config table (endpoint settings) and + * Types.Settings (per type). There are no admin pages yet, so they are set in the database + * directly, or seeded from the endpoint's "initialSettings" in config.json when the database is + * new (a setting already in the database is never overwritten from config.json). + * + * Config carries a generation number that changes whenever a setting does: a process compares + * its own with the database's at most once a second and reloads when they differ. + * + * @module rest/endpoint/settings + */ + +const ENDPOINT_DEFAULTS = { + name: 'FHIRsmith REST server', + description: null, + fhirVersion: null, + // packages beyond the core, 'id#version' + packages: [], + // server-assigned ids: 'key' (the resource key) or 'uuid' + idStrategy: 'key', + createOnUpdate: true, + checkReferences: true, + // the terminology server for $closure and :in/:not-in: a path on this server, or a URL + txServer: null, + // 'off', 'writes' or 'all' + audit: 'writes', + defaultCount: 50, + maxCount: 500, + searchKeepMinutes: 30, + searchMaxResults: 20000, + // above this many results, _total is an estimate unless asked for as accurate + totalEstimateAbove: 10000, + // dates without a zone: IANA name, null for the server's own + timeZone: null, + compress: true, + transactionMaxEntries: 1000, + // 'none', 'read' (a public server) or 'write' (a sandbox) + anonymous: 'none', + customSearchParameters: false, + // the most matches a conditional delete deletes (1: only a single match) + conditionalDeleteMax: 1 +}; + +const TYPE_DEFAULTS = { + versionAware: false, + // null: all of them + interactions: null, + conditionalCreate: true, + conditionalUpdate: true, + conditionalDelete: true +}; + +const INTERACTIONS = ['read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'history-type', 'create', 'search-type']; + +const BOOLEANS = new Set(Object.keys(ENDPOINT_DEFAULTS).filter(k => typeof ENDPOINT_DEFAULTS[k] === 'boolean')); +const NUMBERS = new Set(Object.keys(ENDPOINT_DEFAULTS).filter(k => typeof ENDPOINT_DEFAULTS[k] === 'number')); + +function parseValue(name, text) { + if (text === null || text === undefined) { + return ENDPOINT_DEFAULTS[name]; + } + if (BOOLEANS.has(name)) { + return text === 'true' || text === '1' || text === 'on'; + } + if (NUMBERS.has(name)) { + const n = Number(text); + return Number.isFinite(n) ? n : ENDPOINT_DEFAULTS[name]; + } + if (name === 'packages') { + try { + const v = JSON.parse(text); + return Array.isArray(v) ? v : []; + } catch (e) { + return String(text).split(',').map(s => s.trim()).filter(s => s); + } + } + return text; +} + +function valueText(v) { + if (Array.isArray(v)) { + return JSON.stringify(v); + } + return v === null || v === undefined ? null : String(v); +} + +async function readGeneration(q) { + const row = await q.get('SELECT Value FROM Config WHERE Name = ?', ['generation']); + return row ? Number(row.Value) : 0; +} + +/** Change the generation (in a write transaction): every process reloads */ +async function bumpGeneration(q) { + const g = await readGeneration(q); + const n = g + 1; + const r = await q.run('UPDATE Config SET Value = ? WHERE Name = ?', [String(n), 'generation']); + if (!r.changes) { + await q.run(q.dialect.insertIgnore('Config', ['Name', 'Value']) + '(?, ?)', ['generation', String(n)]); + } + return n; +} + +/** + * Seed settings that aren't in the database yet, and the types (master only). + * @param {Object} db + * @param {Object} initial - name -> value (from config.json) + * @param {string[]} resourceTypes + * @param {Object} [typeSettings] - type -> settings, seeded for types not yet present + */ +async function seed(db, initial, resourceTypes, typeSettings = {}) { + await db.write(async (q) => { + let changed = false; + const rows = await q.all('SELECT Name FROM Config'); + const have = new Set(rows.map(r => r.Name)); + for (const [name, value] of Object.entries(initial || {})) { + if (!(name in ENDPOINT_DEFAULTS)) { + throw new Error(`Unknown endpoint setting '${name}' (known: ${Object.keys(ENDPOINT_DEFAULTS).join(', ')})`); + } + if (!have.has(name)) { + await q.run('INSERT INTO Config (Name, Value) VALUES (?, ?)', [name, valueText(value)]); + changed = true; + } + } + const types = await q.all('SELECT Name FROM Types'); + const haveTypes = new Set(types.map(r => r.Name)); + for (const t of resourceTypes) { + if (!haveTypes.has(t)) { + await q.run(q.dialect.insertIgnore('Types', ['Name', 'Supported', 'Settings']) + '(?, ?, ?)', + [t, 1, typeSettings[t] ? JSON.stringify(typeSettings[t]) : null]); + changed = true; + } + } + if (changed || !have.has('generation')) { + await bumpGeneration(q); + } + }); +} + +/** + * Load the settings. + * @returns {Promise<{generation: number, endpoint: Object, types: Map, typeKeys: Map}>} + */ +async function load(db) { + return db.read(async (q) => { + const rows = await q.all('SELECT Name, Value FROM Config'); + const map = new Map(rows.map(r => [r.Name, r.Value])); + const endpoint = {}; + for (const name of Object.keys(ENDPOINT_DEFAULTS)) { + endpoint[name] = map.has(name) ? parseValue(name, map.get(name)) : ENDPOINT_DEFAULTS[name]; + } + const types = new Map(); + const typeKeys = new Map(); + for (const r of await q.all('SELECT TypeKey, Name, Supported, Settings FROM Types')) { + typeKeys.set(r.Name, Number(r.TypeKey)); + let s = {}; + if (r.Settings) { + try { + s = JSON.parse(r.Settings); + } catch (e) { + s = {}; + } + } + types.set(r.Name, { ...TYPE_DEFAULTS, ...s, supported: !!Number(r.Supported) }); + } + return { generation: map.has('generation') ? Number(map.get('generation')) : 0, endpoint, types, typeKeys }; + }); +} + +/** + * Change endpoint settings (in a write transaction of its own). + * @param {Object} db + * @param {Object} values - name -> value + */ +async function set(db, values) { + await db.write(async (q) => { + for (const [name, value] of Object.entries(values)) { + if (!(name in ENDPOINT_DEFAULTS)) { + throw new Error(`Unknown endpoint setting '${name}'`); + } + const r = await q.run('UPDATE Config SET Value = ? WHERE Name = ?', [valueText(value), name]); + if (!r.changes) { + await q.run('INSERT INTO Config (Name, Value) VALUES (?, ?)', [name, valueText(value)]); + } + } + await bumpGeneration(q); + }); +} + +/** + * Change a type's settings. + * @param {Object} db + * @param {string} type + * @param {Object} values - merged over the type's current settings; supported (boolean) too + */ +async function setType(db, type, values) { + await db.write(async (q) => { + const row = await q.get('SELECT Supported, Settings FROM Types WHERE Name = ?', [type]); + if (!row) { + throw new Error(`Unknown type ${type}`); + } + const current = row.Settings ? JSON.parse(row.Settings) : {}; + const { supported, ...rest } = values; + const next = { ...current, ...rest }; + await q.run('UPDATE Types SET Supported = ?, Settings = ? WHERE Name = ?', + [supported === undefined ? row.Supported : (supported ? 1 : 0), JSON.stringify(next), type]); + await bumpGeneration(q); + }); +} + +/** Whether a type allows an interaction (by its settings) */ +function typeAllows(typeSettings, interaction) { + if (!typeSettings || !typeSettings.supported) { + return false; + } + return !Array.isArray(typeSettings.interactions) || typeSettings.interactions.includes(interaction); +} + +module.exports = { ENDPOINT_DEFAULTS, TYPE_DEFAULTS, INTERACTIONS, seed, load, set, setType, readGeneration, bumpGeneration, typeAllows }; diff --git a/rest/format.js b/rest/format.js new file mode 100644 index 00000000..561faf11 --- /dev/null +++ b/rest/format.js @@ -0,0 +1,101 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Formats: the one place they are handled. JSON only for now; XML is refused with 415 (a + * body) or 406 (a response), and can be added here later. + * + * @module rest/format + */ + +const { FhirError, badRequest } = require('./library/errors'); + +const FHIR_JSON = 'application/fhir+json'; +const JSON_TYPES = new Set(['json', 'application/json', 'application/fhir+json', 'fhir+json', 'application/json+fhir', 'text/json']); +const XML_TYPES = new Set(['xml', 'application/xml', 'application/fhir+xml', 'fhir+xml', 'application/xml+fhir', 'text/xml']); +const PATCH_JSON = 'application/json-patch+json'; + +/** + * The response format the client wants: 'json', or throws 406. + * @param {Object} req + */ +function responseFormat(req) { + const f = typeof req.query._format === 'string' ? req.query._format.trim().toLowerCase().replace(/ /g, '+') : ''; + if (f) { + const base = f.split(';')[0].trim(); + if (JSON_TYPES.has(base)) { + return 'json'; + } + if (XML_TYPES.has(base)) { + throw new FhirError(406, 'not-supported', 'This server only returns JSON (_format=json)'); + } + if (base === 'html' || base === 'text/html') { + return 'json'; + } + throw new FhirError(406, 'not-supported', `Unknown _format '${f}'`); + } + const accept = String(req.get('Accept') || '').toLowerCase(); + if (!accept) { + return 'json'; + } + const types = accept.split(',').map(p => p.split(';')[0].trim()).filter(t => t); + if (types.some(t => JSON_TYPES.has(t) || t === '*/*' || t === 'application/*' || t === 'text/html' || t === 'text/*')) { + return 'json'; + } + if (types.some(t => XML_TYPES.has(t))) { + throw new FhirError(406, 'not-supported', 'This server only returns JSON (Accept: application/fhir+json)'); + } + return 'json'; +} + +/** + * The request body as an object: JSON (the server's parsers leave fhir+json as a Buffer). + * @param {Object} req + * @param {Object} [options] - { patch: true } accepts application/json-patch+json + */ +function requestBody(req, options = {}) { + const ct = String(req.get('Content-Type') || '').split(';')[0].trim().toLowerCase(); + if (XML_TYPES.has(ct)) { + throw new FhirError(415, 'not-supported', 'This server only accepts JSON (application/fhir+json)'); + } + if (ct && !JSON_TYPES.has(ct) && !(options.patch && ct === PATCH_JSON) && ct !== 'application/x-www-form-urlencoded') { + throw new FhirError(415, 'not-supported', `Content-Type ${ct} is not supported: use application/fhir+json`); + } + let b = req.body; + if (Buffer.isBuffer(b)) { + if (b.length === 0) { + return null; + } + try { + b = JSON.parse(b.toString('utf8')); + } catch (e) { + throw badRequest(`The body is not valid JSON: ${e.message}`); + } + } else if (typeof b === 'string') { + if (!b.trim()) { + return null; + } + try { + b = JSON.parse(b); + } catch (e) { + throw badRequest(`The body is not valid JSON: ${e.message}`); + } + } else if (b && typeof b === 'object' && Object.keys(b).length === 0 && !ct) { + return null; + } + return b === undefined ? null : b; +} + +/** Whether the client wants indented output */ +function pretty(req) { + return req.query._pretty === 'true'; +} + +function serialise(req, body) { + return pretty(req) ? JSON.stringify(body, null, 2) : JSON.stringify(body); +} + +module.exports = { responseFormat, requestBody, serialise, FHIR_JSON, PATCH_JSON, JSON_TYPES, XML_TYPES }; diff --git a/rest/html/rest-template.html b/rest/html/rest-template.html new file mode 100644 index 00000000..e652b25f --- /dev/null +++ b/rest/html/rest-template.html @@ -0,0 +1,101 @@ + + + + + FHIRsmith: [%title%] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+ +

FHIRsmith Logo [%title%]

+ +[%content%] + +
+ +
+
+
+
+ + + + + + + + + diff --git a/rest/indexing/definitions.js b/rest/indexing/definitions.js new file mode 100644 index 00000000..8b2c176b --- /dev/null +++ b/rest/indexing/definitions.js @@ -0,0 +1,491 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * What an endpoint indexes and searches by: the SearchParameters, CompartmentDefinitions + * and resource types of its FHIR version, from the core package and any others it lists, + * plus custom SearchParameters stored on the endpoint. + * + * Search parameter expressions are compiled once, with fhirpath.js and the model for the + * endpoint's version. fhirpath.js has no resolve(); the core search parameters only use it + * as `where(resolve() is X)`, which needs just the target's type, so a resolve() is + * supplied that returns a stub of the right type: from the reference (Patient/123, or the + * type in an absolute URL), from Reference.type, or the contained resource itself for #id. + * + * Loading a core package's StructureDefinitions takes time, so what is derived from the + * packages is kept in the cache folder, by package list (deriveDefinitions / cache). + * + * @module rest/indexing/definitions + */ + +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const fhirpath = require('fhirpath'); + +// the parameters the search handles itself, not through the index tables +const SPECIAL_PARAMS = new Set(['_id', '_lastUpdated', '_tag', '_profile', '_security', '_text', '_content', '_list', + '_has', '_type', '_query', '_filter', '_sort', '_count', '_include', '_revinclude', '_summary', '_elements', + '_contained', '_containedType', '_total', '_format', '_pretty', '_offset', '_getpages']); + +// the shape of what deriveDefinitions makes: a change makes the cached copies be derived again +const DERIVED_FORMAT = 2; + +const INDEXED_TYPES = new Set(['string', 'token', 'date', 'number', 'quantity', 'reference', 'uri', 'composite']); + +const CORE_PACKAGES = { + '3.0': 'hl7.fhir.r3.core#3.0.2', + '4.0': 'hl7.fhir.r4.core#4.0.1', + '4.3': 'hl7.fhir.r4b.core#4.3.0', + '5.0': 'hl7.fhir.r5.core#5.0.0' +}; + +/** The major.minor of a FHIR version ('4.0.1' -> '4.0') */ +function majorMinor(v) { + const m = /^(\d+)\.(\d+)/.exec(String(v || '')); + return m ? `${m[1]}.${m[2]}` : null; +} + +function modelFor(fhirVersion) { + const mm = majorMinor(fhirVersion); + if (mm === '3.0') { + return require('fhirpath/fhir-context/stu3'); + } + if (mm === '4.0' || mm === '4.3') { + return require('fhirpath/fhir-context/r4'); + } + return require('fhirpath/fhir-context/r5'); +} + +function corePackage(fhirVersion) { + const p = CORE_PACKAGES[majorMinor(fhirVersion)]; + if (!p) { + throw new Error(`No core package known for FHIR version ${fhirVersion}`); + } + return p; +} + +const TYPE_SEGMENT = /^[A-Z][A-Za-z]{0,63}$/; +const ID_SEGMENT = /^[A-Za-z0-9\-.]{1,64}$/; + +/** + * The resource type a reference string names ([base/]Type/id[/_history/vid]), or null. By its + * last path segments, not a regular expression over the whole string: the string is from a + * resource, and a pattern that can start anywhere is slow on a long one. + * @param {string} ref + */ +function referenceType(ref) { + if (typeof ref !== 'string' || !ref || ref.length > 4096) { + return null; + } + const parts = ref.split('/'); + let n = parts.length; + if (n >= 4 && parts[n - 2] === '_history' && ID_SEGMENT.test(parts[n - 1])) { + n -= 2; + } + if (n >= 2 && TYPE_SEGMENT.test(parts[n - 2]) && ID_SEGMENT.test(parts[n - 1])) { + return parts[n - 2]; + } + return null; +} + +/** + * The fhirpath.js options for indexing: typed results, and resolve(). + * @param {Object} model + */ +function fhirpathOptions(model) { + // fhirpath.js doesn't export ResourceNode, but every typed result is one + const ResourceNode = fhirpath.evaluate({ resourceType: 'Patient' }, 'Patient', null, model, { resolveInternalTypes: false })[0].constructor; + const resolve = { + fn: function (inputs) { + const out = []; + for (const input of inputs) { + const d = input instanceof ResourceNode ? input.data : input; + let target = null; + if (typeof d === 'string') { + const t = referenceType(d); + target = t ? { resourceType: t } : null; + } else if (d && typeof d === 'object') { + if (typeof d.reference === 'string' && d.reference.startsWith('#')) { + // a contained resource: the resource itself + const root = rootOf(input); + const id = d.reference.substring(1); + target = (root && Array.isArray(root.contained) && root.contained.find(c => c && c.id === id)) || null; + } else { + const t = d.type || referenceType(d.reference); + target = t ? { resourceType: t } : null; + } + } + if (target && target.resourceType) { + out.push(ResourceNode.makeResNode(this, target, null, target.resourceType, null, target.resourceType)); + } + } + return out; + } + }; + // hasExtension(url), which fhirpath.js doesn't have (QuestionnaireResponse's item-subject) + const hasExtension = { + fn: function (inputs, url) { + const want = Array.isArray(url) ? url[0] : url; + return inputs.map(input => { + const d = input instanceof ResourceNode ? input.data : input; + return !!(d && typeof d === 'object' && Array.isArray(d.extension) && d.extension.some(e => e && e.url === want)); + }); + }, + arity: { 1: ['String'] } + }; + return { ResourceNode, options: { resolveInternalTypes: false, userInvocationTable: { resolve, hasExtension } } }; +} + +/** + * An expression as fhirpath.js evaluates it. The specification's search parameters use + * "x as T" on paths that can repeat (Observation.component.value as Quantity), which + * fhirpath.js refuses when there is more than one value: x.ofType(T) means the same there. + * @param {string} expression + */ +function forEvaluation(expression) { + return String(expression).replace(/([A-Za-z%][A-Za-z0-9_.]*)\s+as\s+([A-Za-z][A-Za-z0-9]*)/g, '$1.ofType($2)'); +} + +/** + * Split an expression at its top-level | (outside brackets and strings). + * @param {string} expression + * @returns {string[]} + */ +function splitUnion(expression) { + const out = []; + let depth = 0; + let quote = null; + let cur = ''; + for (let i = 0; i < expression.length; i++) { + const c = expression[i]; + if (quote) { + cur += c; + if (c === '\\' && i + 1 < expression.length) { + cur += expression[++i]; + } else if (c === quote) { + quote = null; + } + } else if (c === '\'' || c === '`' || c === '"') { + quote = c; + cur += c; + } else if (c === '(' || c === '[' || c === '{') { + depth++; + cur += c; + } else if (c === ')' || c === ']' || c === '}') { + depth--; + cur += c; + } else if (c === '|' && depth === 0) { + out.push(cur.trim()); + cur = ''; + } else { + cur += c; + } + } + out.push(cur.trim()); + return out.filter(x => x); +} + +function rootOf(node) { + let n = node; + while (n && n.parentResNode) { + n = n.parentResNode; + } + return n ? n.data : null; +} + +/** + * Read the resources of the types wanted from a package folder. + * @param {string} folder - the package's folder (the one holding package/) + * @param {Set} types - resourceType values to read + */ +function readPackage(folder, types) { + const dir = fs.existsSync(path.join(folder, 'package')) ? path.join(folder, 'package') : folder; + const out = []; + let files; + const indexFile = path.join(dir, '.index.json'); + if (fs.existsSync(indexFile)) { + const index = JSON.parse(fs.readFileSync(indexFile, 'utf8')); + files = (index.files || []).filter(f => types.has(f.resourceType)).map(f => f.filename); + } else { + files = fs.readdirSync(dir).filter(f => f.endsWith('.json') && f !== 'package.json'); + } + for (const f of files) { + try { + const r = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); + if (r && types.has(r.resourceType)) { + out.push(r); + } + } catch (e) { + // not a resource: skip it + } + } + return out; +} + +/** + * The definitions an endpoint needs, from its packages, in a plain form that can be cached: + * { fhirVersion, resourceTypes, searchParameters, compartments, summary, mandatory }. + * @param {string[]} folders - package folders, core first + * @param {string} fhirVersion + */ +function deriveDefinitions(folders, fhirVersion) { + const resourceTypes = []; + const searchParameters = []; + const compartments = []; + const summary = {}; + const mandatory = {}; + for (const folder of folders) { + for (const r of readPackage(folder, new Set(['SearchParameter', 'CompartmentDefinition', 'StructureDefinition']))) { + if (r.resourceType === 'SearchParameter') { + searchParameters.push(slimSearchParameter(r)); + } else if (r.resourceType === 'CompartmentDefinition') { + compartments.push({ code: r.code, url: r.url, resource: (r.resource || []).map(x => ({ code: x.code, param: x.param || [] })) }); + } else if (r.kind === 'resource' && r.derivation !== 'constraint' && !r.abstract && r.type) { + if (!resourceTypes.includes(r.type)) { + resourceTypes.push(r.type); + } + const elements = (r.snapshot && r.snapshot.element) || []; + summary[r.type] = []; + mandatory[r.type] = []; + for (const e of elements) { + const parts = String(e.path || '').split('.'); + if (parts.length === 2) { + const name = parts[1].replace('[x]', ''); + if (e.isSummary) { + summary[r.type].push(name); + } + if (e.min > 0) { + mandatory[r.type].push(name); + } + } + } + } + } + } + return { fhirVersion, resourceTypes: resourceTypes.sort(), searchParameters, compartments, summary, mandatory }; +} + +function slimSearchParameter(r) { + return { + url: r.url, code: r.code, type: r.type, expression: r.expression || null, base: r.base || [], + // for the search forms (web.js) + description: r.description ? String(r.description).substring(0, 3000) : null, + target: r.target || [], component: (r.component || []).map(c => ({ definition: c.definition, expression: c.expression })) + }; +} + +/** + * Get the definitions for packages, from the cache folder when they have been derived + * before, else from the packages (fetched through the package manager). + * @param {Object} options + * @param {string} options.fhirVersion + * @param {string[]} options.packages - 'id#version' + * @param {Object} options.packageManager - library/package-manager PackageManager + * @param {string} options.cacheFolder + */ +async function loadDerived(options) { + const key = crypto.createHash('sha256').update(JSON.stringify([DERIVED_FORMAT, options.fhirVersion, options.packages])).digest('hex').substring(0, 16); + const cacheFile = path.join(options.cacheFolder, `rest-definitions-${key}.json`); + if (fs.existsSync(cacheFile)) { + try { + return JSON.parse(fs.readFileSync(cacheFile, 'utf8')); + } catch (e) { + // a broken cache file: derive again + } + } + const folders = []; + for (const p of options.packages) { + const [id, version] = p.split('#'); + const name = await options.packageManager.fetch(id, version); + folders.push(path.isAbsolute(name) ? name : path.join(options.packageManager.cacheFolder, name)); + } + const derived = deriveDefinitions(folders, options.fhirVersion); + fs.mkdirSync(options.cacheFolder, { recursive: true }); + const tmp = cacheFile + '.' + process.pid + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(derived)); + fs.renameSync(tmp, cacheFile); + return derived; +} + +function hashOf(sp) { + return crypto.createHash('sha256').update(JSON.stringify([sp.type, [...(sp.base || [])].sort(), sp.expression, + sp.component || [], [...(sp.target || [])].sort()])).digest('hex').substring(0, 32); +} + +/** + * An endpoint's definitions, ready to use: search parameters by type and code with their + * compiled expressions, compartments, resource types, summary and mandatory elements. + */ +class Definitions { + /** + * @param {Object} derived - from deriveDefinitions / loadDerived (or a test fixture) + * @param {Object[]} [custom] - custom SearchParameter resources stored on the endpoint + * @param {function(string, string)} [log] - (level, message) + */ + constructor(derived, custom = [], log = () => {}) { + this.fhirVersion = derived.fhirVersion; + this.model = modelFor(derived.fhirVersion); + const fp = fhirpathOptions(this.model); + this.ResourceNode = fp.ResourceNode; + this.fhirpathOptions = fp.options; + this.resourceTypes = new Set(derived.resourceTypes); + this.summary = new Map(Object.entries(derived.summary || {}).map(([k, v]) => [k, new Set(v)])); + this.mandatory = new Map(Object.entries(derived.mandatory || {}).map(([k, v]) => [k, new Set(v)])); + this.byUrl = new Map(); + this.byType = new Map(); // type -> Map(code -> def) + this.problems = []; + this.compiled = new Map(); + for (const sp of [...derived.searchParameters, ...custom.map(slimSearchParameter)]) { + this.add(sp, log); + } + // compartments: compType -> Map(resourceType -> [param codes]) + this.compartments = new Map(); + const chosen = new Map(); + for (const c of derived.compartments || []) { + // a package can carry examples with the same code (R4 has one for Device): the + // specification's own definition wins + const canonical = c.url === `http://hl7.org/fhir/CompartmentDefinition/${String(c.code).toLowerCase()}`; + const prior = chosen.get(c.code); + if (!prior || (canonical && !prior.canonical)) { + chosen.set(c.code, { canonical, c }); + } + } + for (const { c } of chosen.values()) { + const m = new Map(); + for (const r of c.resource) { + if (r.param && r.param.length) { + m.set(r.code, r.param); + } + } + this.compartments.set(c.code, m); + } + } + + add(sp, log) { + if (!sp || !sp.url || !sp.code || !INDEXED_TYPES.has(sp.type) || SPECIAL_PARAMS.has(sp.code)) { + return; + } + if (!sp.expression) { + return; + } + if (/resolve\(\)/.test(sp.expression.replace(/\.where\(\s*resolve\(\)\s+is\s+[A-Za-z]+\s*\)/g, '').replace(/resolve\(\)\s+is\s+[A-Za-z]+/g, ''))) { + const msg = `Search parameter ${sp.url} uses resolve() for more than the target's type, which can't be indexed: not used`; + this.problems.push(msg); + log('warn', msg); + return; + } + const def = { + url: sp.url, code: sp.code, type: sp.type, expression: sp.expression, base: sp.base || [], target: sp.target || [], description: sp.description || null, + component: sp.component || [], hash: hashOf(sp), key: null, fn: null + }; + try { + // each branch of a top-level union on its own: fhirpath.js's union compares the values + // (to drop duplicates), which fails on some (a Quantity with a comparator); the indexer + // drops duplicate rows itself + const parts = splitUnion(forEvaluation(sp.expression)).map(x => fhirpath.compile(x, this.model, this.fhirpathOptions)); + def.fn = parts.length === 1 ? parts[0] : (r, env) => parts.flatMap(f => f(r, env)); + } catch (e) { + const msg = `Search parameter ${sp.url}: the expression doesn't compile (${e.message.split('\n')[0]}): not used`; + this.problems.push(msg); + log('warn', msg); + return; + } + // a later definition (an IG's) replaces an earlier one (the core's) with the same url + this.byUrl.set(def.url, def); + for (const base of def.base) { + if (!this.byType.has(base)) { + this.byType.set(base, new Map()); + } + this.byType.get(base).set(def.code, def); + } + } + + /** + * The search parameters for a resource type (its own, and Resource's and DomainResource's). + * @param {string} type + * @returns {Map} code -> definition + */ + forType(type) { + const out = new Map(); + for (const base of ['Resource', 'DomainResource', type]) { + const m = this.byType.get(base); + if (m) { + for (const [code, def] of m) { + out.set(code, def); + } + } + } + return out; + } + + /** A search parameter by type and code, or null */ + param(type, code) { + return this.forType(type).get(code) || null; + } + + /** + * Evaluate an expression relative to a node (a composite's components). + * @param {Object} node - a ResourceNode from an earlier evaluation + * @param {string} expression + */ + evaluateRelative(node, expression, resource) { + const base = node.path || (node.getTypeInfo && node.getTypeInfo().name); + const key = base + '|' + expression; + let fn = this.compiled.get(key); + if (!fn) { + fn = fhirpath.compile({ base, expression: forEvaluation(expression) }, this.model, this.fhirpathOptions); + this.compiled.set(key, fn); + } + // a component's expression can refer to the whole resource (%resource) + return fn(node.data, resource ? { resource } : {}); + } + + /** + * Give each definition its key from the SearchParams table. The master adds rows for new + * definitions and marks changed ones for reindexing; a worker only reads. + * @param {Object} db + * @param {boolean} master + * @param {boolean} hasResources - whether the endpoint has resources yet (if so, a new or + * changed definition needs a reindex) + * @returns {Promise<{added: number, changed: number}>} + */ + async sync(db, master, hasResources) { + let added = 0; + let changed = 0; + if (master) { + await db.write(async (q) => { + const rows = await q.all('SELECT ParamKey, Url, Hash FROM SearchParams'); + const byUrl = new Map(rows.map(r => [r.Url, r])); + for (const def of this.byUrl.values()) { + const row = byUrl.get(def.url); + if (!row) { + await q.run('INSERT INTO SearchParams (Url, Code, Type, Bases, Expression, Hash, Reindex) VALUES (?, ?, ?, ?, ?, ?, ?)', + [def.url, def.code, def.type, JSON.stringify(def.base), def.expression, def.hash, hasResources ? 1 : 0]); + added++; + } else if (row.Hash !== def.hash) { + await q.run('UPDATE SearchParams SET Code = ?, Type = ?, Bases = ?, Expression = ?, Hash = ?, Reindex = 1 WHERE ParamKey = ?', + [def.code, def.type, JSON.stringify(def.base), def.expression, def.hash, row.ParamKey]); + changed++; + } + } + }); + } + const rows = await db.read(q => q.all('SELECT ParamKey, Url, Reindex FROM SearchParams')); + const keys = new Map(rows.map(r => [r.Url, r])); + this.reindexing = new Set(); + for (const def of this.byUrl.values()) { + const row = keys.get(def.url); + def.key = row ? Number(row.ParamKey) : null; + if (row && row.Reindex) { + this.reindexing.add(def.url); + } + } + return { added, changed }; + } +} + +module.exports = { forEvaluation, splitUnion, Definitions, deriveDefinitions, loadDerived, corePackage, majorMinor, referenceType, SPECIAL_PARAMS, modelFor }; diff --git a/rest/indexing/indexer.js b/rest/indexing/indexer.js new file mode 100644 index 00000000..14af33c5 --- /dev/null +++ b/rest/indexing/indexer.js @@ -0,0 +1,358 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Writes a resource's index rows, inside the write transaction that stores it: the index is + * never behind the data. + * + * For each search parameter on the resource's type, the expression is evaluated, the results + * turned into rows (values.js), systems turned into SpaceKeys, codes into ConceptKeys (for + * the closure table), local references into the target's ResourceKey, and compartment rows + * made from the compartment definitions. The old rows go first. + * + * @module rest/indexing/indexer + */ + +const { extractValues } = require('./values'); +const { INDEX_TABLES } = require('../database/schema'); +const { chunks } = require('../database/lookups'); +const { unprocessable } = require('../library/errors'); + +// the most rows one search parameter can add for one resource +const MAX_ROWS_PER_PARAM = 200; + +const COLUMNS = { + IndexStrings: ['Norm', 'Exact'], + IndexTokens: ['SpaceKey', 'Code', 'Implicit', 'ConceptKey', 'TextNorm', 'TypeSpaceKey', 'TypeCode'], + IndexDates: ['Lo', 'Hi'], + IndexNumbers: ['Lo', 'Hi', 'Value'], + IndexQuantities: ['Lo', 'Hi', 'Value', 'SpaceKey', 'Unit', 'CanonLo', 'CanonHi', 'CanonUnit'], + IndexReferences: ['TargetKey', 'TargetType', 'TargetId', 'TargetVersion', 'Url', 'UrlVersion', 'IdentSpaceKey', 'IdentValue'], + IndexUris: ['Value'] +}; + +function rowKey(r) { + const cols = COLUMNS[r.table]; + return r.table + '|' + r.Comp + '|' + r.GroupNo + '|' + cols.map(c => r[c] === undefined ? '' : r[c]).join('|') + + '|' + (r.system || '') + '|' + (r.targetType || '') + '|' + (r.targetId || ''); +} + +class Indexer { + /** + * @param {Object} options + * @param {import('./definitions').Definitions} options.definitions + * @param {import('../database/lookups').Lookups} options.lookups + * @param {Map} options.typeKeys - resource type -> TypeKey + * @param {string} [options.timeZone] - for dates without a zone (default: the server's) + * @param {string[]} [options.baseUrls] - URLs that are this endpoint (references to them are local) + * @param {boolean} [options.checkReferences] - refuse references to resources that don't exist + * @param {function(string, string)} [options.log] + */ + constructor(options) { + this.definitions = options.definitions; + this.lookups = options.lookups; + this.typeKeys = options.typeKeys; + this.ctx = { timeZone: options.timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone, baseUrls: options.baseUrls || [] }; + this.checkReferences = !!options.checkReferences; + this.log = options.log || (() => {}); + } + + /** + * The rows for a resource, without keys (no database). + * @param {Object} resource + * @returns {{rows: Object[], problems: string[]}} + */ + extract(resource) { + const rows = []; + const problems = []; + const type = resource.resourceType; + for (const def of this.definitions.forType(type).values()) { + if (def.key === null || def.key === undefined) { + continue; + } + let nodes; + try { + nodes = def.fn(resource); + } catch (e) { + problems.push(`${def.code}: ${e.message}`); + continue; + } + if (!nodes || nodes.length === 0) { + continue; + } + let out = []; + if (def.type === 'composite') { + out = this.compositeRows(def, nodes, problems, resource); + } else { + out = extractValues(def.type, nodes, this.ctx); + } + const seen = new Set(); + let n = 0; + for (const r of out) { + r.ParamKey = def.key; + r.code = def.code; + if (r.Comp === undefined) { + r.Comp = null; + r.GroupNo = null; + } + const k = rowKey(r); + if (seen.has(k)) { + continue; + } + seen.add(k); + if (++n > MAX_ROWS_PER_PARAM) { + problems.push(`${def.code}: more than ${MAX_ROWS_PER_PARAM} values; the rest are not indexed`); + break; + } + rows.push(r); + } + } + return { rows, problems }; + } + + compositeRows(def, nodes, problems, resource) { + const out = []; + let g = 0; + for (const node of nodes) { + g++; + let i = 0; + for (const comp of def.component) { + const cdef = this.definitions.byUrl.get(comp.definition); + if (!cdef) { + problems.push(`${def.code}: component ${comp.definition} is not known`); + break; + } + let cnodes; + try { + cnodes = this.definitions.evaluateRelative(node, comp.expression, resource); + } catch (e) { + problems.push(`${def.code}: component ${comp.expression}: ${e.message}`); + break; + } + for (const r of extractValues(cdef.type, cnodes, this.ctx)) { + r.Comp = i; + r.GroupNo = g; + out.push(r); + } + i++; + } + } + return out; + } + + /** + * Index a resource, replacing its old rows. + * @param {Object} q - a query object in a write transaction + * @param {Object} entry + * @param {number} entry.resourceKey + * @param {Object} entry.resource + * @param {Set} [entry.reserved] - "Type/id" of resources this transaction is + * creating (references to them are fine) + * @param {boolean} [entry.deferChecks] - don't check references now: return them + * @returns {Promise<{unresolved: string[]}>} local references whose target doesn't exist + * (only when checks are deferred) + */ + async index(q, entry) { + const { resourceKey, resource } = entry; + await this.remove(q, resourceKey); + const { rows, problems } = this.extract(resource); + for (const p of problems) { + this.log('debug', `Indexing ${resource.resourceType}/${resource.id}: ${p}`); + } + + // systems + const systems = []; + for (const r of rows) { + if (r.system) { + systems.push(r.system); + } + if (r.typeSystem) { + systems.push(r.typeSystem); + } + if (r.identSystem) { + systems.push(r.identSystem); + } + } + const spaces = await this.lookups.spaceKeys(q, systems); + for (const r of rows) { + if (r.table === 'IndexTokens' || r.table === 'IndexQuantities') { + r.SpaceKey = r.system ? spaces.get(r.system) : null; + } + if (r.table === 'IndexTokens') { + r.TypeSpaceKey = r.typeSystem ? spaces.get(r.typeSystem) : null; + } + if (r.table === 'IndexReferences') { + r.IdentSpaceKey = r.identSystem ? spaces.get(r.identSystem) : null; + } + } + + // concepts + const pairs = rows.filter(r => r.table === 'IndexTokens' && r.concept && r.SpaceKey).map(r => [r.SpaceKey, r.Code]); + if (pairs.length) { + const concepts = await this.lookups.conceptKeys(q, pairs); + for (const r of rows) { + if (r.table === 'IndexTokens') { + r.ConceptKey = r.concept && r.SpaceKey ? (concepts.get(r.SpaceKey + '|' + r.Code) || null) : null; + } + } + } + + // local references + const unresolved = await this.resolveReferences(q, rows, entry); + + // insert + const byTable = new Map(); + for (const r of rows) { + if (!byTable.has(r.table)) { + byTable.set(r.table, []); + } + byTable.get(r.table).push(r); + } + for (const [table, list] of byTable) { + const cols = ['ResourceKey', 'ParamKey', 'GroupNo', 'Comp', ...COLUMNS[table]]; + const per = Math.max(1, Math.min(500, Math.floor(q.dialect.maxParams / cols.length))); + for (const c of chunks(list, per)) { + const args = []; + for (const r of c) { + args.push(resourceKey, r.ParamKey, r.GroupNo, r.Comp, ...COLUMNS[table].map(col => r[col] === undefined ? null : r[col])); + } + await q.run(`INSERT INTO ${table} (${cols.join(', ')}) VALUES ` + c.map(() => '(' + cols.map(() => '?').join(', ') + ')').join(', '), args); + } + } + + // compartments + const comps = this.compartmentRows(resource, rows, resourceKey); + if (comps.length) { + for (const c of chunks(comps, 500)) { + await q.run('INSERT INTO Compartments (ResourceKey, CompType, CompId, CompKey) VALUES ' + c.map(() => '(?, ?, ?, ?)').join(', '), + c.flatMap(x => [resourceKey, x.type, x.id, x.key])); + } + } + return { unresolved }; + } + + async resolveReferences(q, rows, entry) { + const refs = rows.filter(r => r.table === 'IndexReferences' && r.local && r.targetType && r.targetId); + const unresolved = new Set(); + if (refs.length === 0) { + return []; + } + const byType = new Map(); + for (const r of refs) { + if (!byType.has(r.targetType)) { + byType.set(r.targetType, new Set()); + } + byType.get(r.targetType).add(r.targetId); + } + const found = new Map(); // Type/id -> {key, deleted} + for (const [type, ids] of byType) { + const typeKey = this.typeKeys.get(type); + if (typeKey === undefined) { + for (const id of ids) { + unresolved.add(type + '/' + id); + } + continue; + } + for (const c of chunks([...ids])) { + const list = await q.all(`SELECT ResourceKey, Id, Deleted FROM Ids WHERE TypeKey = ? AND Id IN (${c.map(() => '?').join(', ')})`, [typeKey, ...c]); + for (const row of list) { + found.set(type + '/' + row.Id, { key: Number(row.ResourceKey), deleted: !!Number(row.Deleted) }); + } + } + } + const reserved = entry.reserved || new Set(); + const self = entry.resource.resourceType + '/' + entry.resource.id; + const versioned = []; + for (const r of refs) { + const k = r.targetType + '/' + r.targetId; + const f = found.get(k); + r.TargetType = r.targetType; + r.TargetId = r.targetId; + r.TargetKey = f ? f.key : null; + if ((!f || f.deleted) && !reserved.has(k) && k !== self) { + unresolved.add(k); + } else if (r.TargetVersion && k !== self) { + versioned.push({ r, k, f }); + } + } + // a reference to a version: the version must exist (it may be one a transaction writes + // later: with deferred checks, the transaction looks again at the end) + for (const { r, k, f } of versioned) { + const v = /^\d{1,9}$/.test(r.TargetVersion) && f + ? await q.get('SELECT 1 AS ok FROM Versions WHERE ResourceKey = ? AND VersionId = ?', [f.key, Number(r.TargetVersion)]) : null; + if (!v) { + unresolved.add(`${k}/_history/${r.TargetVersion}`); + } + } + for (const r of rows) { + if (r.table === 'IndexReferences' && !r.local) { + r.TargetType = null; + r.TargetId = null; + r.TargetKey = null; + } + } + if (this.checkReferences && unresolved.size && !entry.deferChecks) { + throw unprocessable(`The resource refers to resources that don't exist: ${[...unresolved].join(', ')}`); + } + return [...unresolved]; + } + + compartmentRows(resource, rows, resourceKey) { + const out = []; + const seen = new Set(); + const add = (type, id, key) => { + const k = type + '/' + id; + if (!seen.has(k)) { + seen.add(k); + out.push({ type, id, key }); + } + }; + const type = resource.resourceType; + for (const [compType, members] of this.definitions.compartments) { + if (compType === type) { + add(type, resource.id, resourceKey); + } + const params = members.get(type); + if (!params) { + continue; + } + for (const code of params) { + if (code === '{def}') { + continue; + } + for (const r of rows) { + if (r.table === 'IndexReferences' && r.code === code && r.TargetType === compType && r.TargetId) { + add(compType, r.TargetId, r.TargetKey); + } + } + } + } + return out; + } + + /** + * Remove a resource's index and compartment rows. + * @param {Object} q + * @param {number} resourceKey + */ + async remove(q, resourceKey) { + for (const t of INDEX_TABLES) { + await q.run(`DELETE FROM ${t} WHERE ResourceKey = ?`, [resourceKey]); + } + await q.run('DELETE FROM Compartments WHERE ResourceKey = ?', [resourceKey]); + } + + /** + * After a resource is created, fill in TargetKey in rows that already refer to it (by + * type and id) but were written before it existed (references, and compartments). + */ + async linkReferences(q, type, id, resourceKey) { + await q.run('UPDATE IndexReferences SET TargetKey = ? WHERE TargetKey IS NULL AND TargetType = ? AND TargetId = ?', [resourceKey, type, id]); + await q.run('UPDATE Compartments SET CompKey = ? WHERE CompKey IS NULL AND CompType = ? AND CompId = ?', [resourceKey, type, id]); + } +} + +module.exports = { Indexer, COLUMNS, MAX_ROWS_PER_PARAM }; diff --git a/rest/indexing/values.js b/rest/indexing/values.js new file mode 100644 index 00000000..95b305d7 --- /dev/null +++ b/rest/indexing/values.js @@ -0,0 +1,318 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Turn what a search parameter's expression returns into index values, by search parameter + * type. Each value is an object with the index table it goes in and its columns; systems + * are left as URIs (the indexer turns them into SpaceKeys). + * + * string string, markdown, HumanName (every part, and the text), Address (every part, + * and the text): normalised (lower case, accents removed) and as written + * token code, Coding, CodeableConcept, Identifier, ContactPoint, boolean, id, uri: + * system and code; display or text for :text; an Identifier's type for :of-type + * date date, dateTime, instant, Period, Timing: a [lo, hi) range + * number integer, decimal: a range from the value's precision + * quantity Quantity, Money, Duration, Age...: as number, with system and unit, and in + * canonical UCUM form where the unit is UCUM + * reference Reference, canonical, uri: the target type and id when it is a local reference, + * else the URL; a reference by identifier as system and value for :identifier + * uri uri, url, canonical: the value + * + * @module rest/indexing/values + */ + +const { dateRange, periodRange, numberRange } = require('../../library/fhir-search-values'); + +const MAX_NORM = 255; +const MAX_EXACT = 1024; +const MAX_CODE = 255; +const UCUM = 'http://unitsofmeasure.org'; + +let ucum = null; +function ucumUtils() { + if (ucum === null) { + try { + ucum = require('@lhncbc/ucum-lhc').UcumLhcUtils.getInstance(); + } catch (e) { + ucum = false; + } + } + return ucum; +} + +/** Lower case, with accents (combining marks) removed */ +function normalise(s) { + return String(s).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase(); +} + +function truncate(s, n) { + s = String(s); + return s.length > n ? s.substring(0, n) : s; +} + +/** + * The canonical (UCUM base unit) form of a quantity: the magnitude, and the unit as a + * stable string ("g", "g.m-1.s-2"), or null if the unit isn't UCUM. + * @param {string} code - a UCUM unit code + * @param {number} value + */ +function canonicalQuantity(code, value) { + const u = ucumUtils(); + if (!u || !code) { + return null; + } + try { + const r = u.convertToBaseUnits(code, value); + if (!r || r.status !== 'succeeded') { + return null; + } + const unit = Object.keys(r.unitToExp).sort().map(k => r.unitToExp[k] === 1 ? k : `${k}${r.unitToExp[k]}`).join('.'); + return { value: r.magnitude, unit: unit || '1' }; + } catch (e) { + return null; + } +} + +const RELATIVE_REF = /^([A-Z][A-Za-z]+)\/([A-Za-z0-9\-.]{1,64})(?:\/_history\/([A-Za-z0-9\-.]{1,64}))?$/; + +/** + * Parse a reference string: a local one (type, id, version), or a URL. + * @param {string} ref + * @param {string[]} baseUrls - this endpoint's base URLs: an absolute reference to one is local + * @returns {{local: boolean, type?: string, id?: string, version?: string, url?: string, urlVersion?: string}|null} + */ +function parseReference(ref, baseUrls = []) { + if (typeof ref !== 'string' || !ref || ref.startsWith('#')) { + return null; + } + let m = RELATIVE_REF.exec(ref); + if (m) { + return { local: true, type: m[1], id: m[2], version: m[3] || null }; + } + for (const base of baseUrls) { + if (base && ref.startsWith(base.endsWith('/') ? base : base + '/')) { + m = RELATIVE_REF.exec(ref.substring(base.length + (base.endsWith('/') ? 0 : 1))); + if (m) { + return { local: true, type: m[1], id: m[2], version: m[3] || null }; + } + } + } + const bar = ref.lastIndexOf('|'); + if (bar > 0 && !ref.startsWith('urn:')) { + return { local: false, url: ref.substring(0, bar), urlVersion: ref.substring(bar + 1) || null }; + } + return { local: false, url: ref, urlVersion: null }; +} + +function typeName(node) { + if (node && typeof node.getTypeInfo === 'function') { + const n = node.getTypeInfo().name; + return n.startsWith('System.') ? n.substring(7) : n; + } + return typeof node; +} + +function dataOf(node) { + return node && typeof node === 'object' && 'data' in node ? node.data : node; +} + +function stringValues(type, d, out) { + const add = (s) => { + if (s !== undefined && s !== null && s !== '') { + out.push({ table: 'IndexStrings', Norm: truncate(normalise(s), MAX_NORM), Exact: truncate(s, MAX_EXACT) }); + } + }; + if (d === null || d === undefined) { + return; + } + if (typeof d !== 'object') { + add(d); + return; + } + if (type === 'HumanName') { + add(d.text); + add(d.family); + for (const g of d.given || []) { + add(g); + } + for (const p of d.prefix || []) { + add(p); + } + for (const s of d.suffix || []) { + add(s); + } + } else if (type === 'Address') { + add(d.text); + for (const l of d.line || []) { + add(l); + } + for (const k of ['city', 'district', 'state', 'postalCode', 'country']) { + add(d[k]); + } + } else if (typeof d.value === 'string') { + add(d.value); + } +} + +function tokenValues(type, d, out) { + // concept: a code from a Coding or CodeableConcept, which goes in the closure table + const add = (system, code, text, implicit, typeSystem, typeCode, concept = false) => { + if (code === undefined || code === null || code === '') { + return; + } + out.push({ + table: 'IndexTokens', system: system || null, Code: truncate(String(code), MAX_CODE), Implicit: implicit ? 1 : 0, + TextNorm: text ? truncate(normalise(text), MAX_NORM) : null, typeSystem: typeSystem || null, TypeCode: typeCode || null, + concept: concept && !!system + }); + }; + if (d === null || d === undefined) { + return; + } + if (typeof d !== 'object') { + // code, string, id, boolean, uri...: no system; a code's system is implicit + add(null, typeof d === 'boolean' ? String(d) : d, null, type === 'code'); + return; + } + if (type === 'Coding') { + add(d.system, d.code, d.display, false, null, null, true); + } else if (type === 'CodeableConcept' || Array.isArray(d.coding)) { + const codings = d.coding || []; + for (const c of codings) { + add(c.system, c.code, d.text || c.display, false, null, null, true); + } + if (codings.length === 0 && d.text) { + // text only: nothing to match a code, but :text still finds it + out.push({ table: 'IndexTokens', system: null, Code: '', Implicit: 0, TextNorm: truncate(normalise(d.text), MAX_NORM), typeSystem: null, TypeCode: null }); + } + } else if (type === 'Identifier') { + const tc = d.type && d.type.coding && d.type.coding[0]; + add(d.system, d.value, d.type && d.type.text, false, tc && tc.system, tc && tc.code); + } else if (type === 'ContactPoint') { + add(d.system, d.value, null); + } else if (typeof d.value !== 'undefined' && typeof d.value !== 'object') { + add(d.system, d.value, null); + } else if (typeof d.code === 'string') { + add(d.system, d.code, d.display); + } +} + +function dateValues(type, d, out, ctx) { + if (d === null || d === undefined) { + return; + } + let range = null; + if (typeof d === 'string') { + range = dateRange(d, ctx.timeZone); + } else if (type === 'Period' || (d.start !== undefined || d.end !== undefined)) { + range = periodRange(d, ctx.timeZone); + } else if (type === 'Timing' || d.event || d.repeat) { + const ranges = (d.event || []).map(e => dateRange(e, ctx.timeZone)).filter(r => r); + if (ranges.length) { + range = { lo: Math.min(...ranges.map(r => r.lo)), hi: Math.max(...ranges.map(r => r.hi)) }; + } else if (d.repeat && d.repeat.boundsPeriod) { + range = periodRange(d.repeat.boundsPeriod, ctx.timeZone); + } + } + if (range) { + out.push({ table: 'IndexDates', Lo: range.lo, Hi: range.hi }); + } +} + +function numberValues(type, d, out) { + const v = d && typeof d === 'object' ? d.value : d; + if (v === undefined || v === null) { + return; + } + const r = numberRange(v); + if (r) { + out.push({ table: 'IndexNumbers', Lo: r.lo, Hi: r.hi, Value: r.value }); + } +} + +function quantityValues(type, d, out) { + if (!d || typeof d !== 'object' || d.value === undefined || d.value === null) { + return; + } + const r = numberRange(d.value); + if (!r) { + return; + } + const row = { + table: 'IndexQuantities', Lo: r.lo, Hi: r.hi, Value: r.value, system: d.system || (type === 'Money' ? 'urn:iso:std:iso:4217' : null), + Unit: d.code || d.currency || d.unit || null, CanonLo: null, CanonHi: null, CanonUnit: null + }; + if (d.system === UCUM && d.code) { + const lo = canonicalQuantity(d.code, r.lo); + const hi = canonicalQuantity(d.code, r.hi); + if (lo && hi) { + row.CanonLo = Math.min(lo.value, hi.value); + row.CanonHi = Math.max(lo.value, hi.value); + row.CanonUnit = lo.unit; + } + } + out.push(row); +} + +function referenceValues(type, d, out, ctx) { + if (d === null || d === undefined) { + return; + } + const push = (p, ident) => { + out.push({ + table: 'IndexReferences', local: !!(p && p.local), targetType: p && p.local ? p.type : null, targetId: p && p.local ? p.id : null, + TargetVersion: p && p.local ? p.version : null, Url: p && !p.local ? truncate(p.url, 512) : null, UrlVersion: p && !p.local ? p.urlVersion : null, + identSystem: ident ? ident.system || null : null, IdentValue: ident && ident.value ? truncate(ident.value, MAX_CODE) : null + }); + }; + if (typeof d === 'string') { + const p = parseReference(d, ctx.baseUrls); + if (p) { + push(p, null); + } + return; + } + if (typeof d === 'object') { + const p = typeof d.reference === 'string' ? parseReference(d.reference, ctx.baseUrls) : null; + const ident = d.identifier && d.identifier.value ? d.identifier : null; + if (p || ident) { + push(p, ident); + } + } +} + +function uriValues(type, d, out) { + if (typeof d === 'string' && d) { + out.push({ table: 'IndexUris', Value: truncate(d, 512) }); + } +} + +/** + * The index values for what an expression returned. + * @param {string} spType - the search parameter's type + * @param {Object[]} nodes - fhirpath.js results (ResourceNodes) + * @param {Object} ctx - { timeZone, baseUrls } + * @returns {Object[]} + */ +function extractValues(spType, nodes, ctx) { + const out = []; + for (const node of nodes) { + const type = typeName(node); + const d = dataOf(node); + switch (spType) { + case 'string': stringValues(type, d, out); break; + case 'token': tokenValues(type, d, out); break; + case 'date': dateValues(type, d, out, ctx); break; + case 'number': numberValues(type, d, out); break; + case 'quantity': quantityValues(type, d, out); break; + case 'reference': referenceValues(type, d, out, ctx); break; + case 'uri': uriValues(type, d, out); break; + } + } + return out; +} + +module.exports = { extractValues, normalise, parseReference, canonicalQuantity, truncate, MAX_NORM, MAX_EXACT, UCUM }; diff --git a/rest/interactions/bundle.js b/rest/interactions/bundle.js new file mode 100644 index 00000000..56cecd38 --- /dev/null +++ b/rest/interactions/bundle.js @@ -0,0 +1,689 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * batch and transaction. + * + * A batch runs each entry on its own (its own transaction); one failure doesn't stop the + * others. + * + * A transaction runs every entry in one database transaction: see the notes on transaction() + * below for how it is planned and run. + * + * @module rest/interactions/bundle + */ + +const http = require('http'); +const { FhirError, badRequest, preconditionFailed, unprocessable, notFound } = require('../library/errors'); +const { fromEntry, parseQuery, preferReturn } = require('../request'); +const access = require('../access'); +const crud = require('./crud'); + +const ORDER = { DELETE: 0, POST: 1, PUT: 2, PATCH: 2, GET: 3, HEAD: 3 }; + +function statusText(status) { + return `${status} ${http.STATUS_CODES[status] || ''}`.trim(); +} + +/** The response entry for a result */ +function responseEntry(ep, freq, result) { + const response = { status: statusText(result.status) }; + const h = result.headers || {}; + if (result.location) { + response.location = result.location; + } + if (h.ETag) { + response.etag = h.ETag; + } + if (h['Last-Modified']) { + response.lastModified = new Date(h['Last-Modified']).toISOString(); + } + const entry = {}; + if (result.outcome) { + response.outcome = { resourceType: 'OperationOutcome', issue: [result.outcome] }; + } + if (result.resource) { + const pr = preferReturn(freq); + if (!result.write || pr === 'representation' || (!pr && ep.bundleReturnsResources)) { + entry.resource = result.resource; + if (result.write && result.location) { + entry.fullUrl = `${freq.base}/${result.location.split('/_history/')[0]}`; + } + } + } + entry.response = response; + return entry; +} + +function errorEntry(err) { + const status = err instanceof FhirError ? err.status : 500; + const outcome = err instanceof FhirError ? err.outcome() + : { resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'exception', diagnostics: 'Internal error' }] }; + return { response: { status: statusText(status), outcome } }; +} + +function checkBundle(bundle) { + if (!bundle || bundle.resourceType !== 'Bundle') { + throw badRequest('POST to the endpoint takes a Bundle (batch or transaction)'); + } + if (bundle.type !== 'batch' && bundle.type !== 'transaction') { + throw badRequest(`A Bundle of type ${bundle.type} can't be processed: post a batch or a transaction`); + } + if (bundle.entry !== undefined && !Array.isArray(bundle.entry)) { + throw badRequest('Bundle.entry must be an array'); + } +} + +async function bundle(ep, freq) { + checkBundle(freq.body); + return freq.body.type === 'batch' ? batch(ep, freq) : transaction(ep, freq); +} + +async function batch(ep, freq) { + const entries = freq.body.entry || []; + const out = []; + for (const entry of entries) { + try { + const efreq = fromEntry(entry, freq); + if (efreq.interaction === 'bundle') { + throw badRequest('A batch can\'t contain another batch or transaction'); + } + // entries in a batch are independent: one can't refer to another by its fullUrl + if (efreq.body && efreq.method !== 'PATCH') { + eachReference(efreq.body, (r) => { + if (URN.test(r.reference)) { + throw badRequest(`The reference ${r.reference} is to another entry: entries in a batch can't refer to each other (use a transaction)`); + } + }); + } + const eaccess = access.check(freq.principal, ep, ep.accessInteraction(efreq)); + const result = await ep.dispatch(efreq, { access: eaccess }); + out.push(responseEntry(ep, efreq, result)); + } catch (err) { + if (!(err instanceof FhirError)) { + ep.log.error(`Batch entry failed: ${err.stack || err.message}`); + } + out.push(errorEntry(err)); + } + } + return { status: 200, resource: { resourceType: 'Bundle', type: 'batch-response', entry: out } }; +} + +/** Replace strings exactly equal to a mapped value, everywhere in a resource */ +// ---- transactions ---- +// +// A transaction is planned before anything is written, inside the database transaction: +// +// 1. every entry is parsed and its access checked (before the database transaction starts) +// 2. each write entry is given the one resource it changes: a DELETE or PUT names it, a POST +// gets a new id reserved for it, and the conditional forms (If-None-Exist, PUT/PATCH/DELETE +// with search criteria) are searched once, here. A resource may be changed by only one +// entry: two entries that change the same one fail the transaction +// 3. conditional references (Patient?identifier=x) are searched: exactly one match +// 4. every fullUrl a write entry has is mapped to its resource, and references to it inside +// the Bundle are rewritten (references, uris, and / in narratives); +// a urn:uuid: or urn:oid: reference that is still left points at nothing: it fails +// 5. references marked resolve-as-version-specific are pointed at the version this +// transaction writes +// 6. the entries run, in the specification's order: deletes, creates, updates and patches, +// reads. Reference checks wait until every entry has been written +// +// Any failure rolls everything back, and the failing entry's OperationOutcome is returned. + +const RESOLVE_AS_VERSION_SPECIFIC = 'http://hl7.org/fhir/StructureDefinition/resolve-as-version-specific'; +const URN = /^urn:(uuid|oid):/; + +/** The mapped value for a string: an exact match, or a match of the part before '#' */ +function mapped(map, s) { + if (map.has(s)) { + return map.get(s); + } + const hash = s.indexOf('#'); + if (hash > 0 && map.has(s.substring(0, hash))) { + return map.get(s.substring(0, hash)) + s.substring(hash); + } + return null; +} + +/** An XHTML attribute's value as text (the entities an attribute holds) */ +function unescapeAttribute(s) { + return s.replace(/&(lt|gt|quot|#39|apos|amp);/g, (m, e) => ({ lt: '<', gt: '>', quot: '"', '#39': '\'', apos: '\'', amp: '&' })[e]); +} + +/** A value for an XHTML attribute */ +function escapeAttribute(s) { + return s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); +} + +/** + * Point the links in a narrative at the new resources: only and , and only + * attributes that match exactly (or up to a #). Nothing else in the XHTML is touched. + */ +function rewriteNarrative(div, map) { + // a single pass over the text (the narrative is the client's: no pattern that can backtrack) + let out = ''; + let i = 0; + for (;;) { + const lt = div.indexOf('<', i); + if (lt < 0) { + break; + } + const gt = div.indexOf('>', lt); + if (gt < 0) { + break; + } + const tag = div.substring(lt, gt + 1); + const name = tagName(tag); + out += div.substring(i, lt) + (name === 'a' ? rewriteAttribute(tag, 'href', map) : name === 'img' ? rewriteAttribute(tag, 'src', map) : tag); + i = gt + 1; + } + return out + div.substring(i); +} + +/** The lower-case name of an opening tag ('' is 'a'), or null */ +function tagName(tag) { + let j = 1; + while (j < tag.length && /[A-Za-z0-9]/.test(tag[j])) { + j++; + } + return j > 1 ? tag.substring(1, j).toLowerCase() : null; +} + +function isSpace(c) { + return c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f'; +} + +/** A tag with one attribute's value mapped, if it is quoted and has a mapping */ +function rewriteAttribute(tag, attr, map) { + const lower = tag.toLowerCase(); + let from = 0; + for (;;) { + const at = lower.indexOf(attr, from); + if (at < 0) { + return tag; + } + from = at + attr.length; + if (!isSpace(lower[at - 1])) { + continue; + } + let k = from; + while (isSpace(lower[k])) { + k++; + } + if (lower[k] !== '=') { + continue; + } + k++; + while (isSpace(lower[k])) { + k++; + } + const q = tag[k]; + if (q !== '"' && q !== '\'') { + return tag; + } + const end = tag.indexOf(q, k + 1); + if (end < 0) { + return tag; + } + const to = mapped(map, unescapeAttribute(tag.substring(k + 1, end))); + return to === null ? tag : tag.substring(0, k + 1) + escapeAttribute(to) + tag.substring(end); + } +} + +/** + * Replace strings that are references to entries of the Bundle, everywhere in a resource + * (any element whose whole value is the fullUrl: references, uris, urls), and the links in + * narratives. Strings that only contain a fullUrl are left alone. + */ +function rewrite(obj, map) { + if (Array.isArray(obj)) { + for (let i = 0; i < obj.length; i++) { + if (typeof obj[i] === 'string') { + const to = mapped(map, obj[i]); + if (to !== null) { + obj[i] = to; + } + } else if (obj[i] && typeof obj[i] === 'object') { + rewrite(obj[i], map); + } + } + } else if (obj && typeof obj === 'object') { + for (const k of Object.keys(obj)) { + const v = obj[k]; + if (k === 'div' && typeof v === 'string') { + obj[k] = rewriteNarrative(v, map); + } else if (typeof v === 'string') { + const to = mapped(map, v); + if (to !== null) { + obj[k] = to; + } + } else if (v && typeof v === 'object') { + rewrite(v, map); + } + } + } +} + +/** Walk the Reference-like objects (those with a string reference) in a resource */ +function eachReference(obj, fn) { + if (Array.isArray(obj)) { + obj.forEach(x => eachReference(x, fn)); + } else if (obj && typeof obj === 'object') { + if (typeof obj.reference === 'string') { + fn(obj); + } + for (const v of Object.values(obj)) { + if (v && typeof v === 'object') { + eachReference(v, fn); + } + } + } +} + +/** Conditional references (Type?criteria) in a resource */ +function conditionalReferences(obj) { + const out = new Set(); + eachReference(obj, (r) => { + if (/^[A-Z][A-Za-z]+\?/.test(r.reference)) { + out.add(r.reference); + } + }); + return out; +} + +function entryError(it, e) { + if (e instanceof FhirError) { + e.message = `Entry ${it.index} (${it.efreq.method} ${it.efreq.url}): ${e.message}`; + e.issues = null; + } + return e; +} + +/** + * Plan a write entry: what it changes, with its conditional criteria searched. + * Sets it.plan = { kind, type, id, ids, reservation, version, existing }. + */ +async function planEntry(ep, q, it, reserved) { + const f = it.efreq; + const search = (type, params, limit) => ep.searcher.matchKeys(q, type, params, { access: it.access, limit, strict: true }); + const current = async (type, id) => ep.store.current(q, type, id); + switch (f.interaction) { + case 'create': { + ep.checkType(f.type, 'create'); + const ine = f.headers['if-none-exist']; + if (ine) { + const settings = ep.typeSettings(f.type); + if (!settings.conditionalCreate) { + throw new FhirError(405, 'not-supported', `Conditional create is not allowed for ${f.type}`); + } + const params = parseQuery(String(ine).replace(/^[^?]*\?/, '')); + // as outside a transaction: two requests mustn't both find nothing and both create + await ep.conditionalLock(q, f.type, params); + const keys = await search(f.type, params, 2); + if (keys.length > 1) { + throw preconditionFailed(`If-None-Exist matches more than one ${f.type}`); + } + if (keys.length === 1) { + const [existing] = await ep.store.byKeys(q, keys); + it.plan = { kind: 'existing', type: f.type, id: existing.id, existing }; + return; + } + } + const reservation = await ep.store.reserve(q, f.type, null); + reserved.add(`${f.type}/${reservation.id}`); + it.plan = { kind: 'create', type: f.type, id: reservation.id, reservation, version: 1 }; + return; + } + case 'update': + case 'conditional-update': { + ep.checkType(f.type, 'update'); + let id = f.id; + if (f.interaction === 'conditional-update') { + if (!ep.typeSettings(f.type).conditionalUpdate) { + throw new FhirError(405, 'not-supported', `Conditional update is not allowed for ${f.type}`); + } + await ep.conditionalLock(q, f.type, f.params); + const keys = await search(f.type, f.params, 2); + if (keys.length > 1) { + throw preconditionFailed(`More than one ${f.type} matches ${f.url}`); + } + if (keys.length === 1) { + const [existing] = await ep.store.byKeys(q, keys); + if (f.body && f.body.id && f.body.id !== existing.id) { + throw badRequest(`The resource's id (${f.body.id}) is not the id of the resource that matches (${existing.id})`); + } + id = existing.id; + } else { + id = f.body && f.body.id ? f.body.id : null; + } + } + const cur = id ? await current(f.type, id) : null; + if (!id || !cur) { + if (!id || f.interaction === 'conditional-update' || ep.settings.createOnUpdate) { + const reservation = await ep.store.reserve(q, f.type, id); + if (!reservation.existing) { + reserved.add(`${f.type}/${reservation.id}`); + } + id = reservation.id; + it.plan = { kind: 'update', type: f.type, id, reservation, version: 1, creates: true }; + return; + } + } + if (cur && cur.deleted) { + reserved.add(`${f.type}/${id}`); + } + it.plan = { kind: 'update', type: f.type, id, version: cur ? cur.versionId + 1 : 1, creates: !cur || cur.deleted }; + return; + } + case 'patch': + case 'conditional-patch': { + ep.checkType(f.type, 'patch'); + let id = f.id; + if (f.interaction === 'conditional-patch') { + if (!ep.typeSettings(f.type).conditionalUpdate) { + throw new FhirError(405, 'not-supported', `Conditional patch is not allowed for ${f.type}`); + } + const keys = await search(f.type, f.params, 2); + if (keys.length === 0) { + throw notFound(`No ${f.type} matches ${f.url}`); + } + if (keys.length > 1) { + throw preconditionFailed(`More than one ${f.type} matches ${f.url}`); + } + id = (await ep.store.byKeys(q, keys))[0].id; + } + const cur = await current(f.type, id); + it.plan = { kind: 'patch', type: f.type, id, version: cur && !cur.deleted ? cur.versionId + 1 : null }; + return; + } + case 'delete': + ep.checkType(f.type, 'delete'); + it.plan = { kind: 'delete', type: f.type, ids: [f.id] }; + return; + case 'conditional-delete': { + ep.checkType(f.type, 'delete'); + if (!ep.typeSettings(f.type).conditionalDelete) { + throw new FhirError(405, 'not-supported', `Conditional delete is not allowed for ${f.type}`); + } + const max = Math.max(1, ep.settings.conditionalDeleteMax || 1); + const keys = await search(f.type, f.params, max + 1); + if (keys.length > max) { + throw preconditionFailed(max === 1 ? `More than one ${f.type} matches ${f.url}` : `More than ${max} ${f.type} resources match ${f.url}`); + } + const found = await ep.store.byKeys(q, keys); + it.plan = { kind: 'delete', type: f.type, ids: found.map(x => x.id), conditional: true }; + return; + } + default: + it.plan = { kind: 'read' }; + } +} + +/** The resources a planned entry changes, as Type/id */ +function identities(plan) { + switch (plan.kind) { + case 'create': + case 'update': + case 'patch': + return [`${plan.type}/${plan.id}`]; + case 'delete': + return plan.ids.map(id => `${plan.type}/${id}`); + default: + return []; + } +} + +/** + * Run a planned entry: the interaction, made concrete (no conditional left in it). + */ +async function runEntry(ep, q, it, reserved) { + const f = it.efreq; + const p = it.plan; + const ctx = { q, access: it.access, reserved, deferChecks: true, reservation: null }; + switch (p.kind) { + case 'existing': + return { status: 200, resource: p.existing.resource, headers: crud.versionHeaders(p.existing), write: true, + location: `${p.type}/${p.existing.id}/_history/${p.existing.versionId}` }; + case 'create': { + const headers = { ...f.headers }; + delete headers['if-none-exist']; + return crud.create(ep, { ...f, headers }, { ...ctx, reservation: p.reservation }); + } + case 'update': { + // a PUT keeps its body as it is (its id is checked against the URL); a conditional + // update's body takes the id of the resource it resolved to + const body = f.interaction === 'update' ? f.body : { ...f.body, id: p.id }; + return crud.update(ep, { ...f, interaction: 'update', id: p.id, body, params: [] }, { ...ctx, reservation: p.reservation || null }); + } + case 'patch': + return crud.patch(ep, { ...f, interaction: 'patch', id: p.id, params: [] }, ctx); + case 'delete': { + if (!p.conditional) { + return crud.remove(ep, f, ctx); + } + for (const id of p.ids) { + await crud.remove(ep, { ...f, interaction: 'delete', id, params: [] }, ctx); + } + const n = p.ids.length; + return { status: 200, outcome: { severity: 'information', code: 'informational', + diagnostics: n === 0 ? `No ${p.type} matched: nothing was deleted` : `Deleted ${n} ${p.type} resource${n === 1 ? '' : 's'}` }, write: true, deletion: true }; + } + default: + return ep.dispatch(f, ctx); + } +} + +/** Check the references left unresolved by the entries, now that they are all written */ +async function checkUnresolved(ep, q, unresolved) { + const missing = []; + for (const ref of unresolved) { + const parts = ref.split('/'); + const [type, id] = parts; + if (!ep.typeKeys.has(type)) { + missing.push(ref); + continue; + } + const row = await ep.store.idRow(q, type, id); + if (!row || row.MostRecent === null || row.Deleted) { + missing.push(ref); + continue; + } + if (parts.length === 4) { + const v = /^\d{1,9}$/.test(parts[3]) ? await q.get('SELECT 1 AS ok FROM Versions WHERE ResourceKey = ? AND VersionId = ?', [row.ResourceKey, Number(parts[3])]) : null; + if (!v) { + missing.push(ref); + } + } + } + return missing; +} + +async function transaction(ep, freq) { + const entries = freq.body.entry || []; + if (entries.length > ep.settings.transactionMaxEntries) { + throw badRequest(`A transaction is limited to ${ep.settings.transactionMaxEntries} entries on this endpoint`); + } + // parse every entry first: a malformed one fails the transaction before it starts + const items = entries.map((entry, index) => { + if (!entry || typeof entry !== 'object') { + throw badRequest(`Entry ${index} is not an object`); + } + let efreq; + try { + efreq = fromEntry(entry, freq); + } catch (e) { + if (e instanceof FhirError) { + e.message = `Entry ${index}: ${e.message}`; + } + throw e; + } + if (efreq.interaction === 'bundle') { + throw badRequest(`Entry ${index}: a transaction can't contain another batch or transaction`); + } + if ((efreq.method === 'POST' || efreq.method === 'PUT') && efreq.interaction !== 'operation' && (!entry.resource || typeof entry.resource !== 'object')) { + throw badRequest(`Entry ${index}: a ${efreq.method} needs a resource`); + } + if (efreq.method === 'PATCH' && !entry.resource) { + throw badRequest(`Entry ${index}: a PATCH needs a Binary resource holding the JSON Patch`); + } + if (efreq.interaction === 'operation') { + throw badRequest(`Entry ${index}: operations can't be used in a transaction`); + } + const eaccess = access.check(freq.principal, ep, ep.accessInteraction(efreq)); + return { index, entry, efreq, access: eaccess }; + }); + const fullUrls = new Map(); + const criteria = new Map(); + for (const it of items) { + const fu = it.entry.fullUrl; + if (fu && it.efreq.method !== 'GET' && it.efreq.method !== 'HEAD') { + if (fullUrls.has(fu)) { + throw badRequest(`Entries ${fullUrls.get(fu)} and ${it.index} both have the fullUrl ${fu}`); + } + fullUrls.set(fu, it.index); + } + const ine = it.efreq.interaction === 'create' && it.efreq.headers['if-none-exist']; + if (ine) { + // two conditional creates with the same criteria would both find nothing, and make two + const key = it.efreq.type + '?' + parseQuery(String(ine).replace(/^[^?]*\?/, '')).map(([n, v]) => `${n}=${v}`).sort().join('&'); + if (criteria.has(key)) { + throw badRequest(`Entries ${criteria.get(key)} and ${it.index} are conditional creates with the same criteria (${ine})`); + } + criteria.set(key, it.index); + } + } + const ordered = [...items].sort((a, b) => (ORDER[a.efreq.method] ?? 9) - (ORDER[b.efreq.method] ?? 9) || a.index - b.index); + + const results = await ep.db.write(async (q) => { + // fresh copies of everything the planning changes: the transaction can run again (busy, deadlock) + const work = ordered.map(it => ({ ...it, efreq: { ...it.efreq, headers: { ...it.efreq.headers }, body: it.efreq.body ? JSON.parse(JSON.stringify(it.efreq.body)) : null }, plan: null, result: null })); + const reserved = new Set(); + + // 2. what each entry changes; a resource changed by two entries fails + const changedBy = new Map(); + for (const it of work) { + try { + await planEntry(ep, q, it, reserved); + } catch (e) { + throw entryError(it, e); + } + for (const ident of identities(it.plan)) { + if (changedBy.has(ident)) { + throw badRequest(`Entries ${changedBy.get(ident)} and ${it.index} both change ${ident}: a resource can only be changed once in a transaction`); + } + changedBy.set(ident, it.index); + } + } + + // 3. conditional references + const map = new Map(); + for (const it of work) { + if (!it.efreq.body) { + continue; + } + for (const ref of conditionalReferences(it.efreq.body)) { + if (map.has(ref)) { + continue; + } + const qm = ref.indexOf('?'); + const type = ref.substring(0, qm); + try { + ep.checkType(type, 'search-type'); + const keys = await ep.searcher.matchKeys(q, type, parseQuery(ref.substring(qm + 1)), { access: it.access, limit: 2, strict: true }); + if (keys.length !== 1) { + throw new FhirError(412, 'conflict', `The conditional reference ${ref} matches ${keys.length === 0 ? 'nothing' : 'more than one resource'}`); + } + const [target] = await ep.store.byKeys(q, keys); + map.set(ref, `${type}/${target.id}`); + } catch (e) { + throw entryError(it, e); + } + } + } + + // 4. fullUrls to their resources, and the references to them + const targets = new Map(); + for (const it of work) { + const p = it.plan; + const fu = it.entry.fullUrl; + if (p.kind === 'create' || p.kind === 'update' || p.kind === 'patch' || p.kind === 'existing') { + const local = `${p.type}/${p.id}`; + targets.set(local, p); + if (fu) { + map.set(fu, local); + } + } + } + if (map.size) { + for (const it of work) { + if (it.efreq.body) { + rewrite(it.efreq.body, map); + } + } + } + for (const it of work) { + if (!it.efreq.body || it.efreq.method === 'PATCH') { + continue; + } + eachReference(it.efreq.body, (r) => { + if (URN.test(r.reference)) { + throw entryError(it, badRequest(`The reference ${r.reference} is not the fullUrl of any resource in the transaction`)); + } + }); + } + + // 5. references to the versions this transaction writes + for (const it of work) { + if (!it.efreq.body) { + continue; + } + eachReference(it.efreq.body, (r) => { + const ext = Array.isArray(r.extension) ? r.extension.find(x => x && x.url === RESOLVE_AS_VERSION_SPECIFIC) : null; + if (!ext) { + return; + } + if (ext.valueBoolean !== false) { + const p = targets.get(r.reference); + if (!p || !p.version && p.kind !== 'existing') { + throw entryError(it, badRequest(`The reference ${r.reference} is to be resolved to a version, but no entry in the transaction writes it`)); + } + r.reference = `${r.reference}/_history/${p.kind === 'existing' ? p.existing.versionId : p.version}`; + } + r.extension = r.extension.filter(x => x !== ext); + if (!r.extension.length) { + delete r.extension; + } + }); + } + + // 6. run the entries, in order + const unresolved = new Set(); + for (const it of work) { + try { + it.result = await runEntry(ep, q, it, reserved); + } catch (e) { + throw entryError(it, e); + } + if (it.result.written && it.result.written.unresolved) { + it.result.written.unresolved.forEach(u => unresolved.add(u)); + } + } + + // and the references, now that everything is written + if (ep.settings.checkReferences && unresolved.size) { + const missing = await checkUnresolved(ep, q, unresolved); + if (missing.length) { + throw unprocessable(`The transaction refers to resources that don't exist: ${missing.join(', ')}`); + } + } + return work; + }); + const byIndex = new Map(results.map(it => [it.index, it])); + const out = entries.map((e, i) => responseEntry(ep, byIndex.get(i).efreq, byIndex.get(i).result)); + return { status: 200, resource: { resourceType: 'Bundle', type: 'transaction-response', entry: out } }; +} + +module.exports = { bundle, batch, transaction, rewrite, rewriteNarrative, notFound }; diff --git a/rest/interactions/capabilities.js b/rest/interactions/capabilities.js new file mode 100644 index 00000000..33a92c79 --- /dev/null +++ b/rest/interactions/capabilities.js @@ -0,0 +1,91 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The CapabilityStatement: built from Types, the search parameters, the endpoint's settings + * and the operations available. + * + * @module rest/interactions/capabilities + */ + +const packageJson = require('../../package.json'); +const { typeAllows } = require('../endpoint/settings'); +const { OPERATIONS } = require('../operations/operations'); + +const COMMON = [ + { name: '_id', type: 'token' }, { name: '_lastUpdated', type: 'date' }, { name: '_tag', type: 'token' }, + { name: '_security', type: 'token' }, { name: '_profile', type: 'uri' }, { name: '_has', type: 'string' }, + { name: '_filter', type: 'string' }, { name: '_list', type: 'string' } +]; + +function capabilities(ep, freq) { + const s = ep.settings; + const resources = []; + for (const type of [...ep.typeKeys.keys()].sort()) { + const ts = ep.typeSettings(type); + if (!ts.supported) { + continue; + } + const interaction = []; + for (const code of ['read', 'vread', 'update', 'patch', 'delete', 'history-instance', 'history-type', 'create', 'search-type']) { + if (typeAllows(ts, code)) { + interaction.push({ code }); + } + } + const searchParam = [...COMMON.map(c => ({ ...c })), + ...[...ep.definitions.forType(type).values()].filter(d => d.key !== null && d.key !== undefined).map(d => ({ name: d.code, definition: d.url, type: d.type }))]; + const r = { + type, + interaction, + versioning: 'versioned-update', + readHistory: true, + updateCreate: !!s.createOnUpdate, + conditionalCreate: !!ts.conditionalCreate, + conditionalRead: 'not-supported', + conditionalUpdate: !!ts.conditionalUpdate, + conditionalDelete: ts.conditionalDelete ? ((s.conditionalDeleteMax || 1) > 1 ? 'multiple' : 'single') : 'not-supported', + referencePolicy: ['literal', 'logical', 'local'], + searchInclude: ['*'], + searchRevInclude: ['*'], + searchParam + }; + if (ts.versionAware) { + r.versioning = 'versioned-update'; + } + const ops = OPERATIONS.filter(o => o.types === null || o.types.includes(type)).filter(o => o.instance || o.type); + if (ops.length) { + r.operation = ops.map(o => ({ name: o.name, definition: o.definition })); + } + resources.push(r); + } + const cs = { + resourceType: 'CapabilityStatement', + status: 'active', + date: new Date(ep.startedAt).toISOString(), + name: 'FHIRsmithRestServer', + title: s.name, + kind: 'instance', + software: { name: 'FHIRsmith', version: packageJson.version }, + implementation: { description: s.description || s.name, url: freq.base }, + fhirVersion: ep.definitions.fhirVersion, + format: ['json'], + patchFormat: ['application/json-patch+json'], + rest: [{ + mode: 'server', + security: { cors: true, description: s.anonymous === 'none' ? 'Log in, or send an API token (Authorization: Bearer)' : `Anonymous ${s.anonymous} is allowed` }, + resource: resources, + interaction: [{ code: 'transaction' }, { code: 'batch' }, { code: 'search-system' }, { code: 'history-system' }], + searchParam: COMMON, + operation: OPERATIONS.filter(o => o.system).map(o => ({ name: o.name, definition: o.definition })) + }] + }; + if (s.description) { + cs.description = s.description; + } + return { status: 200, resource: cs }; +} + +module.exports = { capabilities }; diff --git a/rest/interactions/crud.js b/rest/interactions/crud.js new file mode 100644 index 00000000..1803e255 --- /dev/null +++ b/rest/interactions/crud.js @@ -0,0 +1,347 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * read, vread, create, update, patch and delete, and their conditional forms. + * + * Every write runs in one database transaction covering the resource, its version, tags, + * index rows, compartments, subscription queue row and AuditEvent. In a transaction Bundle + * the Bundle's own transaction is used (ctx.q). + * + * @module rest/interactions/crud + */ + +const { badRequest, notFound, gone, preconditionFailed, unprocessable, FhirError } = require('../library/errors'); +const { ifMatchVersion, etagVersion, parseQuery } = require('../request'); +const { applyPatch, PatchError } = require('../library/json-patch'); +const { ID_RE } = require('../store'); + +/** The headers for a version: ETag, Last-Modified */ +function versionHeaders(v) { + return { ETag: `W/"${v.versionId}"`, 'Last-Modified': new Date(v.lastUpdated).toUTCString() }; +} + +function checkId(id) { + if (!ID_RE.test(String(id))) { + throw badRequest(`'${id}' is not a valid id`); + } +} + +/** Check the body is a resource of the type, with the id (or none, for create) */ +function checkBody(freq, type, id) { + const r = freq.body; + if (!r || typeof r !== 'object' || Array.isArray(r)) { + throw badRequest('The body must be a resource'); + } + if (r.resourceType !== type) { + throw badRequest(`The resource is a ${r.resourceType || '(no resourceType)'}, not a ${type}`); + } + if (id !== undefined) { + if (r.id === undefined || r.id === null) { + throw badRequest(`The resource has no id: it must be ${id}`); + } + if (String(r.id) !== String(id)) { + throw badRequest(`The resource's id (${r.id}) is not the id in the URL (${id})`); + } + } + return r; +} + +/** + * The If-None-Match / If-Modified-Since checks on a read: true when the client's copy is current. + */ +function notModified(freq, v) { + const inm = freq.headers['if-none-match']; + if (inm) { + return etagVersion(inm) === String(v.versionId); + } + const ims = freq.headers['if-modified-since']; + if (ims) { + const t = Date.parse(ims); + return Number.isFinite(t) && Math.floor(v.lastUpdated / 1000) * 1000 <= t; + } + return false; +} + +async function read(ep, freq, ctx) { + checkId(freq.id); + ep.checkType(freq.type, 'read'); + const v = await ep.inRead(ctx, async (q) => { + const cur = await ep.store.current(q, freq.type, freq.id); + if (cur) { + await ep.checkCompartments(q, ctx.access, cur.resourceKey); + } + return cur; + }); + if (!v) { + throw notFound(`${freq.type}/${freq.id} is not known`); + } + if (v.deleted) { + throw gone(`${freq.type}/${freq.id} has been deleted`, { headers: versionHeaders(v) }); + } + if (notModified(freq, v)) { + return { status: 304, headers: versionHeaders(v) }; + } + return { status: 200, resource: v.resource, headers: versionHeaders(v), shape: true }; +} + +async function vread(ep, freq, ctx) { + checkId(freq.id); + ep.checkType(freq.type, 'vread'); + const v = await ep.inRead(ctx, async (q) => { + const ver = await ep.store.version(q, freq.type, freq.id, freq.vid); + if (ver) { + await ep.checkCompartments(q, ctx.access, ver.resourceKey); + } + return ver; + }); + if (!v) { + throw notFound(`${freq.type}/${freq.id}/_history/${freq.vid} is not known`); + } + if (v.deleted) { + throw gone(`${freq.type}/${freq.id}/_history/${freq.vid} is a deletion`, { headers: versionHeaders(v) }); + } + return { status: 200, resource: v.resource, headers: versionHeaders(v), shape: true }; +} + +/** The result of a write: 200 or 201, with Location and the version headers */ +function writeResult(ep, freq, type, r, status) { + const headers = versionHeaders(r); + const loc = `${freq.base}/${type}/${r.id}/_history/${r.versionId}`; + if (status === 201) { + headers.Location = loc; + } else { + headers['Content-Location'] = loc; + } + return { status, resource: r.resource, headers, write: true, location: `${type}/${r.id}/_history/${r.versionId}`, written: r }; +} + +/** + * The resources matching conditional criteria (If-None-Exist, a conditional update or delete). + * @returns {Promise} resource keys (at most limit + 1) + */ +async function conditionalMatches(ep, q, type, params, ctx, limit) { + if (!params.length) { + throw badRequest('A conditional interaction needs search criteria'); + } + return ep.searcher.matchKeys(q, type, params, { access: ctx.access, limit: limit + 1, strict: true }); +} + +async function create(ep, freq, ctx) { + ep.checkType(freq.type, 'create'); + const resource = checkBody(freq, freq.type); + const settings = ep.typeSettings(freq.type); + const ifNoneExist = freq.headers['if-none-exist']; + if (ifNoneExist && !settings.conditionalCreate) { + throw new FhirError(405, 'not-supported', `Conditional create is not allowed for ${freq.type}`); + } + const body = { ...resource }; + // a create ignores the client's id (and its meta.versionId and lastUpdated) + delete body.id; + const result = await ep.inWrite(ctx, async (q) => { + if (ifNoneExist) { + const params = parseQuery(String(ifNoneExist).replace(/^[^?]*\?/, '')); + await ep.conditionalLock(q, freq.type, params); + const keys = await conditionalMatches(ep, q, freq.type, params, ctx, 1); + if (keys.length > 1) { + throw preconditionFailed(`If-None-Exist: more than one ${freq.type} matches ${ifNoneExist}`); + } + if (keys.length === 1) { + const [existing] = await ep.store.byKeys(q, keys); + return { existing }; + } + } + const r = await ep.store.put(q, { + type: freq.type, id: null, resource: body, ifMatch: null, mustCreate: true, userId: ep.userId(freq), + reservation: ctx.reservation, reserved: ctx.reserved, deferChecks: ctx.deferChecks + }); + await ep.auditWrite(q, freq, 'create', 201, `${freq.type}/${r.id}/_history/${r.versionId}`, r.versionKey); + return { r }; + }); + if (result.existing) { + const e = result.existing; + return { status: 200, resource: e.resource, headers: versionHeaders(e), write: true, location: `${freq.type}/${e.id}/_history/${e.versionId}` }; + } + return writeResult(ep, freq, freq.type, result.r, 201); +} + +async function update(ep, freq, ctx) { + checkId(freq.id); + ep.checkType(freq.type, 'update'); + const resource = checkBody(freq, freq.type, freq.id); + const settings = ep.typeSettings(freq.type); + const r = await ep.inWrite(ctx, async (q) => { + const cur = await ep.store.current(q, freq.type, freq.id); + if (cur) { + await ep.checkCompartments(q, ctx.access, cur.resourceKey); + } + const out = await ep.store.put(q, { + type: freq.type, id: freq.id, resource, ifMatch: ifMatchVersion(freq), createOnUpdate: ep.settings.createOnUpdate, + versionAware: settings.versionAware, userId: ep.userId(freq), reservation: ctx.reservation, reserved: ctx.reserved, deferChecks: ctx.deferChecks + }); + await ep.auditWrite(q, freq, out.created ? 'create' : 'update', out.created ? 201 : 200, `${freq.type}/${out.id}/_history/${out.versionId}`, out.versionKey); + return out; + }); + return writeResult(ep, freq, freq.type, r, r.created ? 201 : 200); +} + +async function conditionalUpdate(ep, freq, ctx) { + ep.checkType(freq.type, 'update'); + const settings = ep.typeSettings(freq.type); + if (!settings.conditionalUpdate) { + throw new FhirError(405, 'not-supported', `Conditional update is not allowed for ${freq.type}`); + } + const resource = checkBody(freq, freq.type); + const r = await ep.inWrite(ctx, async (q) => { + await ep.conditionalLock(q, freq.type, freq.params); + const keys = await conditionalMatches(ep, q, freq.type, freq.params, ctx, 1); + if (keys.length > 1) { + throw preconditionFailed(`More than one ${freq.type} matches the criteria`); + } + let id; + if (keys.length === 1) { + const [existing] = await ep.store.byKeys(q, keys); + id = existing.id; + if (resource.id && resource.id !== id) { + throw badRequest(`The resource's id (${resource.id}) is not the id of the matching resource (${id})`); + } + } else { + // no match: a create, with the client's id if it gave one + id = resource.id || null; + } + const body = { ...resource }; + let out; + if (id) { + out = await ep.store.put(q, { + type: freq.type, id, resource: body, ifMatch: ifMatchVersion(freq), createOnUpdate: true, versionAware: settings.versionAware, + userId: ep.userId(freq), reserved: ctx.reserved, deferChecks: ctx.deferChecks, reservation: keys.length === 0 ? ctx.reservation : null + }); + } else { + delete body.id; + out = await ep.store.put(q, { type: freq.type, id: null, resource: body, mustCreate: true, userId: ep.userId(freq), + reservation: ctx.reservation, reserved: ctx.reserved, deferChecks: ctx.deferChecks }); + } + await ep.auditWrite(q, freq, out.created ? 'create' : 'update', out.created ? 201 : 200, `${freq.type}/${out.id}/_history/${out.versionId}`, out.versionKey); + return out; + }); + return writeResult(ep, freq, freq.type, r, r.created ? 201 : 200); +} + +function patchDocument(freq) { + const p = freq.body; + if (Array.isArray(p)) { + return p; + } + if (p && p.resourceType === 'Parameters') { + throw new FhirError(415, 'not-supported', 'FHIRPath Patch is not supported yet: use JSON Patch (application/json-patch+json)'); + } + throw badRequest('The body must be a JSON Patch (an array of operations)'); +} + +async function patchOne(ep, q, freq, ctx, type, id, settings) { + const cur = await ep.store.current(q, type, id); + if (!cur) { + throw notFound(`${type}/${id} is not known`); + } + if (cur.deleted) { + throw gone(`${type}/${id} has been deleted`); + } + await ep.checkCompartments(q, ctx.access, cur.resourceKey); + let patched; + try { + patched = applyPatch(cur.resource, patchDocument(freq)); + } catch (e) { + if (e instanceof PatchError) { + throw unprocessable(`The patch can't be applied: ${e.message}`); + } + throw e; + } + if (!patched || patched.resourceType !== type || patched.id !== id) { + throw unprocessable('A patch can\'t change the resource\'s type or id'); + } + const out = await ep.store.put(q, { + type, id, resource: patched, ifMatch: ifMatchVersion(freq), versionAware: settings.versionAware, userId: ep.userId(freq), + reserved: ctx.reserved, deferChecks: ctx.deferChecks + }); + await ep.auditWrite(q, freq, 'patch', 200, `${type}/${id}/_history/${out.versionId}`, out.versionKey); + return out; +} + +async function patch(ep, freq, ctx) { + checkId(freq.id); + ep.checkType(freq.type, 'patch'); + const settings = ep.typeSettings(freq.type); + if (settings.versionAware && !ifMatchVersion(freq)) { + throw preconditionFailed(`Patches to ${freq.type} must say which version they change (If-Match)`); + } + const r = await ep.inWrite(ctx, q => patchOne(ep, q, freq, ctx, freq.type, freq.id, settings)); + return writeResult(ep, freq, freq.type, r, 200); +} + +async function conditionalPatch(ep, freq, ctx) { + ep.checkType(freq.type, 'patch'); + const settings = ep.typeSettings(freq.type); + if (!settings.conditionalUpdate) { + throw new FhirError(405, 'not-supported', `Conditional patch is not allowed for ${freq.type}`); + } + const r = await ep.inWrite(ctx, async (q) => { + const keys = await conditionalMatches(ep, q, freq.type, freq.params, ctx, 1); + if (keys.length === 0) { + throw notFound(`No ${freq.type} matches the criteria`); + } + if (keys.length > 1) { + throw preconditionFailed(`More than one ${freq.type} matches the criteria`); + } + const [existing] = await ep.store.byKeys(q, keys); + return patchOne(ep, q, freq, ctx, freq.type, existing.id, settings); + }); + return writeResult(ep, freq, freq.type, r, 200); +} + +async function remove(ep, freq, ctx) { + checkId(freq.id); + ep.checkType(freq.type, 'delete'); + const r = await ep.inWrite(ctx, async (q) => { + const cur = await ep.store.current(q, freq.type, freq.id); + if (cur && !cur.deleted) { + await ep.checkCompartments(q, ctx.access, cur.resourceKey); + } + const out = await ep.store.put(q, { type: freq.type, id: freq.id, resource: null, ifMatch: ifMatchVersion(freq), userId: ep.userId(freq) }); + if (!out.unchanged) { + await ep.auditWrite(q, freq, 'delete', 200, `${freq.type}/${freq.id}/_history/${out.versionId}`, out.versionKey); + } + return out; + }); + const headers = r.unchanged || !r.versionId ? {} : { ETag: `W/"${r.versionId}"` }; + return { status: 200, outcome: { severity: 'information', code: 'informational', + diagnostics: r.unchanged ? `${freq.type}/${freq.id} was already deleted, or never existed` : `Deleted ${freq.type}/${freq.id}` }, + headers, write: true, deletion: true }; +} + +async function conditionalDelete(ep, freq, ctx) { + ep.checkType(freq.type, 'delete'); + const settings = ep.typeSettings(freq.type); + if (!settings.conditionalDelete) { + throw new FhirError(405, 'not-supported', `Conditional delete is not allowed for ${freq.type}`); + } + const max = Math.max(1, ep.settings.conditionalDeleteMax || 1); + const n = await ep.inWrite(ctx, async (q) => { + const keys = await conditionalMatches(ep, q, freq.type, freq.params, ctx, max); + if (keys.length > max) { + throw preconditionFailed(max === 1 ? `More than one ${freq.type} matches the criteria` : `More than ${max} ${freq.type} resources match the criteria`); + } + const found = await ep.store.byKeys(q, keys); + for (const e of found) { + const out = await ep.store.put(q, { type: freq.type, id: e.id, resource: null, ifMatch: null, userId: ep.userId(freq) }); + await ep.auditWrite(q, freq, 'delete', 200, `${freq.type}/${e.id}/_history/${out.versionId}`, out.versionKey); + } + return found.length; + }); + return { status: 200, outcome: { severity: 'information', code: 'informational', + diagnostics: n === 0 ? `No ${freq.type} matched: nothing was deleted` : `Deleted ${n} ${freq.type} resource${n === 1 ? '' : 's'}` }, write: true, deletion: true }; +} + +module.exports = { read, vread, create, update, conditionalUpdate, patch, conditionalPatch, remove, conditionalDelete, versionHeaders, checkBody }; diff --git a/rest/interactions/history.js b/rest/interactions/history.js new file mode 100644 index 00000000..8b546430 --- /dev/null +++ b/rest/interactions/history.js @@ -0,0 +1,131 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * history: of a resource, a type, or the whole endpoint. Newest first, paged by version key + * (the next page asks for versions older than the last one shown), so nothing is stored. + * + * _count page size (the endpoint's default and maximum) + * _since versions written at or after an instant + * _at versions that were current at some point in a date's range + * + * @module rest/interactions/history + */ + +const { badRequest, notFound } = require('../library/errors'); +const { dateRange } = require('../../library/fhir-search-values'); +const { decode, OP_CREATE, OP_DELETE } = require('../store'); +const { param } = require('../request'); + +function pageSize(ep, freq) { + const c = param(freq, '_count'); + if (c === undefined || c === '') { + return ep.settings.defaultCount; + } + if (!/^\d+$/.test(c)) { + throw badRequest(`_count must be a number, not '${c}'`); + } + return Math.min(Number(c), ep.settings.maxCount); +} + +async function history(ep, freq, ctx) { + const level = freq.interaction; + if (freq.type) { + ep.checkType(freq.type, level); + } + const count = pageSize(ep, freq); + const where = []; + const args = []; + const since = param(freq, '_since'); + if (since) { + const r = dateRange(since, ep.timeZone); + if (!r) { + throw badRequest(`_since must be an instant, not '${since}'`); + } + where.push('v.LastUpdated >= ?'); + args.push(r.lo); + } + const at = param(freq, '_at'); + if (at) { + const r = dateRange(at, ep.timeZone); + if (!r) { + throw badRequest(`_at must be a date, not '${at}'`); + } + // written before the range ends, and not replaced before it starts + where.push('v.LastUpdated < ?'); + args.push(r.hi); + where.push('NOT EXISTS (SELECT 1 FROM Versions n WHERE n.ResourceKey = v.ResourceKey AND n.VersionId = v.VersionId + 1 AND n.LastUpdated <= ?)'); + args.push(r.lo); + } + const cursor = param(freq, '_cursor'); + if (cursor !== undefined) { + if (!/^\d+$/.test(cursor)) { + throw badRequest('_cursor is not valid'); + } + where.push('v.VersionKey < ?'); + args.push(Number(cursor)); + } + const out = await ep.inRead(ctx, async (q) => { + let resourceKey = null; + if (level === 'history-instance') { + const ids = await ep.store.idRow(q, freq.type, freq.id); + if (!ids || ids.MostRecent === null) { + throw notFound(`${freq.type}/${freq.id} is not known`); + } + await ep.checkCompartments(q, ctx.access, ids.ResourceKey); + resourceKey = ids.ResourceKey; + where.push('v.ResourceKey = ?'); + args.push(resourceKey); + } else if (level === 'history-type') { + where.push('i.TypeKey = ?'); + args.push(ep.store.typeKey(freq.type)); + } + const comp = ep.compartmentFilter(ctx.access, 'i.ResourceKey'); + if (comp) { + where.push(comp.sql); + args.push(...comp.args); + } + const rows = await q.all(`SELECT v.VersionKey, v.ResourceKey, v.VersionId, v.LastUpdated, v.Operation, v.Compressed, v.Content, i.Id, t.Name + FROM Versions v JOIN Ids i ON i.ResourceKey = v.ResourceKey JOIN Types t ON t.TypeKey = i.TypeKey + ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY v.VersionKey DESC LIMIT ${count + 1}`, args); + let total; + if (level === 'history-instance' && cursor === undefined && !since && !at) { + const t = await q.get('SELECT COUNT(*) AS N FROM Versions WHERE ResourceKey = ?', [resourceKey]); + total = Number(t.N); + } + return { rows, total }; + }); + const more = out.rows.length > count; + const rows = out.rows.slice(0, count); + const bundle = { resourceType: 'Bundle', type: 'history' }; + if (out.total !== undefined) { + bundle.total = out.total; + } + const self = freq.base + '/' + freq.segments.map(encodeURIComponent).join('/'); + const keep = freq.params.filter(([n]) => ['_count', '_since', '_at'].includes(n)); + const qs = (extra) => { + const all = [...keep, ...extra]; + return all.length ? '?' + all.map(([n, v]) => `${encodeURIComponent(n)}=${encodeURIComponent(v)}`).join('&') : ''; + }; + bundle.link = [{ relation: 'self', url: self + qs(cursor !== undefined ? [['_cursor', cursor]] : []) }]; + if (more) { + bundle.link.push({ relation: 'next', url: self + qs([['_cursor', String(rows[rows.length - 1].VersionKey)]]) }); + } + bundle.entry = rows.map(r => { + const op = Number(r.Operation); + const e = { fullUrl: `${freq.base}/${r.Name}/${r.Id}` }; + const resource = decode(r); + if (resource) { + e.resource = ep.shapeResource(resource, freq); + } + e.request = op === OP_CREATE ? { method: 'POST', url: r.Name } : op === OP_DELETE ? { method: 'DELETE', url: `${r.Name}/${r.Id}` } : { method: 'PUT', url: `${r.Name}/${r.Id}` }; + e.response = { status: op === OP_CREATE ? '201' : op === OP_DELETE ? '204' : '200', etag: `W/"${r.VersionId}"`, lastModified: new Date(Number(r.LastUpdated)).toISOString() }; + return e; + }); + return { status: 200, resource: bundle }; +} + +module.exports = { history, pageSize }; diff --git a/rest/library/errors.js b/rest/library/errors.js new file mode 100644 index 00000000..66c4c35d --- /dev/null +++ b/rest/library/errors.js @@ -0,0 +1,69 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Errors that become an OperationOutcome and an HTTP status. + * + * @module rest/library/errors + */ + +class FhirError extends Error { + /** + * @param {number} status - HTTP status + * @param {string} code - issue type (not-found, invalid, conflict, ...) + * @param {string} message + * @param {Object} [extra] - { expression: string[], headers: Object, issues: Object[] } + */ + constructor(status, code, message, extra = {}) { + super(message); + this.status = status; + this.code = code; + this.expression = extra.expression; + this.headers = extra.headers || {}; + this.issues = extra.issues || null; + } + + outcome() { + return operationOutcome(this.issues || [{ severity: 'error', code: this.code, diagnostics: this.message, expression: this.expression }]); + } +} + +const badRequest = (msg, extra) => new FhirError(400, 'invalid', msg, extra); +const notFound = (msg) => new FhirError(404, 'not-found', msg); +const gone = (msg, extra) => new FhirError(410, 'deleted', msg, extra); +const conflict = (msg) => new FhirError(409, 'conflict', msg); +const preconditionFailed = (msg) => new FhirError(412, 'conflict', msg); +const forbidden = (msg) => new FhirError(403, 'forbidden', msg); +const unauthorised = (msg) => new FhirError(401, 'login', msg); +const notSupported = (msg) => new FhirError(501, 'not-supported', msg); +const notAllowed = (msg) => new FhirError(405, 'not-supported', msg); +const unprocessable = (msg, extra) => new FhirError(422, 'processing', msg, extra); +const tooCostly = (msg) => new FhirError(400, 'too-costly', msg); + +/** + * @param {Array<{severity: string, code: string, diagnostics?: string, expression?: string[]}>} issues + */ +function operationOutcome(issues) { + return { + resourceType: 'OperationOutcome', + issue: issues.map(i => { + const o = { severity: i.severity || 'error', code: i.code || 'processing' }; + if (i.diagnostics) { + o.diagnostics = i.diagnostics; + o.details = { text: i.diagnostics }; + } + if (i.expression && i.expression.length) { + o.expression = i.expression; + } + return o; + }) + }; +} + +module.exports = { + FhirError, badRequest, notFound, gone, conflict, preconditionFailed, forbidden, unauthorised, notSupported, notAllowed, + unprocessable, tooCostly, operationOutcome +}; diff --git a/rest/library/json-patch.js b/rest/library/json-patch.js new file mode 100644 index 00000000..3defe8ee --- /dev/null +++ b/rest/library/json-patch.js @@ -0,0 +1,194 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * JSON Patch (RFC 6902) and JSON Pointer (RFC 6901), applied to a copy. + * + * @module rest/library/json-patch + */ + +class PatchError extends Error {} + +function parsePointer(p) { + if (p === '') { + return []; + } + if (typeof p !== 'string' || !p.startsWith('/')) { + throw new PatchError(`'${p}' is not a JSON Pointer`); + } + return p.substring(1).split('/').map(s => s.replace(/~1/g, '/').replace(/~0/g, '~')); +} + +function isIndex(s) { + return /^(0|[1-9]\d*)$/.test(s); +} + +function getParent(doc, tokens, path) { + let cur = doc; + for (let i = 0; i < tokens.length - 1; i++) { + const t = tokens[i]; + if (Array.isArray(cur)) { + if (!isIndex(t) || Number(t) >= cur.length) { + throw new PatchError(`${path}: no element ${t}`); + } + cur = cur[Number(t)]; + } else if (cur && typeof cur === 'object' && Object.prototype.hasOwnProperty.call(cur, t)) { + cur = cur[t]; + } else { + throw new PatchError(`${path}: no element ${t}`); + } + } + if (cur === null || typeof cur !== 'object') { + throw new PatchError(`${path}: the parent is not an object or array`); + } + return cur; +} + +function getValue(doc, path) { + const tokens = parsePointer(path); + if (tokens.length === 0) { + return doc; + } + const parent = getParent(doc, tokens, path); + const last = tokens[tokens.length - 1]; + if (Array.isArray(parent)) { + if (!isIndex(last) || Number(last) >= parent.length) { + throw new PatchError(`${path}: no element ${last}`); + } + return parent[Number(last)]; + } + if (!Object.prototype.hasOwnProperty.call(parent, last)) { + throw new PatchError(`${path}: no element ${last}`); + } + return parent[last]; +} + +function add(doc, path, value) { + const tokens = parsePointer(path); + if (tokens.length === 0) { + return value; + } + const parent = getParent(doc, tokens, path); + const last = tokens[tokens.length - 1]; + if (Array.isArray(parent)) { + if (last === '-') { + parent.push(value); + } else if (isIndex(last) && Number(last) <= parent.length) { + parent.splice(Number(last), 0, value); + } else { + throw new PatchError(`${path}: index ${last} is out of range`); + } + } else { + if (last === '__proto__' || last === 'constructor' || last === 'prototype') { + throw new PatchError(`${path}: not allowed`); + } + parent[last] = value; + } + return doc; +} + +function remove(doc, path) { + const tokens = parsePointer(path); + if (tokens.length === 0) { + throw new PatchError('Can\'t remove the whole document'); + } + const parent = getParent(doc, tokens, path); + const last = tokens[tokens.length - 1]; + if (Array.isArray(parent)) { + if (!isIndex(last) || Number(last) >= parent.length) { + throw new PatchError(`${path}: no element ${last}`); + } + return parent.splice(Number(last), 1)[0]; + } + if (!Object.prototype.hasOwnProperty.call(parent, last)) { + throw new PatchError(`${path}: no element ${last}`); + } + const v = parent[last]; + delete parent[last]; + return v; +} + +function equal(a, b) { + return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b)); +} + +function sortKeys(v) { + if (Array.isArray(v)) { + return v.map(sortKeys); + } + if (v && typeof v === 'object') { + const o = {}; + for (const k of Object.keys(v).sort()) { + o[k] = sortKeys(v[k]); + } + return o; + } + return v; +} + +/** + * Apply a JSON Patch to a copy of a document. + * @param {Object} document + * @param {Object[]} patch + * @returns {Object} the patched copy + * @throws {PatchError} + */ +function applyPatch(document, patch) { + if (!Array.isArray(patch)) { + throw new PatchError('A JSON Patch is an array of operations'); + } + let doc = JSON.parse(JSON.stringify(document)); + for (const op of patch) { + if (!op || typeof op !== 'object' || typeof op.op !== 'string' || typeof op.path !== 'string') { + throw new PatchError('Each operation needs op and path'); + } + const clone = (v) => v === undefined ? v : JSON.parse(JSON.stringify(v)); + switch (op.op) { + case 'add': + if (!('value' in op)) { + throw new PatchError(`add ${op.path}: no value`); + } + doc = add(doc, op.path, clone(op.value)); + break; + case 'remove': + remove(doc, op.path); + break; + case 'replace': + if (!('value' in op)) { + throw new PatchError(`replace ${op.path}: no value`); + } + if (parsePointer(op.path).length === 0) { + doc = clone(op.value); + } else { + getValue(doc, op.path); + remove(doc, op.path); + doc = add(doc, op.path, clone(op.value)); + } + break; + case 'move': { + if (op.path.startsWith(op.from + '/')) { + throw new PatchError(`move: ${op.path} is inside ${op.from}`); + } + const v = remove(doc, op.from); + doc = add(doc, op.path, v); + break; + } + case 'copy': + doc = add(doc, op.path, clone(getValue(doc, op.from))); + break; + case 'test': + if (!equal(getValue(doc, op.path), op.value)) { + throw new PatchError(`test ${op.path} failed`); + } + break; + default: + throw new PatchError(`Unknown operation '${op.op}'`); + } + } + return doc; +} + +module.exports = { applyPatch, PatchError, getValue }; diff --git a/rest/operations/operations.js b/rest/operations/operations.js new file mode 100644 index 00000000..465fe7bc --- /dev/null +++ b/rest/operations/operations.js @@ -0,0 +1,198 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The operations: $meta, $meta-add, $meta-delete, and $everything on Patient. + * + * @module rest/operations/operations + */ + +const { badRequest, notFound, gone, notSupported, notAllowed } = require('../library/errors'); +const { TAG, SECURITY, PROFILE, metaTags } = require('../store'); +const { versionHeaders } = require('../interactions/crud'); +const { param } = require('../request'); + +const OPERATIONS = [ + { name: 'meta', definition: 'http://hl7.org/fhir/OperationDefinition/Resource-meta', types: null, system: true, type: true, instance: true, read: true, run: meta }, + { name: 'meta-add', definition: 'http://hl7.org/fhir/OperationDefinition/Resource-meta-add', types: null, system: false, type: false, instance: true, read: false, run: metaAdd }, + { name: 'meta-delete', definition: 'http://hl7.org/fhir/OperationDefinition/Resource-meta-delete', types: null, system: false, type: false, instance: true, read: false, run: metaDelete }, + { name: 'everything', definition: 'http://hl7.org/fhir/OperationDefinition/Patient-everything', types: ['Patient'], system: false, type: false, instance: true, read: true, run: everything } +]; + +/** Find an operation for a request; throws if there is none at that level */ +function findOperation(freq) { + const op = OPERATIONS.find(o => o.name === freq.operation); + if (!op) { + throw notSupported(`The operation $${freq.operation} is not supported`); + } + const level = freq.id ? 'instance' : freq.type ? 'type' : 'system'; + if (!op[level] || (freq.type && op.types && !op.types.includes(freq.type))) { + throw notSupported(`$${freq.operation} can't be used ${level === 'system' ? 'on the endpoint' : level === 'type' ? 'on ' + freq.type : 'on a ' + freq.type}`); + } + if (!op.read && freq.method !== 'POST') { + throw notAllowed(`$${freq.operation} needs POST`); + } + return op; +} + +function metaOf(rows) { + const meta = {}; + for (const r of rows) { + const kind = Number(r.Kind); + if (kind === PROFILE) { + (meta.profile = meta.profile || []).push(r.Code); + } else { + const c = { system: r.TagSystem || undefined, code: r.Code }; + if (r.Display) { + c.display = r.Display; + } + if (kind === TAG) { + (meta.tag = meta.tag || []).push(c); + } else if (kind === SECURITY) { + (meta.security = meta.security || []).push(c); + } + } + } + return meta; +} + +function metaParameters(meta) { + return { resourceType: 'Parameters', parameter: [{ name: 'return', valueMeta: meta }] }; +} + +async function meta(ep, freq, ctx) { + const rows = await ep.inRead(ctx, async (q) => { + if (freq.id) { + const cur = await ep.store.current(q, freq.type, freq.id); + if (!cur) { + throw notFound(`${freq.type}/${freq.id} is not known`); + } + await ep.checkCompartments(q, ctx.access, cur.resourceKey); + return q.all('SELECT DISTINCT t.Kind, t.TagSystem, t.Code, t.Display FROM VersionTags vt JOIN Tags t ON t.TagKey = vt.TagKey WHERE vt.VersionKey = ? ORDER BY t.Kind, t.TagSystem, t.Code', [cur.versionKey]); + } + if (freq.type) { + return q.all(`SELECT DISTINCT t.Kind, t.TagSystem, t.Code, t.Display FROM Ids i JOIN VersionTags vt ON vt.VersionKey = i.MostRecent JOIN Tags t ON t.TagKey = vt.TagKey + WHERE i.TypeKey = ? AND i.Deleted = 0 ORDER BY t.Kind, t.TagSystem, t.Code`, [ep.store.typeKey(freq.type)]); + } + return q.all('SELECT DISTINCT t.Kind, t.TagSystem, t.Code, t.Display FROM Ids i JOIN VersionTags vt ON vt.VersionKey = i.MostRecent JOIN Tags t ON t.TagKey = vt.TagKey WHERE i.Deleted = 0 ORDER BY t.Kind, t.TagSystem, t.Code'); + }); + return { status: 200, resource: metaParameters(metaOf(rows)) }; +} + +function metaInput(freq) { + const b = freq.body; + if (!b || b.resourceType !== 'Parameters') { + throw badRequest('The body must be a Parameters resource with a meta parameter'); + } + const p = (b.parameter || []).find(x => x.name === 'meta'); + if (!p || !p.valueMeta) { + throw badRequest('The Parameters must have a meta parameter (valueMeta)'); + } + return p.valueMeta; +} + +function sameCoding(a, b) { + return (a.system || '') === (b.system || '') && a.code === b.code; +} + +async function changeMeta(ep, freq, ctx, change) { + const input = metaInput(freq); + return ep.inWrite(ctx, async (q) => { + const cur = await ep.store.current(q, freq.type, freq.id); + if (!cur) { + throw notFound(`${freq.type}/${freq.id} is not known`); + } + if (cur.deleted) { + throw gone(`${freq.type}/${freq.id} has been deleted`); + } + await ep.checkCompartments(q, ctx.access, cur.resourceKey); + const resource = cur.resource; + const m = { ...(resource.meta || {}) }; + change(m, input); + for (const k of ['tag', 'security', 'profile']) { + if (Array.isArray(m[k]) && m[k].length === 0) { + delete m[k]; + } + } + resource.meta = m; + await ep.store.rewriteMeta(q, cur, freq.type, resource); + await ep.auditWrite(q, freq, 'operation', 200, `${freq.type}/${freq.id}/_history/${cur.versionId}`, null); + const out = {}; + for (const k of ['tag', 'security', 'profile']) { + if (m[k]) { + out[k] = m[k]; + } + } + return { status: 200, resource: metaParameters(out), headers: versionHeaders(cur) }; + }); +} + +async function metaAdd(ep, freq, ctx) { + return changeMeta(ep, freq, ctx, (m, input) => { + for (const k of ['tag', 'security']) { + for (const c of input[k] || []) { + m[k] = m[k] || []; + if (!m[k].some(x => sameCoding(x, c))) { + m[k].push(c); + } + } + } + for (const p of input.profile || []) { + m.profile = m.profile || []; + if (!m.profile.includes(p)) { + m.profile.push(p); + } + } + }); +} + +async function metaDelete(ep, freq, ctx) { + return changeMeta(ep, freq, ctx, (m, input) => { + for (const k of ['tag', 'security']) { + if (m[k]) { + m[k] = m[k].filter(x => !(input[k] || []).some(c => sameCoding(x, c))); + } + } + if (m.profile) { + m.profile = m.profile.filter(p => !(input.profile || []).includes(p)); + } + }); +} + +/** + * Patient/[id]/$everything: the patient, everything in its compartment, and what those refer + * to; _since, _type and _count as for a search. + */ +async function everything(ep, freq, ctx) { + const exists = await ep.inRead(ctx, q => ep.store.current(q, 'Patient', freq.id)); + if (!exists) { + throw notFound(`Patient/${freq.id} is not known`); + } + if (exists.deleted) { + throw gone(`Patient/${freq.id} has been deleted`); + } + const params = []; + for (const [n, v] of freq.params) { + if (n === '_count' || n === '_type') { + params.push([n, v]); + } else if (n === '_since') { + params.push(['_lastUpdated', 'ge' + v]); + } else if (n === 'start' || n === 'end') { + // clinical dates: not applied yet + } + } + if (param(freq, '_getpages') !== undefined) { + return ep.searcher.search({ ...freq, params: freq.params }, ctx); + } + params.push(['_include', '*']); + const sfreq = { ...freq, type: null, id: null, compartment: { type: 'Patient', id: freq.id }, params, interaction: 'search-system', + segments: freq.segments }; + const r = await ep.searcher.search(sfreq, ctx); + r.resource.type = 'searchset'; + return r; +} + +module.exports = { OPERATIONS, findOperation, metaTags }; diff --git a/rest/request.js b/rest/request.js new file mode 100644 index 00000000..605f1f5a --- /dev/null +++ b/rest/request.js @@ -0,0 +1,268 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * A FHIR request: an HTTP request, or an entry of a batch or transaction Bundle, turned into + * one shape, and the interaction it asks for. + * + * { method, segments, params: [[name, value]...], headers (lower-case names), body, + * interaction, type, id, vid, compartment, operation, principal, ip, base } + * + * The query is parsed here, not by express (whose parser makes objects of a[b]=c): search + * needs the parameters in order, with repeats. + * + * @module rest/request + */ + +const { badRequest, notAllowed } = require('./library/errors'); + +const TYPE_RE = /^[A-Z][A-Za-z]{0,63}$/; + +/** + * Split a relative URL (path and query) into segments and parameters. + * @param {string} url - e.g. "Patient/123/_history?_count=10" + */ +function splitUrl(url) { + const q = url.indexOf('?'); + const pathPart = q >= 0 ? url.substring(0, q) : url; + const query = q >= 0 ? url.substring(q + 1) : ''; + const segments = pathPart.split('/').filter(s => s !== '').map(s => { + try { + return decodeURIComponent(s); + } catch (e) { + throw badRequest(`The URL segment '${s}' is not properly encoded`); + } + }); + return { segments, params: parseQuery(query) }; +} + +/** + * Parse a query string into [name, value] pairs, in order. + * @param {string} query + */ +function parseQuery(query) { + const out = []; + if (!query) { + return out; + } + for (const part of query.split('&')) { + if (!part) { + continue; + } + const eq = part.indexOf('='); + const rawName = eq >= 0 ? part.substring(0, eq) : part; + const rawValue = eq >= 0 ? part.substring(eq + 1) : ''; + try { + out.push([decodeURIComponent(rawName.replace(/\+/g, ' ')), decodeURIComponent(rawValue.replace(/\+/g, ' '))]); + } catch (e) { + throw badRequest(`The query parameter '${rawName}' is not properly encoded`); + } + } + return out; +} + +/** The first value of a parameter, or undefined */ +function param(freq, name) { + const p = freq.params.find(([n]) => n === name); + return p ? p[1] : undefined; +} + +/** + * Work out the interaction from the method and the segments. + * @param {Object} freq - with method, segments, params + */ +function classify(freq) { + const s = freq.segments; + const m = freq.method; + const out = { interaction: null, type: null, id: null, vid: null, compartment: null, operation: null }; + const isOp = (x) => typeof x === 'string' && x.startsWith('$'); + const checkType = (t) => { + if (!TYPE_RE.test(t)) { + throw badRequest(`'${t}' is not a resource type`); + } + return t; + }; + if (s.length === 0) { + if (m === 'POST') { + out.interaction = 'bundle'; + } else if (m === 'GET' || m === 'HEAD') { + out.interaction = 'search-system'; + } + } else if (s.length === 1) { + if (s[0] === 'metadata' && (m === 'GET' || m === 'HEAD')) { + out.interaction = 'capabilities'; + } else if (s[0] === '_history' && (m === 'GET' || m === 'HEAD')) { + out.interaction = 'history-system'; + } else if (s[0] === '_search' && m === 'POST') { + out.interaction = 'search-system'; + } else if (isOp(s[0])) { + out.interaction = 'operation'; + out.operation = s[0].substring(1); + } else { + out.type = checkType(s[0]); + out.interaction = { GET: 'search-type', HEAD: 'search-type', POST: 'create', PUT: 'conditional-update', DELETE: 'conditional-delete', + PATCH: 'conditional-patch' }[m] || null; + } + } else if (s.length === 2) { + out.type = checkType(s[0]); + if (s[1] === '_history' && (m === 'GET' || m === 'HEAD')) { + out.interaction = 'history-type'; + } else if (s[1] === '_search' && m === 'POST') { + out.interaction = 'search-type'; + } else if (isOp(s[1])) { + out.interaction = 'operation'; + out.operation = s[1].substring(1); + } else { + out.id = s[1]; + out.interaction = { GET: 'read', HEAD: 'read', PUT: 'update', PATCH: 'patch', DELETE: 'delete' }[m] || null; + } + } else if (s.length === 3) { + out.type = checkType(s[0]); + out.id = s[1]; + if (s[2] === '_history' && (m === 'GET' || m === 'HEAD')) { + out.interaction = 'history-instance'; + } else if (isOp(s[2])) { + out.interaction = 'operation'; + out.operation = s[2].substring(1); + } else if (m === 'GET' || m === 'HEAD') { + // a compartment search: Patient/123/Observation (or Patient/123/* ) + out.compartment = { type: out.type, id: out.id }; + out.type = s[2] === '*' ? null : checkType(s[2]); + out.id = null; + out.interaction = out.type ? 'search-type' : 'search-system'; + } + } else if (s.length === 4) { + out.type = checkType(s[0]); + out.id = s[1]; + if (s[2] === '_history' && (m === 'GET' || m === 'HEAD')) { + out.vid = s[3]; + out.interaction = 'vread'; + } else if (m === 'POST' && s[3] === '_search') { + out.compartment = { type: out.type, id: out.id }; + out.type = checkType(s[2]); + out.id = null; + out.interaction = 'search-type'; + } + } + if (!out.interaction) { + throw notAllowed(`${m} ${s.join('/') || '/'} is not a FHIR interaction this server knows`); + } + return out; +} + +/** + * A FHIR request from an express request. + * @param {Object} req + * @param {Object|null} body - the parsed body + * @param {Object|null} principal + * @param {string} base - the endpoint's full URL + */ +function fromHttp(req, body, principal, base) { + const url = req.originalUrl.substring(req.baseUrl.length) || '/'; + const { segments, params } = splitUrl(url); + const headers = {}; + for (const [k, v] of Object.entries(req.headers)) { + headers[k.toLowerCase()] = Array.isArray(v) ? v.join(', ') : v; + } + const freq = { method: req.method.toUpperCase(), segments, params, headers, body, principal, ip: req.ip, base, url }; + // a POST _search carries its parameters in the body, as a form + if (req.method === 'POST' && segments[segments.length - 1] === '_search' && typeof req.body === 'string') { + freq.params.push(...parseQuery(req.body)); + freq.body = null; + } else if (req.method === 'POST' && segments[segments.length - 1] === '_search' && Buffer.isBuffer(req.body) && + /x-www-form-urlencoded/.test(headers['content-type'] || '')) { + freq.params.push(...parseQuery(req.body.toString('utf8'))); + freq.body = null; + } + Object.assign(freq, classify(freq)); + return freq; +} + +/** + * A FHIR request from a Bundle entry. + * @param {Object} entry + * @param {Object} parent - the Bundle's request (principal, ip, base, headers) + */ +function fromEntry(entry, parent) { + const r = entry.request || {}; + if (!r.method || !r.url) { + throw badRequest('A Bundle entry needs request.method and request.url'); + } + let url = String(r.url); + if (url.startsWith(parent.base + '/')) { + url = url.substring(parent.base.length + 1); + } + const { segments, params } = splitUrl(url); + const headers = {}; + if (r.ifMatch) { + headers['if-match'] = r.ifMatch; + } + if (r.ifNoneMatch) { + headers['if-none-match'] = r.ifNoneMatch; + } + if (r.ifNoneExist) { + headers['if-none-exist'] = r.ifNoneExist; + } + if (r.ifModifiedSince) { + headers['if-modified-since'] = r.ifModifiedSince; + } + if (parent.headers.prefer) { + headers.prefer = parent.headers.prefer; + } + const freq = { method: String(r.method).toUpperCase(), segments, params, headers, body: entry.resource || null, + principal: parent.principal, ip: parent.ip, base: parent.base, url, inBundle: true }; + if (freq.method === 'PATCH' && entry.resource && entry.resource.resourceType === 'Binary' && entry.resource.data) { + // a JSON Patch in a Bundle comes as a Binary + try { + freq.body = JSON.parse(Buffer.from(entry.resource.data, 'base64').toString('utf8')); + } catch (e) { + throw badRequest('The PATCH entry\'s Binary is not a JSON Patch'); + } + } + Object.assign(freq, classify(freq)); + return freq; +} + +/** The Prefer header's return= value: minimal, representation, OperationOutcome, or null */ +function preferReturn(freq) { + const m = /return=([A-Za-z]+)/.exec(freq.headers.prefer || ''); + return m ? m[1] : null; +} + +/** Prefer: handling=strict */ +function strict(freq) { + return /handling=strict/.test(freq.headers.prefer || ''); +} + +// an ETag is short: anything longer than this isn't one of ours +const MAX_ETAG = 200; + +/** + * The version an ETag names: W/"3", "3" or 3 all give '3'. Parsed by hand, not with a regular + * expression: a header is the client's, and a pattern like \s*"?([^"]*)"?\s* backtracks badly + * on a long run of spaces or tabs. + * @param {string} text + * @returns {string} + */ +function etagVersion(text) { + let s = String(text).substring(0, MAX_ETAG).trim(); + if (s.startsWith('W/')) { + s = s.substring(2); + } + if (s.startsWith('"')) { + const close = s.indexOf('"', 1); + s = close >= 0 ? s.substring(1, close) : s.substring(1); + } + return s; +} + +/** The version in If-Match (W/"3" or "3" or 3), or null */ +function ifMatchVersion(freq) { + const v = freq.headers['if-match']; + return v ? etagVersion(v) : null; +} + +module.exports = { fromHttp, fromEntry, splitUrl, parseQuery, param, classify, preferReturn, strict, ifMatchVersion, etagVersion, TYPE_RE }; diff --git a/rest/rest.js b/rest/rest.js new file mode 100644 index 00000000..7d87f768 --- /dev/null +++ b/rest/rest.js @@ -0,0 +1,141 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The rest module: database-backed FHIR RESTful servers (see rest/README.md). + * + * modules.rest.endpoints lists the endpoints. config.json says only where each one is and + * which database it uses; everything else about an endpoint is in its own database (see + * endpoint/settings.js): + * + * "rest": { + * "enabled": true, + * "endpoints": [ + * { "path": "/fhir/r4", "fhirVersion": "4.0.1", + * "database": { "type": "sqlite", "file": "rest/r4.db" } }, + * { "path": "/fhir/r5", "fhirVersion": "5.0.0", + * "database": { "type": "mysql", "host": "localhost", "database": "fhir_r5", + * "user": "fhirsmith", "passwordEnv": "FHIR_R5_DB_PASSWORD" } } + * ] + * } + * + * Like the tx module, it mounts each endpoint on the app at its path, and runs under the + * cluster: every process serves requests; only the master migrates the schema and runs the + * background jobs. + * + * @module rest/rest + */ + +const rateLimit = require('express-rate-limit'); +const auth = require('../library/auth'); +const folders = require('../library/folder-setup'); +const { PackageManager } = require('../library/package-manager'); +const { Endpoint } = require('./endpoint/endpoint'); +const { MODULE, READ, WRITE, MANAGE } = require('./access'); + +const PACKAGE_SERVERS = ['https://packages2.fhir.org/packages', 'https://packages.fhir.org']; + +class RestModule { + /** + * @param {Object} [stats] - a ModuleStats + * @param {Object} [log] + */ + constructor(stats, log) { + this.stats = stats || null; + this.endpoints = []; + if (log) { + this.log = log; + } else { + const Logger = require('../library/logger'); + this.log = Logger.getInstance().child({ module: 'rest' }); + } + } + + /** + * @param {Object} config - modules.rest + * @param {Function} app - the express app: each endpoint is mounted at its path + * @param {Object} [options] - { hostName, master (default true), maxBody, derived (tests), + * principal (tests: who a request is) } + */ + async initialize(config, app, options = {}) { + this.config = config || {}; + const list = Array.isArray(this.config.endpoints) ? this.config.endpoints : []; + if (!list.length) { + this.log.warn('Rest module: no endpoints configured (modules.rest.endpoints)'); + } + const paths = new Set(); + for (const e of list) { + const p = String(e.path || '').replace(/\/+$/, ''); + if (paths.has(p)) { + throw new Error(`Rest module: two endpoints have the path ${p}`); + } + paths.add(p); + } + const files = new Set(); + for (const e of list) { + const key = e.database && (e.database.type === 'sqlite' ? 'sqlite:' + e.database.file : `mysql:${e.database.host || 'localhost'}:${e.database.port || 3306}/${e.database.database}`); + if (key && files.has(key)) { + throw new Error(`Rest module: two endpoints use the same database (${key}): each endpoint needs its own`); + } + files.add(key); + } + auth.defineRoles(MODULE, [ + { role: READ, label: 'Read', description: 'read, vread, search and history on the endpoint', scope: { label: 'Endpoint', values: () => this.scopeValues() } }, + { role: WRITE, label: 'Write', description: 'create, update, patch, delete, batch and transaction on the endpoint (and read)', scope: { label: 'Endpoint', values: () => this.scopeValues() } }, + { role: MANAGE, label: 'Manage', description: 'the endpoint\'s settings, types, custom search parameters and reindexing', scope: { label: 'Endpoint', values: () => this.scopeValues() } } + ], { title: 'FHIR REST', path: list.length ? list[0].path : '/' }); + + // the package cache is the tx module's: the core packages are often there already + const packageManager = options.derived ? null : new PackageManager(this.config.packageServers || PACKAGE_SERVERS, folders.subDir('terminology-cache')); + for (const e of list) { + const ep = new Endpoint(e, { + databasesDir: folders.databasesDir(), + master: options.master !== false, + log: this.log, + packageManager, + cacheFolder: options.derived ? null : folders.subDir('rest'), + derived: options.derived ? options.derived(e) : null, + app, + hostName: options.hostName, + maxBody: options.maxBody, + stats: this.stats, + principal: options.principal || ((req) => auth.principal(req)) + }); + await ep.open(); + const router = require('express').Router(); + router.use(rateLimit(auth.credentialLimits())); + router.use(ep.router()); + app.use(ep.path, router); + this.endpoints.push(ep); + } + } + + scopeValues() { + return this.endpoints.map(ep => ({ value: ep.path, label: `${ep.path} (${ep.settings ? ep.settings.name : ''})` })); + } + + /** The paths of the endpoints (for the cluster's routing) */ + paths() { + return this.endpoints.map(ep => ep.path); + } + + getStatus() { + return { enabled: true, endpoints: this.endpoints.map(ep => ({ path: ep.path, fhirVersion: ep.settings && ep.settings.fhirVersion, database: ep.cfg.database.type })) }; + } + + async shutdown() { + for (const ep of this.endpoints) { + try { + await ep.close(); + } catch (e) { + this.log.error(`Rest module: closing ${ep.path}: ${e.message}`); + } + } + this.endpoints = []; + } +} + +module.exports = RestModule; diff --git a/rest/search.md b/rest/search.md new file mode 100644 index 00000000..5bd1bbca --- /dev/null +++ b/rest/search.md @@ -0,0 +1,77 @@ +# Search in the rest module + +What an endpoint's search supports: the prefixes, the modifiers for each type of search +parameter, the common parameters, and what is not done yet. See [README.md](README.md) for the +module as a whole. + +An unknown parameter or modifier is ignored, with a warning in the result Bundle (an +OperationOutcome entry, `search.mode` = `outcome`), and left out of the self link. With +`Prefer: handling=strict` it is refused with 400. + +## Prefixes + +On date, number and quantity parameters, and on `_lastUpdated`: `eq` `ne` `gt` `lt` `ge` `le` +`sa` `eb` `ap`. + +- Dates are ranges: a date's precision is the range it covers (`2020` is the whole year), and + a date without a time zone is in the endpoint's time zone (the `timeZone` setting; else the + server's). Each prefix compares the search value's range with the resource's. +- `ne` with several values matches only when none of the resource's values is equal. +- `ap` on dates widens the range by 10% of the distance from now, at least a day; on numbers + and quantities it is ±10% of the value, or the value's precision if that is wider. + +## Modifiers, by type of search parameter + +| Type | Supported | Values | +|---|---|---| +| string | (none): starts with; `:exact`; `:contains`; `:missing` | Accents and case are folded, except for `:exact`. `:text` is accepted, and behaves as the default | +| token | (none); `:not`; `:text`; `:code-text`; `:of-type`; `:below`; `:above`; `:in`; `:not-in`; `:missing` | `code`, `system\|code`, `\|code` (no system), `system\|`. `:text` and `:code-text` are both "starts with" on the display or text. `:of-type` is `system\|code\|value`. `:below` and `:above` use the closure table (kept up to date through the terminology server's `$closure`). `:in` and `:not-in` need the endpoint's `txServer`, and a value set of at most 10,000 codes | +| reference | (none); `:[type]` (e.g. `subject:Patient`); `:identifier`; `:missing` | A bare id, `Type/id`, `Type/id/_history/n`, an absolute URL (a local reference when it is this server's address), a canonical `url\|version` | +| date | prefixes; `:missing` | | +| number | prefixes; `:missing` | The value's precision is its range: `1.5` is [1.45, 1.55) | +| quantity | prefixes; `:missing` | `value`, `value\|system\|code`, `value\|\|code`. With a UCUM code, values are compared in canonical units, so `72\|http://unitsofmeasure.org\|kg` finds `72000 g` | +| uri | (none): exact; `:below`; `:above`; `:contains`; `:missing` | | +| composite | `:missing` | The components' values joined with `$`, matched within one repetition of the element (one component of an Observation, not two) | + +Several values separated by commas are OR'd; a parameter repeated is AND'd. + +## Common parameters + +| Parameter | Supported | +|---|---| +| `_id` | `:not` | +| `_lastUpdated` | prefixes | +| `_tag`, `_security` | `:not`, `:missing` | +| `_profile` | `:below`, `:not`, `:missing` | +| `_list` | the id of a List on the endpoint | +| `_type` | on a search of the whole endpoint | +| `_has` | `_has:Type:reference:parameter=value`, nested up to 3 levels | +| chains | `subject.name=x`, `subject:Patient.name=x`, up to 3 links | +| `_filter` | operators `eq` `ne` `co` `sw` `ew` `gt` `lt` `ge` `le` `ap` `sa` `eb` `pr` `po` `ss` `sb` `in` `ni` `re`; `and`, `or`, `not`, brackets; chains through reference parameters. `sw` on a uri is `:below`; `ss` and `sb` on a token are `:below` and `:above` | + +Compartment searches (`Patient/123/Observation`, `Patient/123/*`) are supported too. + +## Results + +| Parameter | | +|---|---| +| `_sort` | several keys, `-` for descending; by any search parameter but composites, `_id` and `_lastUpdated` | +| `_count` | page size: the endpoint's `defaultCount`, at most its `maxCount` | +| `_total` | `none`, `estimate`, `accurate`. Above `searchMaxResults` (20,000 by default) the total is only given when asked for as `accurate` | +| `_summary` | `true`, `text`, `data`, `count`, `false` | +| `_elements` | the elements to keep (with the mandatory ones) | +| `_include`, `_revinclude` | `Type:parameter`, `Type:parameter:target`, `Type:*`, `*`; `:iterate` (up to 3 rounds, at most 1,000 resources a page) | + +A search that needs more than one page keeps its results (up to `searchMaxResults`) for +`searchKeepMinutes` (30 by default); the paging links are +`[base]?_getpages=[id]&_offset=[n]&_count=[n]`, which any process can serve, but only to the +user who ran the search. + +## Not supported yet + +- `:text-advanced`, and `:text` on references +- `:above` and `:below` on references (canonical version matching) +- `:not` on anything but tokens and `_id`, `_tag`, `_security`, `_profile` +- `:code-text` as it is defined (matching the code's display): it is treated as `:text` +- `_text`, `_content`, `_query`, `_contained`, `_containedType` +- filters on path elements in `_filter` (`name[...]`) diff --git a/rest/search/filter.js b/rest/search/filter.js new file mode 100644 index 00000000..7f318713 --- /dev/null +++ b/rest/search/filter.js @@ -0,0 +1,299 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The _filter parameter: parsed into the same tree as ordinary parameters (parser.js). + * + * filter = expr + * expr = andExpr ("or" andExpr)* + * andExpr = unary ("and" unary)* + * unary = "not" "(" expr ")" | "(" expr ")" | comparison + * comparison = path op value + * path = name ("." name)* a chain through reference parameters + * op = eq ne co sw ew gt lt ge le ap sa eb pr po ss sb in ni re + * value = "quoted string" | token + * + * Filters on path elements (name[filter]) are not supported yet. + * + * @module rest/search/filter + */ + +const { badRequest } = require('../library/errors'); +const { dateRange, numberRange } = require('../../library/fhir-search-values'); +const { normalise } = require('../indexing/values'); + +/** + * A _filter value (already unquoted: every character in it is literal) in the form the search + * parser reads, where a backslash escapes the next character: so backslashes are doubled. A | + * stays a separator (system|code), as it is in _filter. + * @param {string} value + */ +function asSearchValue(value) { + return value.replace(/\\/g, '\\\\'); +} + +const OPS = new Set(['eq', 'ne', 'co', 'sw', 'ew', 'gt', 'lt', 'ge', 'le', 'ap', 'sa', 'eb', 'pr', 'po', 'ss', 'sb', 'in', 'ni', 're']); +const MAX_LENGTH = 4000; + +function tokenise(text) { + const out = []; + let i = 0; + while (i < text.length) { + const c = text[i]; + if (/\s/.test(c)) { + i++; + } else if (c === '(' || c === ')') { + out.push({ t: c }); + i++; + } else if (c === '"') { + let s = ''; + i++; + while (i < text.length && text[i] !== '"') { + if (text[i] === '\\' && i + 1 < text.length) { + s += text[i + 1]; + i += 2; + } else { + s += text[i++]; + } + } + if (i >= text.length) { + throw badRequest('_filter: a quoted value is not closed'); + } + i++; + out.push({ t: 'str', v: s }); + } else { + let s = ''; + while (i < text.length && !/[\s()]/.test(text[i])) { + s += text[i++]; + } + out.push({ t: 'word', v: s }); + } + } + return out; +} + +class FilterParser { + constructor(sp, types, text) { + this.sp = sp; + this.types = types; + if (text.length > MAX_LENGTH) { + throw badRequest(`_filter is limited to ${MAX_LENGTH} characters`); + } + this.tokens = tokenise(text); + this.pos = 0; + } + + peek() { + return this.tokens[this.pos]; + } + + next() { + return this.tokens[this.pos++]; + } + + isWord(tok, w) { + return tok && tok.t === 'word' && tok.v.toLowerCase() === w; + } + + parse() { + const e = this.expr(0); + if (this.pos < this.tokens.length) { + throw badRequest(`_filter: unexpected '${this.peek().v || this.peek().t}'`); + } + return e; + } + + expr(depth) { + if (depth > 20) { + throw badRequest('_filter: nested too deeply'); + } + const items = [this.andExpr(depth)]; + while (this.isWord(this.peek(), 'or')) { + this.next(); + items.push(this.andExpr(depth)); + } + return items.length === 1 ? items[0] : { kind: 'or', items }; + } + + andExpr(depth) { + const items = [this.unary(depth)]; + while (this.isWord(this.peek(), 'and')) { + this.next(); + items.push(this.unary(depth)); + } + return items.length === 1 ? items[0] : { kind: 'and', items }; + } + + unary(depth) { + const tok = this.peek(); + if (!tok) { + throw badRequest('_filter: incomplete expression'); + } + if (this.isWord(tok, 'not') && this.tokens[this.pos + 1] && this.tokens[this.pos + 1].t === '(') { + this.next(); + return { kind: 'not', item: this.group(depth) }; + } + if (tok.t === '(') { + return this.group(depth); + } + return this.comparison(); + } + + group(depth) { + this.next(); + const e = this.expr(depth + 1); + const close = this.next(); + if (!close || close.t !== ')') { + throw badRequest('_filter: missing )'); + } + return e; + } + + comparison() { + const path = this.next(); + const op = this.next(); + const value = this.next(); + if (!path || path.t !== 'word' || !op || op.t !== 'word' || !value || (value.t !== 'word' && value.t !== 'str')) { + throw badRequest('_filter: expected parameter operator value'); + } + if (path.v.includes('[')) { + throw badRequest('_filter: filters on path elements ([...]) are not supported yet'); + } + const o = op.v.toLowerCase(); + if (!OPS.has(o)) { + throw badRequest(`_filter: unknown operator '${op.v}'`); + } + return this.compare(this.types, path.v, o, value.v, 0); + } + + compare(types, path, op, value, depth) { + const sp = this.sp; + const dot = path.indexOf('.'); + if (dot > 0) { + if (depth >= 3) { + throw badRequest('_filter: chains are limited to 3 links'); + } + const code = path.substring(0, dot); + const l = sp.lookup(types, code); + if (!l || l.spType !== 'reference') { + throw badRequest(`_filter: '${code}' is not a reference parameter`); + } + const rest = path.substring(dot + 1); + const nextCode = rest.split('.')[0]; + let targets = [...new Set(l.defs.flatMap(d => d.target || []))].filter(t => sp.ep.typeKeys.has(t)); + if (!nextCode.startsWith('_')) { + targets = targets.filter(t => sp.defs.param(t, nextCode)); + } + if (!targets.length) { + throw badRequest(`_filter: none of the targets of ${code} has a parameter '${nextCode}'`); + } + return { kind: 'chain', keys: l.keys, targetTypes: null, inner: this.compare(targets, rest, op, value, depth + 1) }; + } + if (path === '_id') { + if (op !== 'eq' && op !== 'ne') { + throw badRequest(`_filter: _id takes eq or ne, not ${op}`); + } + return { kind: 'id', ids: [value], negate: op === 'ne' }; + } + if (path === '_lastUpdated') { + const r = dateRange(value, sp.ep.timeZone); + if (!r) { + throw badRequest(`_filter: '${value}' is not a date`); + } + return { kind: 'lastUpdated', values: [{ prefix: op === 'po' ? 'ap' : op, range: r }] }; + } + if (path === '_tag' || path === '_security' || path === '_profile') { + if (op !== 'eq' && op !== 'ne') { + throw badRequest(`_filter: ${path} takes eq or ne`); + } + return sp.tagNode(path, op === 'ne' ? 'not' : null, value); + } + const l = sp.lookup(types, path); + if (!l) { + throw badRequest(`_filter: unknown search parameter '${path}'`); + } + l.keys.forEach(k => sp.keysUsed.add(k)); + if (op === 'pr') { + return { kind: 'missing', spType: l.spType, keys: l.keys, missing: value === 'false' }; + } + const node = (values, modifier = null) => ({ kind: 'param', spType: l.spType, keys: l.keys, defs: l.defs, modifier, values, code: path }); + const negate = op === 'ne'; + switch (l.spType) { + case 'string': { + const norm = normalise(value).substring(0, 255); + const mode = { eq: 'eqnorm', ne: 'eqnorm', co: 'contains', sw: 'start', ew: 'end', gt: 'gt', lt: 'lt', ge: 'ge', le: 'le' }[op]; + if (!mode) { + throw badRequest(`_filter: ${op} can't be used on the string parameter ${path}`); + } + return node([{ mode, text: value, norm, negate }]); + } + case 'token': { + if (op === 'in' || op === 'ni') { + return node([{ mode: 'in', valueSet: value, negate: op === 'ni' }]); + } + const v = sp.tokenValue(op === 'ss' ? 'below' : op === 'sb' ? 'above' : null, asSearchValue(value)); + if (!['eq', 'ne', 'ss', 'sb'].includes(op)) { + throw badRequest(`_filter: ${op} can't be used on the token parameter ${path}`); + } + v.negate = negate; + return node([v]); + } + case 'date': { + const r = dateRange(value, sp.ep.timeZone); + if (!r) { + throw badRequest(`_filter: '${value}' is not a date`); + } + const prefix = op === 'po' ? 'ap' : op === 'ne' ? 'eq' : op; + if (!['eq', 'gt', 'lt', 'ge', 'le', 'ap', 'sa', 'eb'].includes(prefix)) { + throw badRequest(`_filter: ${op} can't be used on the date parameter ${path}`); + } + const range = op === 'ap' ? require('../../library/fhir-search-values').approxDateRange(r) : r; + return node([{ prefix, range, negate }]); + } + case 'number': + case 'quantity': { + const parts = value.split('|'); + const r = numberRange(parts[0]); + if (!r) { + throw badRequest(`_filter: '${value}' is not a number`); + } + const prefix = op === 'ne' ? 'eq' : op; + if (!['eq', 'gt', 'lt', 'ge', 'le', 'ap', 'sa', 'eb'].includes(prefix)) { + throw badRequest(`_filter: ${op} can't be used on ${path}`); + } + return node([{ prefix, ...r, system: parts[1] || null, unit: parts.slice(2).join('|') || null, negate }]); + } + case 'reference': { + if (!['eq', 'ne', 're'].includes(op)) { + throw badRequest(`_filter: ${op} can't be used on the reference parameter ${path}`); + } + const v = sp.referenceValue(l, null, asSearchValue(value)); + v.negate = negate; + return node([v]); + } + case 'uri': { + const mode = { eq: 'eq', ne: 'eq', co: 'contains', sw: 'below', ss: 'above', sb: 'below' }[op]; + if (!mode) { + throw badRequest(`_filter: ${op} can't be used on the uri parameter ${path}`); + } + return node([{ mode, value, negate }]); + } + } + throw badRequest(`_filter: ${path} (${l.spType}) can't be used in _filter`); + } +} + +/** + * Parse _filter into a search tree node. + * @param {import('./parser').SearchParser} sp + * @param {string[]} types + * @param {string} text + */ +function parseFilter(sp, types, text) { + return new FilterParser(sp, types, text).parse(); +} + +module.exports = { parseFilter, tokenise, asSearchValue }; diff --git a/rest/search/parser.js b/rest/search/parser.js new file mode 100644 index 00000000..0b895233 --- /dev/null +++ b/rest/search/parser.js @@ -0,0 +1,538 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Parse search parameters into a tree. Ordinary parameters and _filter produce the same tree, + * so there is one SQL generator (sql.js). + * + * Nodes: + * { kind: 'and', items } { kind: 'or', items } { kind: 'not', item } { kind: 'none' } + * { kind: 'param', spType, keys, modifier, values, code } values OR'd; a value can be + * negated (ne, :not) - see sql.js + * { kind: 'missing', spType, keys, missing: boolean } + * { kind: 'chain', keys, targetType, inner } a reference to a resource that matches inner + * { kind: 'has', typeKey, keys, inner } a resource of the type refers to this one + * { kind: 'id', ids, negate } { kind: 'lastUpdated', values } + * { kind: 'tag', tagKind, values, negate } { kind: 'list', id } + * { kind: 'compartment', type, id } + * + * keys: the ParamKeys of the parameter across the types searched (a code can belong to a + * different definition on each type). + * + * @module rest/search/parser + */ + +const { badRequest } = require('../library/errors'); +const { dateRange, approxDateRange, numberRange, splitPrefix, PREFIXES } = require('../../library/fhir-search-values'); +const { normalise, parseReference } = require('../indexing/values'); +const { TAG, SECURITY, PROFILE, PROFILE_SYSTEM } = require('../store'); + +const MAX_CHAIN = 3; +const MAX_HAS = 3; + +// the result parameters: not criteria +const CONTROL = new Set(['_sort', '_count', '_include', '_revinclude', '_summary', '_elements', '_total', '_format', '_pretty', + '_contained', '_containedType', '_getpages', '_offset']); + +const MODIFIERS = { + string: ['exact', 'contains', 'missing', 'text'], + token: ['text', 'not', 'missing', 'below', 'above', 'in', 'not-in', 'of-type', 'code-text'], + date: ['missing'], + number: ['missing'], + quantity: ['missing'], + reference: ['missing', 'identifier', 'type'], + uri: ['missing', 'below', 'above', 'contains'], + composite: ['missing'] +}; + +class Unsupported extends Error {} + +/** + * Split a value at unescaped separators ($ for composites, | for tokens). + */ +function splitEscaped(s, sep) { + const out = []; + let cur = ''; + for (let i = 0; i < s.length; i++) { + if (s[i] === '\\' && i + 1 < s.length && (s[i + 1] === sep || s[i + 1] === '\\' || s[i + 1] === ',' || s[i + 1] === '$' || s[i + 1] === '|')) { + cur += s[i + 1]; + i++; + } else if (s[i] === sep) { + out.push(cur); + cur = ''; + } else { + cur += s[i]; + } + } + out.push(cur); + return out; +} + +/** Split on commas that aren't escaped, keeping the escapes for the next split */ +function splitOr(value) { + const out = []; + let cur = ''; + for (let i = 0; i < value.length; i++) { + const c = value[i]; + if (c === '\\' && i + 1 < value.length) { + if (value[i + 1] === ',') { + cur += ','; + } else { + cur += c + value[i + 1]; + } + i++; + } else if (c === ',') { + out.push(cur); + cur = ''; + } else { + cur += c; + } + } + out.push(cur); + return out.filter(v => v.length > 0); +} + +function unescape(s) { + return s.replace(/\\([\\,$|])/g, '$1'); +} + +class SearchParser { + /** + * @param {Object} ep - the Endpoint (definitions, typeKeys, timeZone, base) + */ + constructor(ep) { + this.ep = ep; + this.defs = ep.definitions; + } + + /** + * The ParamKeys and definitions for a code across types. + * @returns {{keys: number[], defs: Object[], spType: string}|null} + */ + lookup(types, code) { + const defs = []; + for (const t of types) { + const d = this.defs.param(t, code); + if (d && d.key !== null && d.key !== undefined && !defs.includes(d)) { + defs.push(d); + } + } + if (defs.length === 0) { + return null; + } + const spType = defs[0].type; + const same = defs.filter(d => d.type === spType); + return { keys: same.map(d => d.key), defs: same, spType }; + } + + /** + * Parse the parameters. + * @param {Object} p + * @param {string[]} p.types - the types searched + * @param {Array<[string, string]>} p.params + * @param {boolean} [p.strict] - an unknown parameter or modifier is an error + * @returns {{criteria: Object, control: Object, used: Array, ignored: string[], warnings: string[], keysUsed: Set}} + */ + parse(p) { + const items = []; + const used = []; + const ignored = []; + const warnings = []; + this.keysUsed = new Set(); + const control = { sort: [], include: [], revinclude: [], count: null, total: null, summary: null, elements: null }; + for (const [name, value] of p.params) { + const base = name.split(':')[0].split('.')[0]; + if (CONTROL.has(base)) { + this.parseControl(control, name, value, p.types); + if (base !== '_getpages' && base !== '_offset' && base !== '_format') { + used.push([name, value]); + } + continue; + } + if (base === '_type') { + // handled by the caller + used.push([name, value]); + continue; + } + try { + const node = this.criterion(p.types, name, value, 0); + if (node) { + items.push(node); + used.push([name, value]); + } + } catch (e) { + if (e instanceof Unsupported) { + if (p.strict) { + throw badRequest(e.message); + } + ignored.push(name); + warnings.push(e.message + ': ignored'); + } else { + throw e; + } + } + } + for (const k of this.keysUsed) { + const def = [...this.defs.byUrl.values()].find(d => d.key === k); + if (def && this.defs.reindexing && this.defs.reindexing.has(def.url)) { + warnings.push(`The search parameter ${def.code} is being reindexed: results may be incomplete`); + } + } + return { criteria: { kind: 'and', items }, control, used, ignored, warnings }; + } + + parseControl(control, name, value, types) { + const [base, modifier] = name.split(':'); + switch (base) { + case '_count': + if (!/^\d+$/.test(value)) { + throw badRequest(`_count must be a number, not '${value}'`); + } + control.count = Number(value); + break; + case '_total': + if (!['none', 'estimate', 'accurate'].includes(value)) { + throw badRequest(`_total is none, estimate or accurate, not '${value}'`); + } + control.total = value; + break; + case '_summary': + if (!['true', 'false', 'text', 'data', 'count'].includes(value)) { + throw badRequest(`_summary is true, false, text, data or count, not '${value}'`); + } + control.summary = value; + break; + case '_elements': + control.elements = (control.elements || []).concat(value.split(',').map(s => s.trim()).filter(s => s)); + break; + case '_sort': + for (const s of value.split(',').map(x => x.trim()).filter(x => x)) { + const desc = s.startsWith('-'); + const code = desc ? s.substring(1) : s; + if (code === '_id' || code === '_lastUpdated') { + control.sort.push({ code, desc }); + } else { + const l = this.lookup(types, code); + if (!l || l.spType === 'composite') { + throw badRequest(`Can't sort by '${code}': it isn't a search parameter of ${types.length === 1 ? types[0] : 'these types'}`); + } + control.sort.push({ code, desc, keys: l.keys, spType: l.spType }); + } + } + break; + case '_include': + case '_revinclude': { + const iterate = modifier === 'iterate' || modifier === 'recurse'; + const list = base === '_include' ? control.include : control.revinclude; + if (value === '*') { + list.push({ all: true, iterate }); + break; + } + const parts = value.split(':'); + if (parts.length < 2) { + throw badRequest(`${base} is Type:parameter[:targetType], not '${value}'`); + } + const [srcType, code, target] = parts; + if (!this.ep.typeKeys.has(srcType)) { + throw badRequest(`${base}: unknown type ${srcType}`); + } + if (code === '*') { + list.push({ srcType, all: true, target: target || null, iterate }); + break; + } + const d = this.defs.param(srcType, code); + if (!d || d.type !== 'reference' || d.key === null) { + throw badRequest(`${base}: ${srcType} has no reference parameter '${code}'`); + } + list.push({ srcType, key: d.key, target: target || null, iterate }); + break; + } + default: + break; + } + } + + /** + * One parameter (name[:modifier][.chain] = value) as a node. + */ + criterion(types, name, value, depth) { + if (name.startsWith('_has:')) { + return this.has(types, name, value, depth); + } + const dot = name.indexOf('.'); + if (dot > 0) { + return this.chain(types, name.substring(0, dot), name.substring(dot + 1), value, depth); + } + const colon = name.indexOf(':'); + const code = colon >= 0 ? name.substring(0, colon) : name; + const modifier = colon >= 0 ? name.substring(colon + 1) : null; + switch (code) { + case '_id': + return this.idNode(value, modifier); + case '_lastUpdated': + if (modifier && modifier !== 'missing') { + throw new Unsupported(`_lastUpdated:${modifier} is not supported`); + } + if (modifier === 'missing') { + return value === 'true' ? { kind: 'none' } : null; + } + return { kind: 'lastUpdated', values: splitOr(value).map(v => this.dateValue(v)) }; + case '_tag': + case '_security': + case '_profile': + return this.tagNode(code, modifier, value); + case '_list': + return { kind: 'list', id: value }; + case '_filter': + return require('./filter').parseFilter(this, types, value); + case '_text': + case '_content': + case '_query': + throw new Unsupported(`${code} is not supported yet`); + default: + break; + } + const l = this.lookup(types, code); + if (!l) { + throw new Unsupported(`Unknown search parameter '${code}' for ${types.length === 1 ? types[0] : types.length + ' types'}`); + } + l.keys.forEach(k => this.keysUsed.add(k)); + if (modifier === 'missing') { + if (value !== 'true' && value !== 'false') { + throw badRequest(`${name} is true or false, not '${value}'`); + } + return { kind: 'missing', spType: l.spType, keys: l.keys, missing: value === 'true' }; + } + if (l.spType === 'reference' && modifier && modifier !== 'identifier' && modifier !== 'missing') { + // :[type] + if (!this.ep.typeKeys.has(modifier)) { + throw new Unsupported(`Unknown modifier or type '${modifier}' on ${code}`); + } + } else if (modifier && !(MODIFIERS[l.spType] || []).includes(modifier)) { + throw new Unsupported(`The modifier :${modifier} is not supported on ${code} (a ${l.spType} parameter)`); + } + const values = splitOr(value).map(v => this.value(l, modifier, v, code)); + return { kind: 'param', spType: l.spType, keys: l.keys, defs: l.defs, modifier, values, code }; + } + + idNode(value, modifier) { + if (modifier && modifier !== 'not' && modifier !== 'missing') { + throw new Unsupported(`_id:${modifier} is not supported`); + } + if (modifier === 'missing') { + return value === 'true' ? { kind: 'none' } : null; + } + return { kind: 'id', ids: splitOr(value).map(unescape), negate: modifier === 'not' }; + } + + tagNode(code, modifier, value) { + if (modifier && modifier !== 'not' && modifier !== 'missing' && !(code === '_profile' && (modifier === 'below'))) { + throw new Unsupported(`${code}:${modifier} is not supported`); + } + const tagKind = code === '_tag' ? TAG : code === '_security' ? SECURITY : PROFILE; + if (modifier === 'missing') { + return { kind: 'tagMissing', tagKind, missing: value === 'true' }; + } + const values = splitOr(value).map(v => { + if (tagKind === PROFILE) { + return { system: PROFILE_SYSTEM, code: unescape(v), below: modifier === 'below' }; + } + const parts = splitEscaped(v, '|'); + if (parts.length === 1) { + return { system: undefined, code: parts[0] }; + } + return { system: parts[0], code: parts.slice(1).join('|') || undefined }; + }); + return { kind: 'tag', tagKind, values, negate: modifier === 'not' }; + } + + dateValue(v) { + const { prefix, rest } = splitPrefix(v); + let range = dateRange(rest, this.ep.timeZone); + if (!range) { + throw badRequest(`'${v}' is not a valid date search value`); + } + if (prefix === 'ap') { + range = approxDateRange(range); + } + return { prefix, range }; + } + + /** + * A value for a parameter, by type and modifier. + */ + value(l, modifier, v, code) { + switch (l.spType) { + case 'string': { + const text = unescape(v); + return { mode: modifier === 'exact' ? 'exact' : modifier === 'contains' ? 'contains' : 'start', text, norm: normalise(text).substring(0, 255) }; + } + case 'token': + return this.tokenValue(modifier, v); + case 'date': + return this.dateValue(v); + case 'number': { + const { prefix, rest } = splitPrefix(v); + const r = numberRange(rest); + if (!r) { + throw badRequest(`'${v}' is not a valid number search value for ${code}`); + } + return { prefix, ...r }; + } + case 'quantity': { + const { prefix, rest } = splitPrefix(v); + const parts = splitEscaped(rest, '|'); + const r = numberRange(parts[0]); + if (!r) { + throw badRequest(`'${v}' is not a valid quantity search value for ${code}`); + } + return { prefix, ...r, system: parts.length > 1 ? parts[1] || null : null, unit: parts.length > 2 ? parts.slice(2).join('|') || null : null }; + } + case 'reference': + return this.referenceValue(l, modifier, v); + case 'uri': + return { mode: modifier === 'below' ? 'below' : modifier === 'above' ? 'above' : modifier === 'contains' ? 'contains' : 'eq', value: unescape(v) }; + case 'composite': + return this.compositeValue(l, v, code); + } + throw new Unsupported(`Search parameters of type ${l.spType} are not supported`); + } + + tokenValue(modifier, v) { + if (modifier === 'text' || modifier === 'code-text') { + return { mode: 'text', norm: normalise(unescape(v)).substring(0, 255) }; + } + if (modifier === 'in' || modifier === 'not-in') { + return { mode: 'in', valueSet: unescape(v), negate: modifier === 'not-in' }; + } + const parts = splitEscaped(v, '|'); + if (modifier === 'of-type') { + if (parts.length !== 3) { + throw badRequest(`:of-type takes system|code|value, not '${v}'`); + } + return { mode: 'of-type', typeSystem: parts[0], typeCode: parts[1], code: parts[2] }; + } + let system; + let code; + if (parts.length === 1) { + code = parts[0]; + } else { + system = parts[0] === '' ? null : parts[0]; + code = parts.slice(1).join('|') || undefined; + } + const mode = modifier === 'below' ? 'below' : modifier === 'above' ? 'above' : 'code'; + if ((mode === 'below' || mode === 'above') && (!system || !code)) { + throw badRequest(`:${mode} needs a system and a code (system|code)`); + } + return { mode, system, code, negate: modifier === 'not' }; + } + + referenceValue(l, modifier, v) { + const text = unescape(v); + if (modifier === 'identifier') { + const parts = splitEscaped(v, '|'); + return parts.length === 1 ? { mode: 'identifier', system: undefined, value: parts[0] } + : { mode: 'identifier', system: parts[0] || null, value: parts.slice(1).join('|') }; + } + const typed = modifier && modifier !== 'missing' ? modifier : null; + if (!text.includes('/') && !text.includes(':')) { + // a bare id: of the :type, or any of the parameter's target types + return { mode: 'local', type: typed, id: text }; + } + const p = parseReference(text, [this.ep.baseUrl].filter(x => x)); + if (!p) { + throw badRequest(`'${v}' is not a reference`); + } + if (p.local) { + if (typed && p.type !== typed) { + return { mode: 'nothing' }; + } + return { mode: 'local', type: p.type, id: p.id, version: p.version }; + } + return { mode: 'url', url: p.url, urlVersion: p.urlVersion }; + } + + compositeValue(l, v, code) { + const def = l.defs[0]; + const parts = splitEscaped(v, '$'); + if (parts.length !== def.component.length) { + throw badRequest(`${code} takes ${def.component.length} values separated by $, not '${v}'`); + } + const comps = def.component.map((c, i) => { + const cdef = this.defs.byUrl.get(c.definition); + if (!cdef) { + throw new Unsupported(`The component ${c.definition} of ${code} is not known`); + } + return { spType: cdef.type, value: this.value({ spType: cdef.type, keys: [], defs: [cdef] }, null, parts[i], code) }; + }); + return { comps }; + } + + /** + * subject.name=x, subject:Patient.name=x: the reference must point at a resource that + * matches the rest. + */ + chain(types, head, rest, value, depth) { + if (depth >= MAX_CHAIN) { + throw badRequest(`Chains are limited to ${MAX_CHAIN} links`); + } + const [code, targetType] = head.split(':'); + const l = this.lookup(types, code); + if (!l || l.spType !== 'reference') { + throw new Unsupported(`'${code}' is not a reference parameter, so it can't be chained`); + } + l.keys.forEach(k => this.keysUsed.add(k)); + let targets; + if (targetType) { + if (!this.ep.typeKeys.has(targetType)) { + throw badRequest(`Unknown type ${targetType} in ${head}`); + } + targets = [targetType]; + } else { + targets = [...new Set(l.defs.flatMap(d => d.target || []))].filter(t => this.ep.typeKeys.has(t)); + if (targets.length === 0) { + targets = [...this.ep.typeKeys.keys()]; + } + // only the targets that have the next parameter + const nextCode = rest.split('.')[0].split(':')[0]; + if (!nextCode.startsWith('_')) { + const withIt = targets.filter(t => this.defs.param(t, nextCode)); + if (withIt.length === 0) { + throw new Unsupported(`None of the targets of ${code} has a search parameter '${nextCode}'`); + } + targets = withIt; + } + } + const inner = this.criterion(targets, rest, value, depth + 1); + return { kind: 'chain', keys: l.keys, targetTypes: targetType ? [targetType] : null, inner }; + } + + /** + * _has:Observation:patient:code=x - an Observation whose patient is this resource, with code x. + */ + has(types, name, value, depth) { + if (depth >= MAX_HAS) { + throw badRequest(`_has is limited to ${MAX_HAS} levels`); + } + const m = /^_has:([A-Za-z]+):([^:]+):(.+)$/.exec(name); + if (!m) { + throw badRequest(`_has is _has:Type:reference:parameter, not '${name}'`); + } + const [, type, ref, rest] = m; + if (!this.ep.typeKeys.has(type)) { + throw badRequest(`Unknown type ${type} in ${name}`); + } + const d = this.defs.param(type, ref); + if (!d || d.type !== 'reference' || d.key === null) { + throw badRequest(`${type} has no reference parameter '${ref}'`); + } + this.keysUsed.add(d.key); + const inner = this.criterion([type], rest, value, depth + 1); + return { kind: 'has', typeKey: this.ep.typeKeys.get(type), keys: [d.key], inner }; + } +} + +module.exports = { SearchParser, Unsupported, splitOr, splitEscaped, unescape, CONTROL, PREFIXES }; diff --git a/rest/search/search.js b/rest/search/search.js new file mode 100644 index 00000000..9b3da379 --- /dev/null +++ b/rest/search/search.js @@ -0,0 +1,395 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Search: parse (parser.js), build one query over Ids (sql.js), run it once sorted, and + * keep the matching keys in SearchEntries when they need more than one page. Any process can + * serve any page, since the results are in the database; a page is only served to the user + * who ran the search. + * + * Paging links are [base]?_getpages=[id]&_offset=[n]&_count=[n]. A page shows each + * resource's current version; one deleted since the search ran is left out. + * + * @module rest/search/search + */ + +const crypto = require('crypto'); +const { SearchParser } = require('./parser'); +const { SqlBuilder } = require('./sql'); +const { badRequest, notFound, FhirError } = require('../library/errors'); +const { param, strict } = require('../request'); + +// the most resources _include and _revinclude add to one page +const MAX_INCLUDES = 1000; +const INCLUDE_ROUNDS = 3; + +const SORT_COLUMNS = { + string: ['IndexStrings', 'Norm', 'Norm'], + token: ['IndexTokens', 'Code', 'Code'], + date: ['IndexDates', 'Lo', 'Hi'], + number: ['IndexNumbers', 'Value', 'Value'], + quantity: ['IndexQuantities', 'Value', 'Value'], + reference: ['IndexReferences', 'TargetId', 'TargetId'], + uri: ['IndexUris', 'Value', 'Value'] +}; + +function newSearchId() { + return crypto.randomBytes(16).toString('base64url').substring(0, 22); +} + +function userIdOf(principal) { + return principal ? String(principal.id ?? principal.login) : null; +} + +function queryString(params) { + return params.map(([n, v]) => `${encodeURIComponent(n)}=${encodeURIComponent(v)}`).join('&'); +} + +class Searcher { + constructor(ep) { + this.ep = ep; + } + + /** The types a request searches */ + typesFor(freq) { + const ep = this.ep; + let types; + if (freq.type) { + ep.checkType(freq.type, 'search-type'); + types = [freq.type]; + } else { + const t = freq.params.filter(([n]) => n === '_type').flatMap(([, v]) => v.split(',')).map(s => s.trim()).filter(s => s); + if (t.length) { + for (const x of t) { + ep.checkType(x, 'search-type'); + } + types = [...new Set(t)]; + } else { + types = [...ep.typeKeys.keys()].filter(x => ep.typeSupported(x)); + } + } + if (freq.compartment) { + const c = ep.definitions.compartments.get(freq.compartment.type); + if (!c) { + throw badRequest(`${freq.compartment.type} is not a compartment`); + } + if (freq.type && !c.has(freq.type) && freq.type !== freq.compartment.type) { + throw badRequest(`${freq.type} is not in the ${freq.compartment.type} compartment`); + } + types = types.filter(t => c.has(t) || t === freq.compartment.type); + } + return types; + } + + /** + * Parse and build the condition for a search. + * @returns {Promise<{where: string, args: Array, parsed: Object, types: string[]}>} + */ + async prepare(q, types, params, options) { + const ep = this.ep; + const parsed = new SearchParser(ep).parse({ types, params, strict: options.strict }); + const items = [...parsed.criteria.items]; + if (options.compartment) { + items.push({ kind: 'compartment', type: options.compartment.type, id: options.compartment.id }); + } + const b = new SqlBuilder(ep, q); + const crit = await b.build({ kind: 'and', items }, 'i.ResourceKey'); + const where = ['i.Deleted = 0', 'i.MostRecent IS NOT NULL']; + const args = []; + const all = [...ep.typeKeys.keys()].filter(t => ep.typeSupported(t)); + if (types.length < all.length) { + if (types.length === 0) { + where.push('1 = 0'); + } else { + where.push(`i.TypeKey IN (${types.map(() => '?').join(', ')})`); + args.push(...types.map(t => ep.typeKeys.get(t))); + } + } + if (crit.sql !== '1 = 1') { + where.push(crit.sql); + args.push(...crit.args); + } + const comp = ep.compartmentFilter(options.access, 'i.ResourceKey'); + if (comp) { + where.push(comp.sql); + args.push(...comp.args); + } + return { where: where.join(' AND '), args, parsed, types }; + } + + orderBy(sort) { + const parts = []; + for (const s of sort) { + const dir = s.desc ? 'DESC' : 'ASC'; + if (s.code === '_id') { + parts.push(`i.Id ${dir}`); + } else if (s.code === '_lastUpdated') { + parts.push(`(SELECT sv.LastUpdated FROM Versions sv WHERE sv.VersionKey = i.MostRecent) ${dir}`); + } else { + const [table, asc, desc] = SORT_COLUMNS[s.spType]; + const col = s.desc ? `MAX(so.${desc})` : `MIN(so.${asc})`; + // the keys are numbers from the database: safe to put in the SQL + parts.push(`(SELECT ${col} FROM ${table} so WHERE so.ResourceKey = i.ResourceKey AND so.ParamKey IN (${s.keys.map(Number).join(', ')})) ${dir}`); + } + } + parts.push('i.ResourceKey ASC'); + return 'ORDER BY ' + parts.join(', '); + } + + /** + * The keys of the resources matching criteria (conditional interactions). + * @returns {Promise} + */ + async matchKeys(q, type, params, options = {}) { + const p = await this.prepare(q, [type], params, { access: options.access, strict: options.strict }); + if (p.parsed.used.length === 0 && p.parsed.criteria.items.length === 0) { + throw badRequest('The search criteria have no parameters this server knows'); + } + const rows = await q.all(`SELECT i.ResourceKey FROM Ids i WHERE ${p.where} ORDER BY i.ResourceKey LIMIT ${Number(options.limit || 2)}`, p.args); + return rows.map(r => Number(r.ResourceKey)); + } + + /** + * A search interaction. + */ + async search(freq, ctx) { + const ep = this.ep; + if (param(freq, '_getpages') !== undefined) { + return this.page(freq, ctx); + } + const types = this.typesFor(freq); + const max = ep.settings.searchMaxResults; + const prepared = await ep.inRead(ctx, async (q) => { + const p = await this.prepare(q, types, freq.params, { access: ctx.access, strict: strict(freq), compartment: freq.compartment }); + const control = p.parsed.control; + const count = control.count === null ? ep.settings.defaultCount : Math.min(control.count, ep.settings.maxCount); + if (control.summary === 'count' || count === 0) { + const row = await q.get(`SELECT COUNT(*) AS N FROM Ids i WHERE ${p.where}`, p.args); + return { p, count, keys: [], total: Number(row.N), countOnly: true }; + } + const rows = await q.all(`SELECT i.ResourceKey FROM Ids i WHERE ${p.where} ${this.orderBy(control.sort)} LIMIT ${max + 1}`, p.args); + let keys = rows.map(r => Number(r.ResourceKey)); + let total = null; + const truncated = keys.length > max; + if (truncated) { + keys = keys.slice(0, max); + if (control.total === 'accurate') { + const row = await q.get(`SELECT COUNT(*) AS N FROM Ids i WHERE ${p.where}`, p.args); + total = Number(row.N); + } + } else if (control.total !== 'none') { + total = keys.length; + } + return { p, count, keys, total, truncated }; + }); + const { p, count, keys, total } = prepared; + const warnings = [...p.parsed.warnings]; + if (prepared.truncated) { + warnings.push(`The search matched more than ${max} resources: only the first ${max} can be paged through`); + } + const control = p.parsed.control; + const self = this.selfLink(freq, p.parsed.used, types); + if (prepared.countOnly) { + const bundle = { resourceType: 'Bundle', type: 'searchset', total: prepared.total, link: [{ relation: 'self', url: self }] }; + if (warnings.length) { + bundle.entry = [this.outcomeEntry(warnings)]; + } + return { status: 200, resource: bundle }; + } + let searchId = null; + if (keys.length > count) { + searchId = newSearchId(); + const stored = { types, used: p.parsed.used, control: { include: control.include, revinclude: control.revinclude, summary: control.summary, elements: control.elements }, + self, warnings: p.parsed.warnings }; + await ep.inWrite(ctx, async (q) => { + const now = Date.now(); + const r = await q.run('INSERT INTO Searches (SearchId, Query, Total, StoredCount, UserId, Created, Expires) VALUES (?, ?, ?, ?, ?, ?, ?)', + [searchId, JSON.stringify(stored), total, keys.length, userIdOf(freq.principal), now, now + ep.settings.searchKeepMinutes * 60000]); + const sk = Number(r.lastId); + for (let i = 0; i < keys.length; i += 500) { + const c = keys.slice(i, i + 500); + await q.run('INSERT INTO SearchEntries (SearchKey, Pos, ResourceKey) VALUES ' + c.map(() => '(?, ?, ?)').join(', '), + c.flatMap((k, j) => [sk, i + j, k])); + } + }); + } + return this.buildPage(freq, ctx, { keys: keys.slice(0, count), offset: 0, count, stored: keys.length, total, searchId, self, + control, warnings }); + } + + selfLink(freq, used, types) { + const path = freq.segments.filter(s => s !== '_search').map(encodeURIComponent).join('/'); + const params = [...used]; + if (!freq.type && !params.some(([n]) => n === '_type') && freq.params.some(([n]) => n === '_type')) { + params.push(['_type', types.join(',')]); + } + const qs = queryString(params); + return `${freq.base}${path ? '/' + path : ''}${qs ? '?' + qs : ''}`; + } + + /** A later page of a stored search */ + async page(freq, ctx) { + const ep = this.ep; + const id = param(freq, '_getpages'); + const offsetText = param(freq, '_offset') || '0'; + const countText = param(freq, '_count'); + if (!/^\d+$/.test(offsetText) || (countText !== undefined && !/^\d+$/.test(countText))) { + throw badRequest('_offset and _count must be numbers'); + } + const offset = Number(offsetText); + const count = Math.min(countText === undefined ? ep.settings.defaultCount : Number(countText), ep.settings.maxCount) || ep.settings.defaultCount; + const found = await ep.inRead(ctx, async (q) => { + const s = await q.get('SELECT SearchKey, Query, Total, StoredCount, UserId, Expires FROM Searches WHERE SearchId = ?', [String(id)]); + if (!s || Number(s.Expires) < Date.now() || (s.UserId || null) !== userIdOf(freq.principal)) { + return null; + } + const rows = await q.all('SELECT ResourceKey FROM SearchEntries WHERE SearchKey = ? AND Pos >= ? AND Pos < ? ORDER BY Pos', + [s.SearchKey, offset, offset + count]); + return { s, keys: rows.map(r => Number(r.ResourceKey)) }; + }); + if (!found) { + throw new FhirError(404, 'not-found', `The search ${id} has expired, or is not known`); + } + const stored = JSON.parse(found.s.Query); + return this.buildPage(freq, ctx, { keys: found.keys, offset, count, stored: Number(found.s.StoredCount), + total: found.s.Total === null ? null : Number(found.s.Total), searchId: String(id), self: stored.self, control: stored.control, + warnings: stored.warnings || [], paged: true }); + } + + outcomeEntry(warnings) { + return { + resource: { resourceType: 'OperationOutcome', issue: warnings.map(w => ({ severity: 'warning', code: 'processing', diagnostics: w })) }, + search: { mode: 'outcome' } + }; + } + + async buildPage(freq, ctx, pg) { + const ep = this.ep; + const { found, included } = await ep.inRead(ctx, async (q) => { + const f = await ep.store.byKeys(q, pg.keys); + const inc = await this.includes(q, f, pg.control, ctx.access); + return { found: f, included: inc }; + }); + const bundle = { resourceType: 'Bundle', type: 'searchset' }; + if (pg.total !== null && pg.total !== undefined) { + bundle.total = pg.total; + } + const pageUrl = (offset) => `${freq.base}?${queryString([['_getpages', pg.searchId], ['_offset', String(offset)], ['_count', String(pg.count)]])}`; + bundle.link = [{ relation: 'self', url: pg.paged ? pageUrl(pg.offset) : pg.self }]; + if (pg.searchId) { + const last = Math.max(0, Math.floor((pg.stored - 1) / pg.count) * pg.count); + bundle.link.push({ relation: 'first', url: pageUrl(0) }); + if (pg.offset > 0) { + bundle.link.push({ relation: 'previous', url: pageUrl(Math.max(0, pg.offset - pg.count)) }); + } + if (pg.offset + pg.count < pg.stored) { + bundle.link.push({ relation: 'next', url: pageUrl(pg.offset + pg.count) }); + } + bundle.link.push({ relation: 'last', url: pageUrl(last) }); + } + const shapeControl = { summary: pg.control.summary, elements: pg.control.elements }; + bundle.entry = found.map(r => ({ + fullUrl: `${freq.base}/${r.type}/${r.id}`, resource: ep.shapeResource(r.resource, freq, shapeControl), search: { mode: 'match' } + })); + for (const r of included) { + bundle.entry.push({ fullUrl: `${freq.base}/${r.type}/${r.id}`, resource: ep.shapeResource(r.resource, freq, shapeControl), search: { mode: 'include' } }); + } + if (pg.warnings.length) { + bundle.entry.push(this.outcomeEntry(pg.warnings)); + } + return { status: 200, resource: bundle, searchKeys: found.map(r => r.resourceKey) }; + } + + /** + * _include and _revinclude for a page's resources: up to 3 rounds for :iterate. + */ + async includes(q, matches, control, access) { + const ep = this.ep; + if (!control || (!control.include.length && !control.revinclude.length) || !matches.length) { + return []; + } + const seen = new Set(matches.map(m => m.resourceKey)); + const out = []; + let current = matches; + for (let round = 0; round < INCLUDE_ROUNDS && current.length && out.length < MAX_INCLUDES; round++) { + const found = new Set(); + for (const inc of control.include) { + if (round > 0 && !inc.iterate) { + continue; + } + const src = current.filter(r => !inc.srcType || r.type === inc.srcType).map(r => r.resourceKey); + if (!src.length) { + continue; + } + for (let i = 0; i < src.length; i += 500) { + const c = src.slice(i, i + 500); + const conds = [`r.ResourceKey IN (${c.map(() => '?').join(', ')})`, 'r.TargetKey IS NOT NULL']; + const args = [...c]; + if (inc.key) { + conds.push('r.ParamKey = ?'); + args.push(inc.key); + } + if (inc.target) { + conds.push('r.TargetType = ?'); + args.push(inc.target); + } + const rows = await q.all(`SELECT DISTINCT r.TargetKey FROM IndexReferences r WHERE ${conds.join(' AND ')}`, args); + rows.forEach(r => found.add(Number(r.TargetKey))); + } + } + for (const inc of control.revinclude) { + if (round > 0 && !inc.iterate) { + continue; + } + const tgt = current.map(r => r.resourceKey); + for (let i = 0; i < tgt.length; i += 500) { + const c = tgt.slice(i, i + 500); + const conds = [`r.TargetKey IN (${c.map(() => '?').join(', ')})`, 'o.Deleted = 0']; + const args = [...c]; + if (inc.key) { + conds.push('r.ParamKey = ?'); + args.push(inc.key); + } + if (inc.srcType) { + conds.push('o.TypeKey = ?'); + args.push(ep.typeKeys.get(inc.srcType)); + } + const rows = await q.all(`SELECT DISTINCT r.ResourceKey FROM IndexReferences r JOIN Ids o ON o.ResourceKey = r.ResourceKey WHERE ${conds.join(' AND ')}`, args); + rows.forEach(r => found.add(Number(r.ResourceKey))); + } + } + let fresh = [...found].filter(k => !seen.has(k)); + fresh = await ep.filterKeysByAccess(q, access, fresh); + fresh = fresh.slice(0, MAX_INCLUDES - out.length); + fresh.forEach(k => seen.add(k)); + const loaded = await ep.store.byKeys(q, fresh); + out.push(...loaded); + current = loaded; + } + return out; + } + + /** Delete expired searches (a master job) */ + async cleanup() { + const ep = this.ep; + const now = Date.now(); + const expired = await ep.db.read(q => q.all('SELECT SearchKey FROM Searches WHERE Expires < ? LIMIT 1000', [now])); + if (!expired.length) { + return 0; + } + const keys = expired.map(r => Number(r.SearchKey)); + await ep.db.write(async (q) => { + for (let i = 0; i < keys.length; i += 200) { + const c = keys.slice(i, i + 200); + await q.run(`DELETE FROM SearchEntries WHERE SearchKey IN (${c.map(() => '?').join(', ')})`, c); + await q.run(`DELETE FROM Searches WHERE SearchKey IN (${c.map(() => '?').join(', ')})`, c); + } + }); + return keys.length; + } +} + +module.exports = { Searcher, MAX_INCLUDES, newSearchId, notFound }; diff --git a/rest/search/shape.js b/rest/search/shape.js new file mode 100644 index 00000000..ee7af02d --- /dev/null +++ b/rest/search/shape.js @@ -0,0 +1,71 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * _summary and _elements: the parts of a resource a client asked for. A shortened resource + * is marked with the SUBSETTED tag. + * + * @module rest/search/shape + */ + +const SUBSETTED = { system: 'http://terminology.hl7.org/CodeSystem/v3-ObservationValue', code: 'SUBSETTED', display: 'Resource encoded in summary mode' }; +const ALWAYS = new Set(['resourceType', 'id', 'meta', 'implicitRules']); + +function markSubsetted(r) { + r.meta = { ...(r.meta || {}) }; + const tags = (r.meta.tag || []).filter(t => !(t.system === SUBSETTED.system && t.code === SUBSETTED.code)); + r.meta.tag = [...tags, SUBSETTED]; + return r; +} + +/** Keep the named elements (choice elements by their stem: value keeps valueQuantity) */ +function keep(resource, names) { + const out = {}; + for (const [k, v] of Object.entries(resource)) { + if (ALWAYS.has(k) || names.has(k) || [...names].some(n => k.startsWith(n) && /^[A-Z]/.test(k.substring(n.length)))) { + out[k] = v; + } + } + return out; +} + +/** + * Shape a resource for _summary / _elements. + * @param {Object} resource + * @param {{summary: string|null, elements: string[]|null}} control + * @param {Object} definitions - summary and mandatory element names by type + * @returns {Object} + */ +function shape(resource, control, definitions) { + if (!resource || !control) { + return resource; + } + const type = resource.resourceType; + const summary = control.summary; + if (summary === 'true') { + const names = new Set(definitions.summary.get(type) || []); + return markSubsetted(keep(resource, names)); + } + if (summary === 'text') { + const names = new Set([...(definitions.mandatory.get(type) || []), 'text']); + return markSubsetted(keep(resource, names)); + } + if (summary === 'data') { + const r = { ...resource }; + delete r.text; + return markSubsetted(r); + } + if (control.elements && control.elements.length) { + const names = new Set(control.elements.map(e => e.includes('.') ? e.split('.').pop() : e)); + for (const m of definitions.mandatory.get(type) || []) { + names.add(m); + } + return markSubsetted(keep(resource, names)); + } + return resource; +} + +module.exports = { shape, SUBSETTED }; diff --git a/rest/search/sql.js b/rest/search/sql.js new file mode 100644 index 00000000..afc29e94 --- /dev/null +++ b/rest/search/sql.js @@ -0,0 +1,463 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Turn a search tree (parser.js) into SQL: a condition on a resource key expression. Each + * parameter is an EXISTS against its index table; a chain joins IndexReferences.TargetKey to + * the next condition; _has goes the other way. Everything is parameterised. + * + * Several values of one parameter are OR'd. A negated value (ne, :not, :not-in) matches when + * no value of the resource is equal: NOT EXISTS. + * + * @module rest/search/sql + */ + +const { dateClause, escapeLikeBang } = require('../../library/fhir-search-values'); +const { canonicalQuantity, UCUM } = require('../indexing/values'); +const { badRequest, notSupported } = require('../library/errors'); +const { TAG, PROFILE } = require('../store'); + +const TABLES = { + string: 'IndexStrings', token: 'IndexTokens', date: 'IndexDates', number: 'IndexNumbers', quantity: 'IndexQuantities', + reference: 'IndexReferences', uri: 'IndexUris' +}; + +const NOTHING = { sql: '1 = 0', args: [] }; +const EVERYTHING = { sql: '1 = 1', args: [] }; + +function inList(n) { + return new Array(n).fill('?').join(', '); +} + +class SqlBuilder { + /** + * @param {Object} ep - the Endpoint + * @param {Object} q - a query object + */ + constructor(ep, q) { + this.ep = ep; + this.q = q; + this.n = 0; + } + + alias(p) { + return p + (++this.n); + } + + /** + * A condition on a resource key. + * @param {Object} node + * @param {string} key - the SQL expression for the resource key (i.ResourceKey) + * @returns {Promise<{sql: string, args: Array}>} + */ + async build(node, key) { + switch (node.kind) { + case 'and': { + if (!node.items.length) { + return EVERYTHING; + } + const parts = []; + for (const n of node.items) { + parts.push(await this.build(n, key)); + } + return { sql: '(' + parts.map(p => p.sql).join(' AND ') + ')', args: parts.flatMap(p => p.args) }; + } + case 'or': { + const parts = []; + for (const n of node.items) { + parts.push(await this.build(n, key)); + } + return { sql: '(' + parts.map(p => p.sql).join(' OR ') + ')', args: parts.flatMap(p => p.args) }; + } + case 'not': { + const p = await this.build(node.item, key); + return { sql: `NOT ${p.sql}`, args: p.args }; + } + case 'none': + return NOTHING; + case 'id': { + const a = this.alias('z'); + const sql = `EXISTS (SELECT 1 FROM Ids ${a} WHERE ${a}.ResourceKey = ${key} AND ${a}.Id IN (${inList(node.ids.length)}))`; + return { sql: node.negate ? 'NOT ' + sql : sql, args: node.ids }; + } + case 'lastUpdated': { + const a = this.alias('z'); + const v = this.alias('zv'); + const parts = node.values.map(x => dateClause({ lo: `${v}.LastUpdated`, hi: `(${v}.LastUpdated + 1)` }, x.prefix, x.range)); + return { sql: `EXISTS (SELECT 1 FROM Ids ${a} JOIN Versions ${v} ON ${v}.VersionKey = ${a}.MostRecent WHERE ${a}.ResourceKey = ${key} AND (${parts.map(p => p.sql).join(' OR ')}))`, + args: parts.flatMap(p => p.args) }; + } + case 'tag': + return this.tag(node, key); + case 'tagMissing': { + const a = this.alias('z'); + const vt = this.alias('vt'); + const tg = this.alias('tg'); + const sql = `EXISTS (SELECT 1 FROM Ids ${a} JOIN VersionTags ${vt} ON ${vt}.VersionKey = ${a}.MostRecent JOIN Tags ${tg} ON ${tg}.TagKey = ${vt}.TagKey WHERE ${a}.ResourceKey = ${key} AND ${tg}.Kind = ?)`; + return { sql: node.missing ? 'NOT ' + sql : sql, args: [node.tagKind] }; + } + case 'list': + return this.list(node, key); + case 'compartment': { + const c = this.alias('c'); + return { sql: `EXISTS (SELECT 1 FROM Compartments ${c} WHERE ${c}.ResourceKey = ${key} AND ${c}.CompType = ? AND ${c}.CompId = ?)`, args: [node.type, node.id] }; + } + case 'missing': { + if (node.spType === 'composite') { + return this.compositeMissing(node, key); + } + const t = TABLES[node.spType]; + const x = this.alias('x'); + const sql = `EXISTS (SELECT 1 FROM ${t} ${x} WHERE ${x}.ResourceKey = ${key} AND ${x}.ParamKey IN (${inList(node.keys.length)}))`; + return { sql: node.missing ? 'NOT ' + sql : sql, args: node.keys }; + } + case 'chain': { + const r = this.alias('r'); + const inner = await this.build(node.inner, `${r}.TargetKey`); + let typeCond = ''; + const args = [...node.keys]; + if (node.targetTypes) { + typeCond = ` AND ${r}.TargetType IN (${inList(node.targetTypes.length)})`; + args.push(...node.targetTypes); + } + return { sql: `EXISTS (SELECT 1 FROM IndexReferences ${r} WHERE ${r}.ResourceKey = ${key} AND ${r}.ParamKey IN (${inList(node.keys.length)})${typeCond} AND ${r}.TargetKey IS NOT NULL AND ${inner.sql})`, + args: [...args, ...inner.args] }; + } + case 'has': { + const r = this.alias('r'); + const o = this.alias('o'); + const inner = await this.build(node.inner, `${r}.ResourceKey`); + return { sql: `EXISTS (SELECT 1 FROM IndexReferences ${r} JOIN Ids ${o} ON ${o}.ResourceKey = ${r}.ResourceKey WHERE ${r}.TargetKey = ${key} AND ${r}.ParamKey IN (${inList(node.keys.length)}) AND ${o}.TypeKey = ? AND ${o}.Deleted = 0 AND ${inner.sql})`, + args: [...node.keys, node.typeKey, ...inner.args] }; + } + case 'param': + return this.param(node, key); + } + throw new Error(`Unknown search node ${node.kind}`); + } + + async tag(node, key) { + const a = this.alias('z'); + const vt = this.alias('vt'); + const tg = this.alias('tg'); + const conds = []; + const args = [node.tagKind]; + for (const v of node.values) { + if (node.tagKind === PROFILE && v.below) { + conds.push(`${tg}.Code LIKE ? ESCAPE '!'`); + args.push(escapeLikeBang(v.code) + '%'); + } else if (v.system === undefined) { + conds.push(`${tg}.Code = ?`); + args.push(v.code); + } else if (v.code === undefined) { + conds.push(`${tg}.TagSystem = ?`); + args.push(v.system); + } else { + conds.push(`(${tg}.TagSystem = ? AND ${tg}.Code = ?)`); + args.push(v.system || '', v.code); + } + } + const sql = `EXISTS (SELECT 1 FROM Ids ${a} JOIN VersionTags ${vt} ON ${vt}.VersionKey = ${a}.MostRecent JOIN Tags ${tg} ON ${tg}.TagKey = ${vt}.TagKey WHERE ${a}.ResourceKey = ${key} AND ${tg}.Kind = ? AND (${conds.join(' OR ')}))`; + return { sql: node.negate ? 'NOT ' + sql : sql, args }; + } + + async list(node, key) { + const listType = this.ep.typeKeys.get('List'); + const item = this.ep.definitions.param('List', 'item'); + if (listType === undefined || !item || item.key === null) { + throw notSupported('_list needs the List resource and its item search parameter'); + } + const r = this.alias('r'); + const l = this.alias('l'); + return { sql: `EXISTS (SELECT 1 FROM IndexReferences ${r} JOIN Ids ${l} ON ${l}.ResourceKey = ${r}.ResourceKey WHERE ${l}.TypeKey = ? AND ${l}.Id = ? AND ${l}.Deleted = 0 AND ${r}.ParamKey = ? AND ${r}.TargetKey = ${key})`, + args: [listType, node.id, item.key] }; + } + + async compositeMissing(node, key) { + const x = this.alias('x'); + const subs = Object.values(TABLES).map(t => `SELECT 1 FROM ${t} ${x}${t} WHERE ${x}${t}.ResourceKey = ${key} AND ${x}${t}.ParamKey IN (${inList(node.keys.length)})`); + const sql = `EXISTS (${subs.join(' UNION ALL ')})`; + return { sql: node.missing ? 'NOT ' + sql : sql, args: Object.values(TABLES).flatMap(() => node.keys) }; + } + + /** + * One parameter: positive values in one EXISTS, each negated value in a NOT EXISTS. + */ + async param(node, key) { + if (node.spType === 'composite') { + return this.composite(node, key); + } + const t = TABLES[node.spType]; + const pos = []; + const neg = []; + for (const v of node.values) { + const x = this.alias('x'); + const c = await this.value(node.spType, node, v, x); + (v.negate ? neg : pos).push({ x, c }); + } + const parts = []; + const args = []; + const sub = (x, c) => `SELECT 1 FROM ${t} ${x} WHERE ${x}.ResourceKey = ${key} AND ${x}.ParamKey IN (${inList(node.keys.length)}) AND ${c.sql}`; + if (pos.length) { + // one EXISTS per value keeps each value's join simple; OR'd + for (const { x, c } of pos) { + parts.push(`EXISTS (${sub(x, c)})`); + args.push(...node.keys, ...c.args); + } + } + for (const { x, c } of neg) { + parts.push(`NOT EXISTS (${sub(x, c)})`); + args.push(...node.keys, ...c.args); + } + return { sql: '(' + parts.join(' OR ') + ')', args }; + } + + /** + * The condition on an index row (alias x) for one value. + */ + async value(spType, node, v, x) { + switch (spType) { + case 'string': + return this.stringValue(v, x); + case 'token': + return this.tokenValue(v, x); + case 'date': + return dateClause({ lo: `${x}.Lo`, hi: `${x}.Hi` }, v.prefix, v.range); + case 'number': + return this.numberClause(`${x}.Value`, v); + case 'quantity': + return this.quantityValue(v, x); + case 'reference': + return this.referenceValue(node, v, x); + case 'uri': + return this.uriValue(v, x); + } + throw badRequest(`Search parameters of type ${spType} are not supported`); + } + + stringValue(v, x) { + switch (v.mode) { + case 'exact': return { sql: `${x}.Exact = ?`, args: [v.text] }; + case 'contains': return { sql: `${x}.Norm LIKE ? ESCAPE '!'`, args: ['%' + escapeLikeBang(v.norm) + '%'] }; + case 'end': return { sql: `${x}.Norm LIKE ? ESCAPE '!'`, args: ['%' + escapeLikeBang(v.norm)] }; + case 'eqnorm': return { sql: `${x}.Norm = ?`, args: [v.norm] }; + case 'gt': return { sql: `${x}.Norm > ?`, args: [v.norm] }; + case 'lt': return { sql: `${x}.Norm < ?`, args: [v.norm] }; + case 'ge': return { sql: `${x}.Norm >= ?`, args: [v.norm] }; + case 'le': return { sql: `${x}.Norm <= ?`, args: [v.norm] }; + default: return { sql: `${x}.Norm LIKE ? ESCAPE '!'`, args: [escapeLikeBang(v.norm) + '%'] }; + } + } + + async space(uri) { + return this.ep.lookups.spaceKey(this.q, uri); + } + + async tokenValue(v, x) { + switch (v.mode) { + case 'text': + return { sql: `${x}.TextNorm LIKE ? ESCAPE '!'`, args: [escapeLikeBang(v.norm) + '%'] }; + case 'of-type': { + const sk = await this.space(v.typeSystem); + if (sk === null) { + return NOTHING; + } + return { sql: `(${x}.TypeSpaceKey = ? AND ${x}.TypeCode = ? AND ${x}.Code = ?)`, args: [sk, v.typeCode, v.code] }; + } + case 'below': + case 'above': + return this.subsumption(v, x); + case 'in': + return this.inValueSet(v, x); + } + if (v.system === undefined) { + return { sql: `${x}.Code = ?`, args: [v.code] }; + } + if (v.system === null) { + return { sql: `(${x}.SpaceKey IS NULL AND ${x}.Implicit = 0 AND ${x}.Code = ?)`, args: [v.code] }; + } + const sk = await this.space(v.system); + if (v.code === undefined) { + return sk === null ? NOTHING : { sql: `${x}.SpaceKey = ?`, args: [sk] }; + } + if (sk === null) { + // the system is not known, but a code with an implicit system (a code element) can match + return { sql: `(${x}.Implicit = 1 AND ${x}.Code = ?)`, args: [v.code] }; + } + return { sql: `((${x}.SpaceKey = ? OR ${x}.Implicit = 1) AND ${x}.Code = ?)`, args: [sk, v.code] }; + } + + async subsumption(v, x) { + const sk = await this.space(v.system); + if (sk === null) { + return NOTHING; + } + const row = await this.q.get('SELECT ConceptKey FROM Concepts WHERE SpaceKey = ? AND Code = ?', [sk, v.code]); + if (!row) { + return NOTHING; + } + const ck = Number(row.ConceptKey); + const ce = this.alias('ce'); + if (v.mode === 'below') { + return { sql: `(${x}.ConceptKey = ? OR ${x}.ConceptKey IN (SELECT ${ce}.SubsumedKey FROM ClosureEntries ${ce} WHERE ${ce}.SubsumesKey = ?))`, args: [ck, ck] }; + } + return { sql: `(${x}.ConceptKey = ? OR ${x}.ConceptKey IN (SELECT ${ce}.SubsumesKey FROM ClosureEntries ${ce} WHERE ${ce}.SubsumedKey = ?))`, args: [ck, ck] }; + } + + async inValueSet(v, x) { + if (!this.ep.terminology) { + throw notSupported(':in and :not-in need a terminology server (the endpoint\'s txServer setting)'); + } + const codes = await this.ep.terminology.expand(v.valueSet); + const bySystem = new Map(); + for (const c of codes) { + if (!bySystem.has(c.system)) { + bySystem.set(c.system, []); + } + bySystem.get(c.system).push(c.code); + } + const parts = []; + const args = []; + for (const [system, list] of bySystem) { + const sk = await this.space(system); + if (sk === null) { + continue; + } + for (let i = 0; i < list.length; i += 1000) { + const c = list.slice(i, i + 1000); + parts.push(`(${x}.SpaceKey = ? AND ${x}.Code IN (${inList(c.length)}))`); + args.push(sk, ...c); + } + } + return parts.length ? { sql: '(' + parts.join(' OR ') + ')', args } : NOTHING; + } + + numberClause(col, v) { + switch (v.prefix) { + case 'eq': return { sql: `(${col} >= ? AND ${col} < ?)`, args: [v.lo, v.hi] }; + case 'ne': return { sql: `NOT (${col} >= ? AND ${col} < ?)`, args: [v.lo, v.hi] }; + case 'gt': return { sql: `${col} > ?`, args: [v.value] }; + case 'lt': return { sql: `${col} < ?`, args: [v.value] }; + case 'ge': return { sql: `${col} >= ?`, args: [v.value] }; + case 'le': return { sql: `${col} <= ?`, args: [v.value] }; + case 'sa': return { sql: `${col} >= ?`, args: [v.hi] }; + case 'eb': return { sql: `${col} < ?`, args: [v.lo] }; + case 'ap': { + const w = Math.max(Math.abs(v.value) * 0.1, v.hi - v.lo); + return { sql: `(${col} >= ? AND ${col} <= ?)`, args: [v.value - w, v.value + w] }; + } + } + throw badRequest(`Unknown prefix ${v.prefix}`); + } + + async quantityValue(v, x) { + if (v.system === UCUM && v.unit) { + const lo = canonicalQuantity(v.unit, v.lo); + const hi = canonicalQuantity(v.unit, v.hi); + const val = canonicalQuantity(v.unit, v.value); + if (lo && hi && val) { + const cv = { prefix: v.prefix, lo: Math.min(lo.value, hi.value), hi: Math.max(lo.value, hi.value), value: val.value }; + const c = this.numberClause(`((${x}.CanonLo + ${x}.CanonHi) / 2)`, cv); + return { sql: `(${x}.CanonUnit = ? AND ${c.sql})`, args: [lo.unit, ...c.args] }; + } + } + const c = this.numberClause(`${x}.Value`, v); + const conds = [c.sql]; + const args = [...c.args]; + if (v.system) { + const sk = await this.space(v.system); + if (sk === null) { + return NOTHING; + } + conds.push(`${x}.SpaceKey = ?`); + args.push(sk); + } + if (v.unit) { + conds.push(`${x}.Unit = ?`); + args.push(v.unit); + } + return { sql: '(' + conds.join(' AND ') + ')', args }; + } + + async referenceValue(node, v, x) { + switch (v.mode) { + case 'nothing': + return NOTHING; + case 'identifier': { + if (v.system === undefined) { + return { sql: `${x}.IdentValue = ?`, args: [v.value] }; + } + const sk = v.system ? await this.space(v.system) : null; + if (v.system && sk === null) { + return NOTHING; + } + return v.system ? { sql: `(${x}.IdentSpaceKey = ? AND ${x}.IdentValue = ?)`, args: [sk, v.value] } + : { sql: `(${x}.IdentSpaceKey IS NULL AND ${x}.IdentValue = ?)`, args: [v.value] }; + } + case 'local': { + const conds = [`${x}.TargetId = ?`]; + const args = [v.id]; + const type = v.type || (node.modifier && node.modifier !== 'missing' ? node.modifier : null); + if (type) { + conds.push(`${x}.TargetType = ?`); + args.push(type); + } + if (v.version) { + conds.push(`${x}.TargetVersion = ?`); + args.push(v.version); + } + return { sql: '(' + conds.join(' AND ') + ')', args }; + } + case 'url': + if (v.urlVersion) { + return { sql: `(${x}.Url = ? AND ${x}.UrlVersion = ?)`, args: [v.url, v.urlVersion] }; + } + return { sql: `${x}.Url = ?`, args: [v.url] }; + } + throw badRequest('Unknown reference value'); + } + + uriValue(v, x) { + switch (v.mode) { + case 'below': return { sql: `${x}.Value LIKE ? ESCAPE '!'`, args: [escapeLikeBang(v.value) + '%'] }; + case 'contains': return { sql: `${x}.Value LIKE ? ESCAPE '!'`, args: ['%' + escapeLikeBang(v.value) + '%'] }; + case 'above': return { sql: `? LIKE ${this.q.dialect.concat(`${x}.Value`, '\'%\'')}`, args: [v.value] }; + default: return { sql: `${x}.Value = ?`, args: [v.value] }; + } + } + + /** + * A composite: the components' rows share ResourceKey, ParamKey and GroupNo. + */ + async composite(node, key) { + const parts = []; + const args = []; + for (const v of node.values) { + const aliases = v.comps.map(() => this.alias('k')); + const froms = []; + const conds = []; + const cargs = []; + for (let i = 0; i < v.comps.length; i++) { + const comp = v.comps[i]; + const a = aliases[i]; + const t = TABLES[comp.spType]; + if (i === 0) { + froms.push(`${t} ${a}`); + } else { + froms.push(`JOIN ${t} ${a} ON ${a}.ResourceKey = ${aliases[0]}.ResourceKey AND ${a}.ParamKey = ${aliases[0]}.ParamKey AND ${a}.GroupNo = ${aliases[0]}.GroupNo AND ${a}.Comp = ${i}`); + } + const c = await this.value(comp.spType, { modifier: null }, comp.value, a); + conds.push(c.sql); + cargs.push(...c.args); + } + parts.push(`EXISTS (SELECT 1 FROM ${froms.join(' ')} WHERE ${aliases[0]}.ResourceKey = ${key} AND ${aliases[0]}.ParamKey IN (${inList(node.keys.length)}) AND ${aliases[0]}.Comp = 0 AND ${conds.join(' AND ')})`); + args.push(...node.keys, ...cargs); + } + return { sql: '(' + parts.join(' OR ') + ')', args }; + } +} + +module.exports = { SqlBuilder, TABLES, NOTHING, EVERYTHING, TAG }; diff --git a/rest/store.js b/rest/store.js new file mode 100644 index 00000000..61fb69c8 --- /dev/null +++ b/rest/store.js @@ -0,0 +1,391 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Resources in the database: reading the current or a past version, and writing a new + * version (with its tags, index rows, compartments and subscription queue row) inside the + * caller's write transaction. + * + * Ids: a row per resource, (TypeKey, Id) unique. MostRecent is the current version's key; + * NULL means the id is reserved by a transaction that hasn't written it yet. Deleted is 1 + * when the current version is a deletion. + * + * Versions: one per version, VersionId counting up from 1 per resource. A new version is + * written by moving Ids.MostRecent from the version it was based on, as a conditional update: + * if another request got there first, nothing changes and the write starts again from the + * newer version (or fails, with If-Match). + * + * @module rest/store + */ + +const zlib = require('zlib'); +const crypto = require('crypto'); +const { FhirError, preconditionFailed, conflict, badRequest } = require('./library/errors'); + +const OP_CREATE = 1; +const OP_UPDATE = 2; +const OP_DELETE = 3; +const OP_NAMES = { 1: 'create', 2: 'update', 3: 'delete' }; + +// tag kinds in Tags +const TAG = 1; +const SECURITY = 2; +const PROFILE = 3; +const PROFILE_SYSTEM = 'urn:profile'; + +const ID_RE = /^[A-Za-z0-9\-.]{1,64}$/; + +function encode(resource, compress) { + const text = Buffer.from(JSON.stringify(resource), 'utf8'); + return compress ? { compressed: 1, content: zlib.gzipSync(text) } : { compressed: 0, content: text }; +} + +function decode(row) { + if (!row || row.Content === null || row.Content === undefined) { + return null; + } + let buf = Buffer.isBuffer(row.Content) ? row.Content : Buffer.from(row.Content); + if (Number(row.Compressed)) { + buf = zlib.gunzipSync(buf); + } + return JSON.parse(buf.toString('utf8')); +} + +function newUuid() { + return crypto.randomUUID(); +} + +/** The tags, security labels and profiles in a resource's meta */ +function metaTags(meta) { + const out = []; + if (!meta) { + return out; + } + for (const t of meta.tag || []) { + if (t && t.code) { + out.push({ kind: TAG, system: t.system || '', code: t.code, display: t.display }); + } + } + for (const t of meta.security || []) { + if (t && t.code) { + out.push({ kind: SECURITY, system: t.system || '', code: t.code, display: t.display }); + } + } + for (const p of meta.profile || []) { + if (typeof p === 'string' && p) { + out.push({ kind: PROFILE, system: PROFILE_SYSTEM, code: p.substring(0, 255) }); + } + } + return out; +} + +class Store { + /** + * @param {Object} endpoint - an Endpoint: settings, typeKeys, lookups, indexer, audit + */ + constructor(endpoint) { + this.endpoint = endpoint; + } + + typeKey(type) { + const k = this.endpoint.typeKeys.get(type); + if (k === undefined) { + throw badRequest(`Unknown resource type ${type}`); + } + return k; + } + + /** + * The Ids row for a resource, or null. + * @returns {Promise<{ResourceKey: number, MostRecent: number|null, Deleted: number}|null>} + */ + async idRow(q, type, id, lock = false) { + if (!ID_RE.test(String(id))) { + return null; + } + const forUpdate = lock && q.inTransaction ? q.dialect.forUpdate || '' : ''; + const row = await q.get('SELECT ResourceKey, MostRecent, Deleted FROM Ids WHERE TypeKey = ? AND Id = ?' + forUpdate, [this.typeKey(type), id]); + if (!row) { + return null; + } + return { ResourceKey: Number(row.ResourceKey), MostRecent: row.MostRecent === null ? null : Number(row.MostRecent), Deleted: Number(row.Deleted) }; + } + + /** + * The current version of a resource. + * @returns {Promise} + * null when there is no such resource (or only a reservation) + */ + async current(q, type, id, lock = false) { + const ids = await this.idRow(q, type, id, lock); + if (!ids || ids.MostRecent === null) { + return null; + } + const v = await q.get('SELECT VersionKey, VersionId, LastUpdated, Operation, UserId, Compressed, Content FROM Versions WHERE VersionKey = ?', [ids.MostRecent]); + if (!v) { + return null; + } + return this.versionResult(ids.ResourceKey, v, !!ids.Deleted); + } + + versionResult(resourceKey, v, deleted) { + return { + resourceKey, + versionKey: Number(v.VersionKey), + versionId: Number(v.VersionId), + lastUpdated: Number(v.LastUpdated), + operation: Number(v.Operation), + deleted: deleted === undefined ? Number(v.Operation) === OP_DELETE : deleted, + userId: v.UserId, + resource: decode(v) + }; + } + + /** A version of a resource, or null */ + async version(q, type, id, versionId) { + const ids = await this.idRow(q, type, id); + if (!ids || !/^\d{1,9}$/.test(String(versionId))) { + return null; + } + const v = await q.get('SELECT VersionKey, VersionId, LastUpdated, Operation, UserId, Compressed, Content FROM Versions WHERE ResourceKey = ? AND VersionId = ?', + [ids.ResourceKey, Number(versionId)]); + return v ? this.versionResult(ids.ResourceKey, v) : null; + } + + /** The current resources for a list of keys (in that order; missing or deleted ones left out) */ + async byKeys(q, keys) { + if (!keys.length) { + return []; + } + const out = new Map(); + for (let i = 0; i < keys.length; i += 500) { + const c = keys.slice(i, i + 500); + const rows = await q.all(`SELECT i.ResourceKey, i.Id, t.Name, v.VersionKey, v.VersionId, v.LastUpdated, v.Operation, v.UserId, v.Compressed, v.Content + FROM Ids i JOIN Types t ON t.TypeKey = i.TypeKey JOIN Versions v ON v.VersionKey = i.MostRecent + WHERE i.Deleted = 0 AND i.ResourceKey IN (${c.map(() => '?').join(', ')})`, c); + for (const r of rows) { + const res = this.versionResult(Number(r.ResourceKey), r, false); + res.type = r.Name; + res.id = r.Id; + out.set(Number(r.ResourceKey), res); + } + } + return keys.map(k => out.get(Number(k))).filter(x => x); + } + + /** + * Reserve an id for a resource this transaction will create (an Ids row with no version). + * @param {Object} q + * @param {string} type + * @param {string|null} id - a client id (PUT), or null for a server-assigned one + * @returns {Promise<{resourceKey: number, id: string, existing: boolean}>} + */ + async reserve(q, type, id) { + const typeKey = this.typeKey(type); + if (id) { + if (!ID_RE.test(id)) { + throw badRequest(`'${id}' is not a valid id`); + } + const row = await this.idRow(q, type, id); + if (row) { + return { resourceKey: row.ResourceKey, id, existing: true }; + } + try { + const r = await q.run('INSERT INTO Ids (TypeKey, Id, MostRecent, Deleted) VALUES (?, ?, NULL, 0)', [typeKey, id]); + return { resourceKey: Number(r.lastId), id, existing: false }; + } catch (e) { + if (e.unique) { + // made by another request since we looked: the caller starts again + e.retryable = true; + } + throw e; + } + } + if (this.endpoint.settings.idStrategy === 'uuid') { + const uuid = newUuid(); + const r = await q.run('INSERT INTO Ids (TypeKey, Id, MostRecent, Deleted) VALUES (?, ?, NULL, 0)', [typeKey, uuid]); + return { resourceKey: Number(r.lastId), id: uuid, existing: false }; + } + // the resource key: the row is made with a temporary id, then given its key as id. A + // client may already have used that number as an id (PUT): then a UUID + const r = await q.run('INSERT INTO Ids (TypeKey, Id, MostRecent, Deleted) VALUES (?, ?, NULL, 0)', [typeKey, '~' + newUuid().substring(0, 30)]); + const key = Number(r.lastId); + let newId = String(key); + const taken = await q.get('SELECT ResourceKey FROM Ids WHERE TypeKey = ? AND Id = ?', [typeKey, newId]); + if (taken) { + newId = newUuid(); + } + await q.run('UPDATE Ids SET Id = ? WHERE ResourceKey = ?', [newId, key]); + return { resourceKey: key, id: newId, existing: false }; + } + + /** + * Write a new version of a resource (create, update or delete). + * @param {Object} q - in a write transaction + * @param {Object} w + * @param {string} w.type + * @param {string} w.id + * @param {number} w.resourceKey - from reserve() or the current version + * @param {number|null} w.basedOn - the version key this is based on (null for a create) + * @param {number} w.previousVersionId - 0 for a create + * @param {Object|null} w.resource - null for a delete + * @param {number} w.operation - OP_CREATE, OP_UPDATE, OP_DELETE + * @param {string|null} w.userId + * @param {Set} [w.reserved] - Type/id of resources this transaction creates + * @param {boolean} [w.deferChecks] + * @param {number} [w.now] + * @returns {Promise<{versionKey, versionId, lastUpdated, resource, unresolved}>} + */ + async writeVersion(q, w) { + const ep = this.endpoint; + const now = w.now || Date.now(); + const versionId = (w.previousVersionId || 0) + 1; + let resource = null; + if (w.resource) { + resource = { ...w.resource, id: w.id }; + resource.meta = { ...(resource.meta || {}), versionId: String(versionId), lastUpdated: new Date(now).toISOString() }; + } + const enc = resource ? encode(resource, ep.settings.compress) : { compressed: 0, content: null }; + let vr; + try { + vr = await q.run('INSERT INTO Versions (ResourceKey, VersionId, LastUpdated, Operation, UserId, AuditKey, Compressed, Content) VALUES (?, ?, ?, ?, ?, NULL, ?, ?)', + [w.resourceKey, versionId, now, w.operation, w.userId ? String(w.userId).substring(0, 128) : null, enc.compressed, enc.content]); + } catch (e) { + if (e.unique) { + e.retryable = true; + } + throw e; + } + const versionKey = Number(vr.lastId); + const deleted = w.operation === OP_DELETE ? 1 : 0; + const moved = w.basedOn === null || w.basedOn === undefined + ? await q.run('UPDATE Ids SET MostRecent = ?, Deleted = ? WHERE ResourceKey = ? AND MostRecent IS NULL', [versionKey, deleted, w.resourceKey]) + : await q.run('UPDATE Ids SET MostRecent = ?, Deleted = ? WHERE ResourceKey = ? AND MostRecent = ?', [versionKey, deleted, w.resourceKey, w.basedOn]); + if (!moved.changes) { + // another request wrote a version first + const e = conflict(`${w.type}/${w.id} was changed by another request`); + e.retryable = true; + throw e; + } + let unresolved = []; + if (resource) { + const tagKeys = await ep.lookups.tagKeys(q, metaTags(resource.meta)); + if (tagKeys.length) { + const uniq = [...new Set(tagKeys)]; + await q.run('INSERT INTO VersionTags (VersionKey, TagKey) VALUES ' + uniq.map(() => '(?, ?)').join(', '), uniq.flatMap(k => [versionKey, k])); + } + const r = await ep.indexer.index(q, { resourceKey: w.resourceKey, resource, reserved: w.reserved, deferChecks: w.deferChecks }); + unresolved = r.unresolved; + } else { + await ep.indexer.remove(q, w.resourceKey); + } + if (w.operation === OP_CREATE || (w.previousVersionId > 0 && w.previousDeleted)) { + await ep.indexer.linkReferences(q, w.type, w.id, w.resourceKey); + } + if (w.type === 'SearchParameter' && ep.settings.customSearchParameters) { + // the definitions change: every process reloads them, and the master reindexes + await require('./endpoint/settings').bumpGeneration(q); + } + await q.run('INSERT INTO SubscriptionQueue (ResourceKey, VersionKey, PreviousVersionKey, Operation, Entered, Handled) VALUES (?, ?, ?, ?, ?, NULL)', + [w.resourceKey, versionKey, w.basedOn || null, w.operation, now]); + return { versionKey, versionId, lastUpdated: now, resource, unresolved }; + } + + /** + * Create, update or delete with the version checks: the common path for every write. + * @param {Object} q + * @param {Object} p + * @param {string} p.type + * @param {string|null} p.id - null: a server-assigned id (create) + * @param {Object|null} p.resource - null: delete + * @param {string|null} p.ifMatch - the version the client says it is updating + * @param {boolean} [p.mustCreate] - a create: an existing id is a conflict + * @param {boolean} [p.createOnUpdate] + * @param {boolean} [p.versionAware] - the type needs If-Match on update + * @param {string|null} p.userId + * @param {Object} [p.reservation] - an id already reserved by this transaction + * @returns {Promise<{created: boolean, deleted: boolean, unchanged: boolean, id, resourceKey, versionKey, versionId, lastUpdated, resource, previous}>} + */ + async put(q, p) { + let reservation = p.reservation || null; + let cur = null; + let ids = null; + // the row is locked (MySQL) until the transaction ends: another write to the same + // resource waits for this one + if (!reservation && p.id) { + ids = await this.idRow(q, p.type, p.id, true); + } + if (reservation) { + ids = await this.idRow(q, p.type, reservation.id, true); + } + if (ids && ids.MostRecent !== null) { + cur = await this.current(q, p.type, p.id || reservation.id); + } + if (p.mustCreate && cur && !cur.deleted) { + throw conflict(`${p.type}/${p.id} already exists`); + } + if (p.ifMatch !== null && p.ifMatch !== undefined) { + if (!cur || String(cur.versionId) !== String(p.ifMatch)) { + throw preconditionFailed(cur ? `Version ${p.ifMatch} is not the current version (${cur.versionId}) of ${p.type}/${p.id}` + : `${p.type}/${p.id} doesn't exist (If-Match ${p.ifMatch})`); + } + } else if (p.versionAware && cur && !cur.deleted && p.resource) { + throw preconditionFailed(`Updates to ${p.type} must say which version they update (If-Match)`); + } + if (!p.resource) { + // delete + if (!cur || cur.deleted) { + return { deleted: true, unchanged: true, id: p.id, resourceKey: ids ? ids.ResourceKey : null, versionId: cur ? cur.versionId : null, previous: cur }; + } + const r = await this.writeVersion(q, { type: p.type, id: p.id, resourceKey: cur.resourceKey, basedOn: cur.versionKey, + previousVersionId: cur.versionId, resource: null, operation: OP_DELETE, userId: p.userId }); + return { deleted: true, unchanged: false, id: p.id, resourceKey: cur.resourceKey, ...r, previous: cur }; + } + if (!cur && !reservation) { + if (p.id && !p.createOnUpdate && !p.mustCreate) { + throw new FhirError(405, 'not-supported', `${p.type}/${p.id} doesn't exist, and this server doesn't create resources by PUT`); + } + reservation = ids ? { resourceKey: ids.ResourceKey, id: p.id } : await this.reserve(q, p.type, p.id); + } + const id = cur ? p.id || reservation.id : reservation.id; + const resourceKey = cur ? cur.resourceKey : reservation.resourceKey; + const operation = cur && !cur.deleted ? OP_UPDATE : OP_CREATE; + const r = await this.writeVersion(q, { + type: p.type, id, resourceKey, basedOn: cur ? cur.versionKey : null, previousVersionId: cur ? cur.versionId : 0, + previousDeleted: cur ? cur.deleted : false, resource: p.resource, operation, + userId: p.userId, reserved: p.reserved, deferChecks: p.deferChecks + }); + return { created: !cur || cur.deleted, deleted: false, unchanged: false, id, resourceKey, ...r, previous: cur }; + } + + /** Set the AuditEvent that recorded a version */ + async setAudit(q, versionKey, auditKey) { + await q.run('UPDATE Versions SET AuditKey = ? WHERE VersionKey = ?', [auditKey, versionKey]); + } + + /** + * Replace the meta of the current version without a new version ($meta-add, $meta-delete). + */ + async rewriteMeta(q, cur, type, resource) { + const ep = this.endpoint; + const enc = encode(resource, ep.settings.compress); + await q.run('UPDATE Versions SET Compressed = ?, Content = ? WHERE VersionKey = ?', [enc.compressed, enc.content, cur.versionKey]); + await q.run('DELETE FROM VersionTags WHERE VersionKey = ?', [cur.versionKey]); + const tagKeys = [...new Set(await ep.lookups.tagKeys(q, metaTags(resource.meta)))]; + if (tagKeys.length) { + await q.run('INSERT INTO VersionTags (VersionKey, TagKey) VALUES ' + tagKeys.map(() => '(?, ?)').join(', '), tagKeys.flatMap(k => [cur.versionKey, k])); + } + await ep.indexer.index(q, { resourceKey: cur.resourceKey, resource }); + } + + /** Whether any resource exists (for deciding whether new definitions need reindexing) */ + async hasResources(q) { + const row = await q.get('SELECT ResourceKey FROM Ids WHERE MostRecent IS NOT NULL LIMIT 1'); + return !!row; + } +} + +module.exports = { Store, encode, decode, metaTags, OP_CREATE, OP_UPDATE, OP_DELETE, OP_NAMES, TAG, SECURITY, PROFILE, PROFILE_SYSTEM, ID_RE }; diff --git a/rest/terminology.js b/rest/terminology.js new file mode 100644 index 00000000..aaa4dcd6 --- /dev/null +++ b/rest/terminology.js @@ -0,0 +1,162 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The endpoint's terminology server: value set expansions for :in and :not-in, and the + * closure table (for :below and :above), kept up to date as a client of the server's + * $closure. The server is a path on this server (the tx module, in process) or a URL, as for + * the IPS module. + * + * @module rest/terminology + */ + +const crypto = require('crypto'); +const { TxClient } = require('../ips/tx-client'); +const { FhirError, tooCostly } = require('./library/errors'); + +const MAX_EXPANSION = 10000; +const EXPANSION_KEEP_MS = 5 * 60 * 1000; +const CLOSURE_BATCH = 200; + +// R4 equivalence and R5 relationship: does the target subsume the source (up), or the +// source the target (down)? +const UP = new Set(['subsumes', 'wider', 'source-is-narrower-than-target']); +const DOWN = new Set(['specializes', 'narrower', 'source-is-broader-than-target']); + +class Terminology { + /** + * @param {string} server - a path on this server or an http(s) URL + * @param {Object} options - { app, log, closureName } + */ + constructor(server, options = {}) { + this.client = new TxClient(server, { app: options.app, log: options.log }); + this.log = options.log; + this.closureName = options.closureName; + this.expansions = new Map(); + } + + /** + * The codes in a value set. + * @param {string} url + * @returns {Promise>} + */ + async expand(url) { + const cached = this.expansions.get(url); + if (cached && cached.until > Date.now()) { + return cached.codes; + } + const r = await this.client.get('/ValueSet/$expand', { url, count: MAX_EXPANSION + 1, excludeNested: true }); + if (r.status !== 200 || !r.resource || r.resource.resourceType !== 'ValueSet') { + const msg = r.resource && r.resource.issue ? r.resource.issue.map(i => i.diagnostics || (i.details && i.details.text)).filter(x => x).join('; ') : `status ${r.status}`; + throw new FhirError(400, 'processing', `The value set ${url} couldn't be expanded: ${msg}`); + } + const codes = []; + const walk = (list) => { + for (const c of list || []) { + if (c.system && c.code && !c.abstract) { + codes.push({ system: c.system, code: c.code }); + } + walk(c.contains); + } + }; + walk(r.resource.expansion && r.resource.expansion.contains); + const total = r.resource.expansion && r.resource.expansion.total; + if (codes.length > MAX_EXPANSION || (typeof total === 'number' && total > MAX_EXPANSION)) { + throw tooCostly(`The value set ${url} has more than ${MAX_EXPANSION} codes: too many for :in`); + } + this.expansions.set(url, { codes, until: Date.now() + EXPANSION_KEEP_MS }); + if (this.expansions.size > 200) { + this.expansions.delete(this.expansions.keys().next().value); + } + return codes; + } + + /** + * One round of the closure job: send the concepts not yet in the closure, and apply what + * comes back. A master job. + * @param {Object} ep - the Endpoint + * @returns {Promise} how many concepts were sent + */ + async updateClosure(ep) { + const db = ep.db; + const closure = await db.read(q => q.get('SELECT ClosureKey, Name, Version FROM Closures WHERE Name = ?', [this.closureName])); + let closureKey; + let version; + if (!closure) { + const r = await this.client.post('/$closure', { resourceType: 'Parameters', parameter: [{ name: 'name', valueString: this.closureName }] }); + if (r.status !== 200) { + throw new Error(`The terminology server didn't start the closure ${this.closureName} (status ${r.status})`); + } + closureKey = await db.write(async (q) => { + await q.run(q.dialect.insertIgnore('Closures', ['Name', 'Version']) + '(?, NULL)', [this.closureName]); + const row = await q.get('SELECT ClosureKey FROM Closures WHERE Name = ?', [this.closureName]); + return Number(row.ClosureKey); + }); + version = null; + } else { + closureKey = Number(closure.ClosureKey); + version = closure.Version; + } + const pending = await db.read(q => q.all(`SELECT c.ConceptKey, c.Code, s.Uri FROM Concepts c JOIN Spaces s ON s.SpaceKey = c.SpaceKey + WHERE c.InClosure = 0 ORDER BY c.ConceptKey LIMIT ${CLOSURE_BATCH}`)); + if (!pending.length) { + return 0; + } + const params = { resourceType: 'Parameters', parameter: [{ name: 'name', valueString: this.closureName }] }; + for (const c of pending) { + params.parameter.push({ name: 'concept', valueCoding: { system: c.Uri, code: c.Code } }); + } + if (version) { + params.parameter.push({ name: 'version', valueString: version }); + } + const r = await this.client.post('/$closure', params); + if (r.status !== 200 || !r.resource || r.resource.resourceType !== 'ConceptMap') { + throw new Error(`$closure failed (status ${r.status})`); + } + const pairs = []; + for (const g of r.resource.group || []) { + for (const e of g.element || []) { + for (const t of e.target || []) { + const rel = t.equivalence || t.relationship; + const src = { system: g.source, code: e.code }; + const tgt = { system: g.target, code: t.code }; + if (UP.has(rel)) { + pairs.push([tgt, src]); + } else if (DOWN.has(rel)) { + pairs.push([src, tgt]); + } + } + } + } + await db.write(async (q) => { + if (pairs.length) { + const systems = pairs.flatMap(([a, b]) => [a.system, b.system]); + const spaces = await ep.lookups.spaceKeys(q, systems); + const concepts = await ep.lookups.conceptKeys(q, pairs.flatMap(([a, b]) => [[spaces.get(a.system), a.code], [spaces.get(b.system), b.code]])); + const rows = pairs.map(([a, b]) => [concepts.get(spaces.get(a.system) + '|' + a.code), concepts.get(spaces.get(b.system) + '|' + b.code)]) + .filter(([a, b]) => a && b && a !== b); + for (let i = 0; i < rows.length; i += 300) { + const c = rows.slice(i, i + 300); + await q.run(q.dialect.insertIgnore('ClosureEntries', ['ClosureKey', 'SubsumesKey', 'SubsumedKey']) + c.map(() => '(?, ?, ?)').join(', '), + c.flatMap(([a, b]) => [closureKey, a, b])); + } + } + const keys = pending.map(p => Number(p.ConceptKey)); + await q.run(`UPDATE Concepts SET InClosure = 1 WHERE ConceptKey IN (${keys.map(() => '?').join(', ')})`, keys); + if (r.resource.version) { + await q.run('UPDATE Closures SET Version = ? WHERE ClosureKey = ?', [String(r.resource.version), closureKey]); + } + }); + return pending.length; + } +} + +/** A closure name for an endpoint: stable, and different for each endpoint's database */ +function closureName(path, instance) { + return 'fhirsmith-rest-' + crypto.createHash('sha256').update(path + '|' + instance).digest('hex').substring(0, 16); +} + +module.exports = { Terminology, closureName, MAX_EXPANSION }; diff --git a/rest/web.js b/rest/web.js new file mode 100644 index 00000000..28ed5054 --- /dev/null +++ b/rest/web.js @@ -0,0 +1,515 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The web interface over an endpoint's API: a browser (Accept: text/html, or _format=html) + * that GETs an endpoint's URLs gets pages instead of JSON. The same URLs, the same access + * checks, and the same interactions underneath: the pages are a view of what the API returns. + * + * [base] the endpoint: what it is, the resource types with how many of each, + * and the CapabilityStatement + * [base]/metadata the CapabilityStatement + * [base]/[type] the type: how many there are, and a search form built from its + * search parameters + * [base]/[type]?... search results (and history: [base]/_history, ...) + * [base]/[type]/[id] a resource: what identifies it, its narrative, and its JSON + * + * Writes stay JSON: there are no forms that change anything. The CapabilityStatement is drawn + * by the tx module's renderer, which needs the translations: they are loaded on the first page. + * + * @module rest/web + */ + +const path = require('path'); +const escape = require('escape-html'); +const parse5 = require('parse5'); +const htmlServer = require('../library/html-server'); +const { checkResourceNarratives } = require('../library/narrative-check'); + +const TEMPLATE = 'rest'; +const TEMPLATE_PATH = path.join(__dirname, 'html', 'rest-template.html'); + +// what a search parameter's value looks like, by type, for the form's placeholders +const HINTS = { + string: 'starts with (:exact, :contains)', + token: 'code, or system|code', + date: 'e.g. 2020-01-01, ge2020, lt2021-06', + number: 'e.g. 5, gt5.0', + quantity: 'value|system|code, e.g. gt5.4|http://unitsofmeasure.org|mmol/L', + reference: 'Type/id, or a URL', + uri: 'a URI (:below, :above)', + composite: 'values separated by $' +}; + +const COMMON = [ + { code: '_id', type: 'token', description: 'The resource\'s id' }, + { code: '_lastUpdated', type: 'date', description: 'When the resource was last changed' }, + { code: '_tag', type: 'token', description: 'A tag in the resource\'s meta' }, + { code: '_profile', type: 'uri', description: 'A profile the resource says it conforms to' }, + { code: '_security', type: 'token', description: 'A security label in the resource\'s meta' } +]; + +// the parameters that control a search rather than choose what it finds +const CONTROL = new Set(['_format', '_pretty', '_count', '_sort', '_summary', '_elements', '_total', '_include', '_revinclude']); + +let i18nPromise = null; + +/** The translations the tx module's renderer needs: loaded once, on the first page that needs them */ +function translations() { + if (!i18nPromise) { + i18nPromise = (async () => { + const { LanguageDefinitions } = require('../library/languages'); + const { I18nSupport } = require('../library/i18nsupport'); + const languages = await LanguageDefinitions.fromFiles(path.join(__dirname, '..', 'tx', 'data')); + const i18n = new I18nSupport(path.join(__dirname, '..', 'translations'), languages); + await i18n.load(); + return i18n; + })(); + i18nPromise.catch(() => { + i18nPromise = null; + }); + } + return i18nPromise; +} + +/** + * Whether a request is for a page: a GET (or HEAD) that asks for HTML, by _format or Accept. + * @param {Object} req + */ +function wantsHtml(req) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + return false; + } + const f = typeof req.query._format === 'string' ? req.query._format.trim().toLowerCase() : ''; + if (f) { + return f === 'html' || f === 'text/html'; + } + const accept = String(req.get('Accept') || '').toLowerCase(); + // a browser asks for text/html first; an API client that also takes */* isn't a browser + return accept.split(',').map(s => s.split(';')[0].trim()).includes('text/html'); +} + +/** The part of a parameter's description for one type (the core shares parameters across types) */ +function describeFor(description, type) { + if (!description) { + return ''; + } + const m = new RegExp(`\\* \\[${type}\\]\\([^)]*\\): ([^\\n]*)`).exec(description); + if (m) { + return m[1].trim(); + } + if (/^Multiple Resources/.test(description)) { + return ''; + } + return description.split('\n')[0].trim(); +} + +function fmtDate(ms) { + return new Date(ms).toISOString().replace('T', ' ').replace(/\.\d+Z$/, 'Z'); +} + +/** A short text for a resource: its name, title or text, where it has one */ +function displayOf(r) { + if (!r || typeof r !== 'object') { + return ''; + } + if (typeof r.title === 'string') { + return r.title; + } + if (typeof r.name === 'string') { + return r.name; + } + if (Array.isArray(r.name) && r.name[0]) { + const n = r.name[0]; + if (n.text) { + return n.text; + } + if (n.family || n.given) { + return [...(n.given || []), n.family].filter(x => x).join(' '); + } + } + for (const k of ['code', 'type', 'category']) { + const v = Array.isArray(r[k]) ? r[k][0] : r[k]; + if (v && typeof v === 'object') { + if (v.text) { + return v.text; + } + const c = (v.coding || [])[0]; + if (c && (c.display || c.code)) { + return c.display || c.code; + } + } + } + if (typeof r.description === 'string') { + return r.description.substring(0, 100); + } + return ''; +} + +class RestWeb { + /** + * @param {Object} ep - the Endpoint + */ + constructor(ep) { + this.ep = ep; + if (!htmlServer.hasTemplate(TEMPLATE)) { + htmlServer.loadTemplate(TEMPLATE, TEMPLATE_PATH); + } + } + + base(req) { + return req.baseUrl; + } + + send(req, res, status, title, content, start) { + const html = htmlServer.renderPage(TEMPLATE, title, content, { + endpointpath: req.baseUrl, + fhirversion: this.ep.settings.fhirVersion, + processingTime: Date.now() - start, + templateVars: { 'endpoint-name': this.ep.settings.name || 'Endpoint' } + }); + res.status(status).set('Content-Type', 'text/html; charset=utf-8'); + if (req.method === 'HEAD') { + res.end(); + } else { + res.send(html); + } + } + + /** + * A page for a request (already parsed and allowed): the endpoint, a type, or what the + * interaction returned. + * @param {Object} req + * @param {Object} res + * @param {Object} freq - from request.js + * @param {Object} access - from access.js + * @param {number} start + */ + async page(req, res, freq, access, start) { + // a page for the endpoint or a type when nothing is asked of it; any parameter is a search + const asked = freq.params.filter(([n]) => n !== '_format' && n !== '_pretty').length > 0; + if (freq.interaction === 'search-system' && !freq.compartment && !asked) { + return this.home(req, res, freq, start); + } + if (freq.interaction === 'capabilities') { + const r = await this.ep.dispatch(freq, { access }); + return this.send(req, res, 200, 'Capability Statement', await this.capabilityStatement(r.resource), start); + } + if (freq.interaction === 'search-type' && !freq.compartment && !asked && !freq.segments.includes('_search')) { + return this.typeHome(req, res, freq, start); + } + const r = await this.ep.dispatch(freq, { access }); + if (r.status === 304) { + res.status(304).end(); + return; + } + const resource = r.resource; + if (!resource) { + return this.send(req, res, r.status, 'Done', this.outcome(r.outcome ? { issue: [r.outcome] } : { issue: [] }), start); + } + if (resource.resourceType === 'Bundle') { + const title = freq.interaction.startsWith('history') ? `History${freq.type ? ': ' + freq.type : ''}${freq.id ? '/' + freq.id : ''}` + : `Search${freq.type ? ': ' + freq.type : ''}`; + return this.send(req, res, r.status, title, await this.bundle(req, freq, resource), start); + } + if (resource.resourceType === 'OperationOutcome') { + return this.send(req, res, r.status, 'Outcome', this.outcome(resource), start); + } + if (resource.resourceType === 'Parameters') { + return this.send(req, res, r.status, `$${freq.operation || 'operation'}`, this.json(resource, true), start); + } + const title = `${resource.resourceType}/${resource.id}${freq.vid ? ' (version ' + freq.vid + ')' : ''}`; + return this.send(req, res, r.status, title, await this.resource(req, resource), start); + } + + /** An error as a page; 401 with a link to log in */ + error(req, res, fe, start) { + let content = this.outcome(fe.outcome()); + if (fe.status === 401) { + let login = '/auth/login'; + try { + login = require('../library/auth').loginUrl(req); + } catch (e) { + // no logins on this server + } + content += `

Log in

`; + } + for (const [k, v] of Object.entries(fe.headers || {})) { + res.set(k, v); + } + this.send(req, res, fe.status, fe.status === 404 ? 'Not found' : fe.status === 410 ? 'Deleted' : 'Error', content, start); + } + + // ---- the endpoint ---- + + async counts() { + const rows = await this.ep.db.read(q => q.all('SELECT TypeKey, COUNT(*) AS N FROM Ids WHERE Deleted = 0 AND MostRecent IS NOT NULL GROUP BY TypeKey')); + const byKey = new Map(rows.map(r => [Number(r.TypeKey), Number(r.N)])); + const out = new Map(); + for (const [type, key] of this.ep.typeKeys) { + out.set(type, byKey.get(key) || 0); + } + return out; + } + + async home(req, res, freq, start) { + const ep = this.ep; + const s = ep.settings; + const base = this.base(req); + const counts = await this.counts(); + const types = [...ep.typeKeys.keys()].filter(t => ep.typeSupported(t)).sort(); + const total = types.reduce((n, t) => n + counts.get(t), 0); + let html = ''; + if (s.description) { + html += `

${escape(s.description)}

`; + } + html += ''; + const row = (k, v) => ``; + html += row('Address', `${escape(freq.base)}`); + html += row('FHIR version', escape(s.fhirVersion)); + if (s.packages && s.packages.length) { + html += row('Packages', escape(s.packages.join(', '))); + } + html += row('Resources', `${total.toLocaleString()} (current versions, of ${types.length} types)`); + html += row('Access', s.anonymous === 'write' ? 'anyone can read and write' : s.anonymous === 'read' ? 'anyone can read; writing needs a login' : 'a login or an API token'); + html += row('Server-assigned ids', s.idStrategy === 'uuid' ? 'UUIDs' : 'numbers'); + html += row('Create by PUT', s.createOnUpdate ? 'yes' : 'no'); + html += row('Reference checks', s.checkReferences ? 'on' : 'off'); + if (s.txServer) { + html += row('Terminology server', escape(s.txServer)); + } + html += '
${escape(k)}${v}
'; + + html += '

Resource types

'; + const used = types.filter(t => counts.get(t) > 0); + const empty = types.filter(t => counts.get(t) === 0); + if (used.length) { + html += ''; + for (const t of used) { + const u = `${base}/${encodeURIComponent(t)}`; + html += `` + + ``; + } + html += '
TypeResources
${escape(t)}${counts.get(t).toLocaleString()}latest
'; + } else { + html += '

There are no resources yet.

'; + } + if (empty.length) { + html += `

${used.length ? 'Also supported, with none yet' : 'Supported'}: ` + + empty.map(t => `${escape(t)}`).join(', ') + '

'; + } + + html += '

Capability Statement

'; + const cs = await ep.dispatch({ ...freq, interaction: 'capabilities' }, {}); + html += await this.capabilityStatement(cs.resource); + return this.send(req, res, 200, s.name || 'FHIR server', html, start); + } + + async capabilityStatement(cs) { + try { + const { Renderer } = require('../tx/library/renderer'); + const { OperationContext } = require('../tx/operation-context'); + const i18n = await translations(); + const html = await new Renderer(new OperationContext('en', i18n)).renderCapabilityStatement(cs); + return `
${html}
` + this.json(cs, false); + } catch (e) { + this.ep.log.warn(`Rest ${this.ep.path}: the CapabilityStatement couldn't be drawn: ${e.message}`); + return this.json(cs, true); + } + } + + // ---- a type ---- + + /** The search parameters a type's form offers: the common ones, then its own by name */ + formParams(type) { + const own = [...this.ep.definitions.forType(type).values()] + .filter(d => d.key !== null && d.key !== undefined) + .map(d => ({ code: d.code, type: d.type, description: describeFor(d.description, type) })) + .sort((a, b) => a.code.localeCompare(b.code)); + return [...COMMON, ...own]; + } + + async typeHome(req, res, freq, start) { + const ep = this.ep; + const type = freq.type; + ep.checkType(type, 'search-type'); + const base = this.base(req); + const n = (await this.counts()).get(type) || 0; + const action = `${base}/${encodeURIComponent(type)}`; + let html = `

${n.toLocaleString()} ${escape(type)} resource${n === 1 ? '' : 's'}. ` + + `The latest  |  ` + + `History

`; + const params = this.formParams(type); + html += `
`; + html += ''; + for (const p of params) { + const id = 'sp_' + p.code.replace(/[^A-Za-z0-9_-]/g, '_'); + html += `` + + `` + + ``; + } + html += '
ParameterValueDescription

${escape(p.type)}
${escape(p.description || '')}
'; + const sortable = params.filter(p => p.type !== 'composite'); + html += '

'; + html += '   '; + html += `   `; + html += ' '; + html += '

'; + html += '

' + + 'Empty fields are left out. Repeat a parameter in the URL to AND values; separate values with commas to OR them.

'; + html += '
'; + // empty fields would otherwise each send name= + html += ``; + return this.send(req, res, 200, type, html, start); + } + + // ---- what the API returned ---- + + pager(bundle) { + const links = bundle.link || []; + const order = ['first', 'previous', 'next', 'last']; + const items = order.map(rel => links.find(l => l.relation === rel)).filter(l => l); + if (!items.length) { + return ''; + } + const rel = (u) => u.replace(/^https?:\/\/[^/]+/, ''); + return ''; + } + + async bundle(req, freq, bundle) { + const base = this.base(req); + const entries = bundle.entry || []; + const matches = entries.filter(e => e.resource && (!e.search || e.search.mode !== 'outcome')); + const outcomes = entries.filter(e => e.search && e.search.mode === 'outcome'); + let html = ''; + for (const o of outcomes) { + html += this.outcome(o.resource); + } + const criteria = freq.params.filter(([n]) => !CONTROL.has(n) && n !== '_getpages' && n !== '_offset'); + if (criteria.length) { + html += '

Where ' + criteria.map(([n, v]) => `${escape(n)} = ${escape(v)}`).join(' and ') + '

'; + } + if (typeof bundle.total === 'number') { + html += `

${bundle.total.toLocaleString()} found${matches.length < bundle.total ? `, ${matches.length} on this page` : ''}.

`; + } else if (bundle.type === 'searchset') { + html += `

${matches.length} on this page.

`; + } + if (freq.type && freq.interaction === 'search-type' && !freq.compartment) { + html += `

New search

`; + } + html += this.pager(bundle); + if (matches.length) { + html += ''; + for (const e of entries) { + if (e.search && e.search.mode === 'outcome') { + continue; + } + const r = e.resource; + const req2 = e.request; + if (!r) { + // a deletion, in history + const what = req2 ? req2.url : ''; + html += `` + + ``; + continue; + } + const link = `${base}/${encodeURIComponent(r.resourceType)}/${encodeURIComponent(r.id)}`; + const vid = r.meta && r.meta.versionId; + const vlink = vid ? `${link}/_history/${encodeURIComponent(vid)}` : link; + const mode = e.search && e.search.mode === 'include' ? ' included' : ''; + const op = req2 ? ` (${escape(req2.method === 'POST' ? 'created' : req2.method === 'PUT' ? 'updated' : req2.method)})` : ''; + html += `` + + `` + + `` + + ``; + } + html += '
ResourceSummaryVersionUpdated
${escape(what)}deleted${escape((e.response && e.response.etag || '').replace(/^W\/"|"$/g, ''))}${escape(e.response && e.response.lastModified ? e.response.lastModified : '')}
${escape(r.resourceType)}/${escape(r.id)}${mode}${escape(displayOf(r))}${escape(vid || '')}${op}${escape(r.meta && r.meta.lastUpdated ? r.meta.lastUpdated.replace('T', ' ').replace(/\.\d+Z$/, 'Z') : '')}JSON
'; + } + html += this.pager(bundle); + return html; + } + + /** The things that identify a resource, as table rows */ + identity(req, r) { + const base = this.base(req); + const rows = []; + const add = (k, v) => { + if (v) { + rows.push(`
${escape(k)}${v}
${rows.join('')}
`; + } + + async resource(req, r) { + let html = this.identity(req, r); + html += '

Narrative

'; + html += this.narrative(r); + html += this.json(r, false); + return html; + } + + /** The resource's narrative, made safe: none if it carries active content */ + narrative(r) { + const found = checkResourceNarratives({ resourceType: r.resourceType, id: r.id, text: r.text }); + if (found) { + return `
This narrative is not shown: ${escape(found)}
`; + } + const div = r.text && r.text.div; + if (typeof div !== 'string' || !div) { + return '

The resource has no narrative.

'; + } + // the parsed tree written out again, never the string as it is: an unterminated tag + // would otherwise swallow the rest of the page + return `
${parse5.serialize(parse5.parseFragment(div))}
`; + } + + json(resource, open) { + const id = 'json_' + Math.random().toString(36).substring(2, 10); + return `
` + + `
${escape(JSON.stringify(resource, null, 2))}
`; + } + + outcome(oo) { + const cls = { fatal: 'alert-danger', error: 'alert-danger', warning: 'alert-warning', information: 'alert-info' }; + return (oo.issue || []).map(i => `
` + + `${escape((i.details && i.details.text) || i.diagnostics || i.code)}
`).join(''); + } +} + +module.exports = { RestWeb, wantsHtml, describeFor, displayOf }; diff --git a/server.js b/server.js index 48b40acc..e7802eac 100644 --- a/server.js +++ b/server.js @@ -160,6 +160,7 @@ const NpmProjectorModule = require('./npmprojector/npmprojector.js'); const TXModule = require('./tx/tx.js'); const TestingModule = require('./testing/testing.js'); const IpsModule = require('./ips/ips.js'); +const RestModule = require('./rest/rest.js'); const htmlServer = require('./library/html-server'); const auth = require('./library/auth'); @@ -481,6 +482,22 @@ async function initializeModules() { } } + // Initialize the rest module: database-backed FHIR endpoints, mounted at their own paths + // like the tx module's. After tx, so an endpoint's terminology server can be the tx module's + // own endpoint, in process. On a worker its endpoints leave migrations and jobs to the master + if (config.modules?.rest?.enabled) { + try { + serverLog.info('Initializing module: rest...'); + modules.rest = new RestModule(stats.forModule('rest')); + await modules.rest.initialize(config.modules.rest, app, { + hostName: config.hostName, master: !role || role.role === 'master', maxBody + }); + } catch (error) { + serverLog.error('Failed to initialize rest module:', error); + throw error; + } + } + if (config.modules?.folder?.enabled) { try { serverLog.info('Initializing module: folder...'); @@ -753,6 +770,13 @@ async function buildRootPageContent() { content += ''; } + if (config.modules?.rest?.enabled) { + content += '
  • '; + content += 'FHIR REST: database-backed FHIR servers: '; + content += (config.modules.rest.endpoints || []).map(e => `${escape(String(e.path))}`).join(', '); + content += '
  • '; + } + if (config.modules?.folder?.enabled) { content += '
  • '; content += 'Cache Folder: '; diff --git a/tests/data/rest/r4-definitions.json b/tests/data/rest/r4-definitions.json new file mode 100644 index 00000000..4aa6bf9b --- /dev/null +++ b/tests/data/rest/r4-definitions.json @@ -0,0 +1,4305 @@ +{ + "fhirVersion": "4.0.1", + "resourceTypes": [ + "AuditEvent", + "Condition", + "Device", + "Encounter", + "Group", + "List", + "MedicationRequest", + "Observation", + "Organization", + "Patient", + "Practitioner", + "RelatedPerson", + "SearchParameter", + "ValueSet" + ], + "searchParameters": [ + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-action", + "code": "action", + "type": "token", + "expression": "AuditEvent.action", + "base": [ + "AuditEvent" + ], + "description": "Type of action performed during the event", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-address", + "code": "address", + "type": "string", + "expression": "AuditEvent.agent.network.address", + "base": [ + "AuditEvent" + ], + "description": "Identifier for the network access point of the user device", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-agent-name", + "code": "agent-name", + "type": "string", + "expression": "AuditEvent.agent.name", + "base": [ + "AuditEvent" + ], + "description": "Human friendly name for the agent", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-agent-role", + "code": "agent-role", + "type": "token", + "expression": "AuditEvent.agent.role", + "base": [ + "AuditEvent" + ], + "description": "Agent role in the event", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-agent", + "code": "agent", + "type": "reference", + "expression": "AuditEvent.agent.who", + "base": [ + "AuditEvent" + ], + "description": "Identifier of who", + "target": [ + "Practitioner", + "Organization", + "Device", + "Patient", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-altid", + "code": "altid", + "type": "token", + "expression": "AuditEvent.agent.altId", + "base": [ + "AuditEvent" + ], + "description": "Alternative User identity", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-date", + "code": "date", + "type": "date", + "expression": "AuditEvent.recorded", + "base": [ + "AuditEvent" + ], + "description": "Time when the event was recorded", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-entity-name", + "code": "entity-name", + "type": "string", + "expression": "AuditEvent.entity.name", + "base": [ + "AuditEvent" + ], + "description": "Descriptor for entity", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-entity-role", + "code": "entity-role", + "type": "token", + "expression": "AuditEvent.entity.role", + "base": [ + "AuditEvent" + ], + "description": "What role the entity played", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-entity-type", + "code": "entity-type", + "type": "token", + "expression": "AuditEvent.entity.type", + "base": [ + "AuditEvent" + ], + "description": "Type of entity involved", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-entity", + "code": "entity", + "type": "reference", + "expression": "AuditEvent.entity.what", + "base": [ + "AuditEvent" + ], + "description": "Specific instance of resource", + "target": [ + "Account", + "ActivityDefinition", + "AdverseEvent", + "AllergyIntolerance", + "Appointment", + "AppointmentResponse", + "AuditEvent", + "Basic", + "Binary", + "BiologicallyDerivedProduct", + "BodyStructure", + "Bundle", + "CapabilityStatement", + "CarePlan", + "CareTeam", + "CatalogEntry", + "ChargeItem", + "ChargeItemDefinition", + "Claim", + "ClaimResponse", + "ClinicalImpression", + "CodeSystem", + "Communication", + "CommunicationRequest", + "CompartmentDefinition", + "Composition", + "ConceptMap", + "Condition", + "Consent", + "Contract", + "Coverage", + "CoverageEligibilityRequest", + "CoverageEligibilityResponse", + "DetectedIssue", + "Device", + "DeviceDefinition", + "DeviceMetric", + "DeviceRequest", + "DeviceUseStatement", + "DiagnosticReport", + "DocumentManifest", + "DocumentReference", + "EffectEvidenceSynthesis", + "Encounter", + "Endpoint", + "EnrollmentRequest", + "EnrollmentResponse", + "EpisodeOfCare", + "EventDefinition", + "Evidence", + "EvidenceVariable", + "ExampleScenario", + "ExplanationOfBenefit", + "FamilyMemberHistory", + "Flag", + "Goal", + "GraphDefinition", + "Group", + "GuidanceResponse", + "HealthcareService", + "ImagingStudy", + "Immunization", + "ImmunizationEvaluation", + "ImmunizationRecommendation", + "ImplementationGuide", + "InsurancePlan", + "Invoice", + "Library", + "Linkage", + "List", + "Location", + "Measure", + "MeasureReport", + "Media", + "Medication", + "MedicationAdministration", + "MedicationDispense", + "MedicationKnowledge", + "MedicationRequest", + "MedicationStatement", + "MedicinalProduct", + "MedicinalProductAuthorization", + "MedicinalProductContraindication", + "MedicinalProductIndication", + "MedicinalProductIngredient", + "MedicinalProductInteraction", + "MedicinalProductManufactured", + "MedicinalProductPackaged", + "MedicinalProductPharmaceutical", + "MedicinalProductUndesirableEffect", + "MessageDefinition", + "MessageHeader", + "MolecularSequence", + "NamingSystem", + "NutritionOrder", + "Observation", + "ObservationDefinition", + "OperationDefinition", + "OperationOutcome", + "Organization", + "OrganizationAffiliation", + "Patient", + "PaymentNotice", + "PaymentReconciliation", + "Person", + "PlanDefinition", + "Practitioner", + "PractitionerRole", + "Procedure", + "Provenance", + "Questionnaire", + "QuestionnaireResponse", + "RelatedPerson", + "RequestGroup", + "ResearchDefinition", + "ResearchElementDefinition", + "ResearchStudy", + "ResearchSubject", + "RiskAssessment", + "RiskEvidenceSynthesis", + "Schedule", + "SearchParameter", + "ServiceRequest", + "Slot", + "Specimen", + "SpecimenDefinition", + "StructureDefinition", + "StructureMap", + "Subscription", + "Substance", + "SubstanceNucleicAcid", + "SubstancePolymer", + "SubstanceProtein", + "SubstanceReferenceInformation", + "SubstanceSourceMaterial", + "SubstanceSpecification", + "SupplyDelivery", + "SupplyRequest", + "Task", + "TerminologyCapabilities", + "TestReport", + "TestScript", + "ValueSet", + "VerificationResult", + "VisionPrescription" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-outcome", + "code": "outcome", + "type": "token", + "expression": "AuditEvent.outcome", + "base": [ + "AuditEvent" + ], + "description": "Whether the event succeeded or failed", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-patient", + "code": "patient", + "type": "reference", + "expression": "AuditEvent.agent.who.where(resolve() is Patient) | AuditEvent.entity.what.where(resolve() is Patient)", + "base": [ + "AuditEvent" + ], + "description": "Identifier of who", + "target": [ + "Patient" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-policy", + "code": "policy", + "type": "uri", + "expression": "AuditEvent.agent.policy", + "base": [ + "AuditEvent" + ], + "description": "Policy that authorized event", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-site", + "code": "site", + "type": "token", + "expression": "AuditEvent.source.site", + "base": [ + "AuditEvent" + ], + "description": "Logical source location within the enterprise", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-source", + "code": "source", + "type": "reference", + "expression": "AuditEvent.source.observer", + "base": [ + "AuditEvent" + ], + "description": "The identity of source detecting the event", + "target": [ + "Practitioner", + "Organization", + "Device", + "Patient", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-subtype", + "code": "subtype", + "type": "token", + "expression": "AuditEvent.subtype", + "base": [ + "AuditEvent" + ], + "description": "More specific type/id for the event", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/AuditEvent-type", + "code": "type", + "type": "token", + "expression": "AuditEvent.type", + "base": [ + "AuditEvent" + ], + "description": "Type/identifier of event", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/clinical-code", + "code": "code", + "type": "token", + "expression": "AllergyIntolerance.code | AllergyIntolerance.reaction.substance | Condition.code | (DeviceRequest.code as CodeableConcept) | DiagnosticReport.code | FamilyMemberHistory.condition.code | List.code | Medication.code | (MedicationAdministration.medication as CodeableConcept) | (MedicationDispense.medication as CodeableConcept) | (MedicationRequest.medication as CodeableConcept) | (MedicationStatement.medication as CodeableConcept) | Observation.code | Procedure.code | ServiceRequest.code", + "base": [ + "Condition", + "List", + "MedicationRequest", + "Observation" + ], + "description": "Multiple Resources: \r\n\r\n* [AllergyIntolerance](allergyintolerance.html): Code that identifies the allergy or intolerance\r\n* [Condition](condition.html): Code for the condition\r\n* [DeviceRequest](devicerequest.html): Code for what is being requested/ordered\r\n* [DiagnosticReport](diagnosticreport.html): The code for the report, as opposed to codes for the atomic results, which are the names on the observation resource referred to from the result\r\n* [FamilyMemberHistory](familymemberhistory.html): A search by a condition code\r\n* [List](list.html): What the purpose of this list is\r\n* [Medication](medication.html): Returns medications for a specific code\r\n* [MedicationAdministration](medicationadministration.html): Return administrations of this medication code\r\n* [MedicationDispense](medicationdispense.html): Returns dispenses of this medicine code\r\n* [MedicationRequest](medicationrequest.html): Return prescriptions of this medication code\r\n* [MedicationStatement](medicationstatement.html): Return statements of this medication code\r\n* [Observation](observation.html): The code of the observation type\r\n* [Procedure](procedure.html): A code to identify a procedure\r\n* [ServiceRequest](servicerequest.html): What is being requested/ordered\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/clinical-date", + "code": "date", + "type": "date", + "expression": "AllergyIntolerance.recordedDate | CarePlan.period | CareTeam.period | ClinicalImpression.date | Composition.date | Consent.dateTime | DiagnosticReport.effective | Encounter.period | EpisodeOfCare.period | FamilyMemberHistory.date | Flag.period | Immunization.occurrence | List.date | Observation.effective | Procedure.performed | (RiskAssessment.occurrence as dateTime) | SupplyRequest.authoredOn", + "base": [ + "Encounter", + "List", + "Observation" + ], + "description": "Multiple Resources: \r\n\r\n* [AllergyIntolerance](allergyintolerance.html): Date first version of the resource instance was recorded\r\n* [CarePlan](careplan.html): Time period plan covers\r\n* [CareTeam](careteam.html): Time period team covers\r\n* [ClinicalImpression](clinicalimpression.html): When the assessment was documented\r\n* [Composition](composition.html): Composition editing time\r\n* [Consent](consent.html): When this Consent was created or indexed\r\n* [DiagnosticReport](diagnosticreport.html): The clinically relevant time of the report\r\n* [Encounter](encounter.html): A date within the period the Encounter lasted\r\n* [EpisodeOfCare](episodeofcare.html): The provided date search value falls within the episode of care's period\r\n* [FamilyMemberHistory](familymemberhistory.html): When history was recorded or last updated\r\n* [Flag](flag.html): Time period when flag is active\r\n* [Immunization](immunization.html): Vaccination (non)-Administration Date\r\n* [List](list.html): When the list was prepared\r\n* [Observation](observation.html): Obtained date/time. If the obtained element is a period, a date that falls in the period\r\n* [Procedure](procedure.html): When the procedure was performed\r\n* [RiskAssessment](riskassessment.html): When was assessment made?\r\n* [SupplyRequest](supplyrequest.html): When the request was made\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/clinical-encounter", + "code": "encounter", + "type": "reference", + "expression": "Composition.encounter | DeviceRequest.encounter | DiagnosticReport.encounter | DocumentReference.context.encounter | Flag.encounter | List.encounter | NutritionOrder.encounter | Observation.encounter | Procedure.encounter | RiskAssessment.encounter | ServiceRequest.encounter | VisionPrescription.encounter", + "base": [ + "List", + "Observation" + ], + "description": "Multiple Resources: \r\n\r\n* [Composition](composition.html): Context of the Composition\r\n* [DeviceRequest](devicerequest.html): Encounter during which request was created\r\n* [DiagnosticReport](diagnosticreport.html): The Encounter when the order was made\r\n* [DocumentReference](documentreference.html): Context of the document content\r\n* [Flag](flag.html): Alert relevant during encounter\r\n* [List](list.html): Context in which list created\r\n* [NutritionOrder](nutritionorder.html): Return nutrition orders with this encounter identifier\r\n* [Observation](observation.html): Encounter related to the observation\r\n* [Procedure](procedure.html): Encounter created as part of\r\n* [RiskAssessment](riskassessment.html): Where was assessment performed?\r\n* [ServiceRequest](servicerequest.html): An encounter in which this request is made\r\n* [VisionPrescription](visionprescription.html): Return prescriptions with this encounter identifier\r\n", + "target": [ + "Encounter", + "EpisodeOfCare" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/clinical-identifier", + "code": "identifier", + "type": "token", + "expression": "AllergyIntolerance.identifier | CarePlan.identifier | CareTeam.identifier | Composition.identifier | Condition.identifier | Consent.identifier | DetectedIssue.identifier | DeviceRequest.identifier | DiagnosticReport.identifier | DocumentManifest.masterIdentifier | DocumentManifest.identifier | DocumentReference.masterIdentifier | DocumentReference.identifier | Encounter.identifier | EpisodeOfCare.identifier | FamilyMemberHistory.identifier | Goal.identifier | ImagingStudy.identifier | Immunization.identifier | List.identifier | MedicationAdministration.identifier | MedicationDispense.identifier | MedicationRequest.identifier | MedicationStatement.identifier | NutritionOrder.identifier | Observation.identifier | Procedure.identifier | RiskAssessment.identifier | ServiceRequest.identifier | SupplyDelivery.identifier | SupplyRequest.identifier | VisionPrescription.identifier", + "base": [ + "Condition", + "Encounter", + "List", + "MedicationRequest", + "Observation" + ], + "description": "Multiple Resources: \r\n\r\n* [AllergyIntolerance](allergyintolerance.html): External ids for this item\r\n* [CarePlan](careplan.html): External Ids for this plan\r\n* [CareTeam](careteam.html): External Ids for this team\r\n* [Composition](composition.html): Version-independent identifier for the Composition\r\n* [Condition](condition.html): A unique identifier of the condition record\r\n* [Consent](consent.html): Identifier for this record (external references)\r\n* [DetectedIssue](detectedissue.html): Unique id for the detected issue\r\n* [DeviceRequest](devicerequest.html): Business identifier for request/order\r\n* [DiagnosticReport](diagnosticreport.html): An identifier for the report\r\n* [DocumentManifest](documentmanifest.html): Unique Identifier for the set of documents\r\n* [DocumentReference](documentreference.html): Master Version Specific Identifier\r\n* [Encounter](encounter.html): Identifier(s) by which this encounter is known\r\n* [EpisodeOfCare](episodeofcare.html): Business Identifier(s) relevant for this EpisodeOfCare\r\n* [FamilyMemberHistory](familymemberhistory.html): A search by a record identifier\r\n* [Goal](goal.html): External Ids for this goal\r\n* [ImagingStudy](imagingstudy.html): Identifiers for the Study, such as DICOM Study Instance UID and Accession number\r\n* [Immunization](immunization.html): Business identifier\r\n* [List](list.html): Business identifier\r\n* [MedicationAdministration](medicationadministration.html): Return administrations with this external identifier\r\n* [MedicationDispense](medicationdispense.html): Returns dispenses with this external identifier\r\n* [MedicationRequest](medicationrequest.html): Return prescriptions with this external identifier\r\n* [MedicationStatement](medicationstatement.html): Return statements with this external identifier\r\n* [NutritionOrder](nutritionorder.html): Return nutrition orders with this external identifier\r\n* [Observation](observation.html): The unique id for a particular observation\r\n* [Procedure](procedure.html): A unique identifier for a procedure\r\n* [RiskAssessment](riskassessment.html): Unique identifier for the assessment\r\n* [ServiceRequest](servicerequest.html): Identifiers assigned to this order\r\n* [SupplyDelivery](supplydelivery.html): External identifier\r\n* [SupplyRequest](supplyrequest.html): Business Identifier for SupplyRequest\r\n* [VisionPrescription](visionprescription.html): Return prescriptions with this external identifier\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/clinical-patient", + "code": "patient", + "type": "reference", + "expression": "AllergyIntolerance.patient | CarePlan.subject.where(resolve() is Patient) | CareTeam.subject.where(resolve() is Patient) | ClinicalImpression.subject.where(resolve() is Patient) | Composition.subject.where(resolve() is Patient) | Condition.subject.where(resolve() is Patient) | Consent.patient | DetectedIssue.patient | DeviceRequest.subject.where(resolve() is Patient) | DeviceUseStatement.subject | DiagnosticReport.subject.where(resolve() is Patient) | DocumentManifest.subject.where(resolve() is Patient) | DocumentReference.subject.where(resolve() is Patient) | Encounter.subject.where(resolve() is Patient) | EpisodeOfCare.patient | FamilyMemberHistory.patient | Flag.subject.where(resolve() is Patient) | Goal.subject.where(resolve() is Patient) | ImagingStudy.subject.where(resolve() is Patient) | Immunization.patient | List.subject.where(resolve() is Patient) | MedicationAdministration.subject.where(resolve() is Patient) | MedicationDispense.subject.where(resolve() is Patient) | MedicationRequest.subject.where(resolve() is Patient) | MedicationStatement.subject.where(resolve() is Patient) | NutritionOrder.patient | Observation.subject.where(resolve() is Patient) | Procedure.subject.where(resolve() is Patient) | RiskAssessment.subject.where(resolve() is Patient) | ServiceRequest.subject.where(resolve() is Patient) | SupplyDelivery.patient | VisionPrescription.patient", + "base": [ + "Condition", + "Encounter", + "List", + "MedicationRequest", + "Observation" + ], + "description": "Multiple Resources: \r\n\r\n* [AllergyIntolerance](allergyintolerance.html): Who the sensitivity is for\r\n* [CarePlan](careplan.html): Who the care plan is for\r\n* [CareTeam](careteam.html): Who care team is for\r\n* [ClinicalImpression](clinicalimpression.html): Patient or group assessed\r\n* [Composition](composition.html): Who and/or what the composition is about\r\n* [Condition](condition.html): Who has the condition?\r\n* [Consent](consent.html): Who the consent applies to\r\n* [DetectedIssue](detectedissue.html): Associated patient\r\n* [DeviceRequest](devicerequest.html): Individual the service is ordered for\r\n* [DeviceUseStatement](deviceusestatement.html): Search by subject - a patient\r\n* [DiagnosticReport](diagnosticreport.html): The subject of the report if a patient\r\n* [DocumentManifest](documentmanifest.html): The subject of the set of documents\r\n* [DocumentReference](documentreference.html): Who/what is the subject of the document\r\n* [Encounter](encounter.html): The patient or group present at the encounter\r\n* [EpisodeOfCare](episodeofcare.html): The patient who is the focus of this episode of care\r\n* [FamilyMemberHistory](familymemberhistory.html): The identity of a subject to list family member history items for\r\n* [Flag](flag.html): The identity of a subject to list flags for\r\n* [Goal](goal.html): Who this goal is intended for\r\n* [ImagingStudy](imagingstudy.html): Who the study is about\r\n* [Immunization](immunization.html): The patient for the vaccination record\r\n* [List](list.html): If all resources have the same subject\r\n* [MedicationAdministration](medicationadministration.html): The identity of a patient to list administrations for\r\n* [MedicationDispense](medicationdispense.html): The identity of a patient to list dispenses for\r\n* [MedicationRequest](medicationrequest.html): Returns prescriptions for a specific patient\r\n* [MedicationStatement](medicationstatement.html): Returns statements for a specific patient.\r\n* [NutritionOrder](nutritionorder.html): The identity of the person who requires the diet, formula or nutritional supplement\r\n* [Observation](observation.html): The subject that the observation is about (if patient)\r\n* [Procedure](procedure.html): Search by subject - a patient\r\n* [RiskAssessment](riskassessment.html): Who/what does assessment apply to?\r\n* [ServiceRequest](servicerequest.html): Search by subject - a patient\r\n* [SupplyDelivery](supplydelivery.html): Patient for whom the item is supplied\r\n* [VisionPrescription](visionprescription.html): The identity of a patient to list dispenses for\r\n", + "target": [ + "Patient", + "Group" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/clinical-type", + "code": "type", + "type": "token", + "expression": "AllergyIntolerance.type | Composition.type | DocumentManifest.type | DocumentReference.type | Encounter.type | EpisodeOfCare.type", + "base": [ + "Encounter" + ], + "description": "Multiple Resources: \r\n\r\n* [AllergyIntolerance](allergyintolerance.html): allergy | intolerance - Underlying mechanism (if known)\r\n* [Composition](composition.html): Kind of composition (LOINC if possible)\r\n* [DocumentManifest](documentmanifest.html): Kind of document set\r\n* [DocumentReference](documentreference.html): Kind of document (LOINC if possible)\r\n* [Encounter](encounter.html): Specific type of encounter\r\n* [EpisodeOfCare](episodeofcare.html): Type/class - e.g. specialist referral, disease management\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-abatement-age", + "code": "abatement-age", + "type": "quantity", + "expression": "Condition.abatement.as(Age) | Condition.abatement.as(Range)", + "base": [ + "Condition" + ], + "description": "Abatement as age or age range", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-abatement-date", + "code": "abatement-date", + "type": "date", + "expression": "Condition.abatement.as(dateTime) | Condition.abatement.as(Period)", + "base": [ + "Condition" + ], + "description": "Date-related abatements (dateTime and period)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-abatement-string", + "code": "abatement-string", + "type": "string", + "expression": "Condition.abatement.as(string)", + "base": [ + "Condition" + ], + "description": "Abatement as a string", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-asserter", + "code": "asserter", + "type": "reference", + "expression": "Condition.asserter", + "base": [ + "Condition" + ], + "description": "Person who asserts this condition", + "target": [ + "Practitioner", + "Patient", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-body-site", + "code": "body-site", + "type": "token", + "expression": "Condition.bodySite", + "base": [ + "Condition" + ], + "description": "Anatomical location, if relevant", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-category", + "code": "category", + "type": "token", + "expression": "Condition.category", + "base": [ + "Condition" + ], + "description": "The category of the condition", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-clinical-status", + "code": "clinical-status", + "type": "token", + "expression": "Condition.clinicalStatus", + "base": [ + "Condition" + ], + "description": "The clinical status of the condition", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-encounter", + "code": "encounter", + "type": "reference", + "expression": "Condition.encounter", + "base": [ + "Condition" + ], + "description": "Encounter created as part of", + "target": [ + "Encounter" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-evidence-detail", + "code": "evidence-detail", + "type": "reference", + "expression": "Condition.evidence.detail", + "base": [ + "Condition" + ], + "description": "Supporting information found elsewhere", + "target": [ + "Account", + "ActivityDefinition", + "AdverseEvent", + "AllergyIntolerance", + "Appointment", + "AppointmentResponse", + "AuditEvent", + "Basic", + "Binary", + "BiologicallyDerivedProduct", + "BodyStructure", + "Bundle", + "CapabilityStatement", + "CarePlan", + "CareTeam", + "CatalogEntry", + "ChargeItem", + "ChargeItemDefinition", + "Claim", + "ClaimResponse", + "ClinicalImpression", + "CodeSystem", + "Communication", + "CommunicationRequest", + "CompartmentDefinition", + "Composition", + "ConceptMap", + "Condition", + "Consent", + "Contract", + "Coverage", + "CoverageEligibilityRequest", + "CoverageEligibilityResponse", + "DetectedIssue", + "Device", + "DeviceDefinition", + "DeviceMetric", + "DeviceRequest", + "DeviceUseStatement", + "DiagnosticReport", + "DocumentManifest", + "DocumentReference", + "EffectEvidenceSynthesis", + "Encounter", + "Endpoint", + "EnrollmentRequest", + "EnrollmentResponse", + "EpisodeOfCare", + "EventDefinition", + "Evidence", + "EvidenceVariable", + "ExampleScenario", + "ExplanationOfBenefit", + "FamilyMemberHistory", + "Flag", + "Goal", + "GraphDefinition", + "Group", + "GuidanceResponse", + "HealthcareService", + "ImagingStudy", + "Immunization", + "ImmunizationEvaluation", + "ImmunizationRecommendation", + "ImplementationGuide", + "InsurancePlan", + "Invoice", + "Library", + "Linkage", + "List", + "Location", + "Measure", + "MeasureReport", + "Media", + "Medication", + "MedicationAdministration", + "MedicationDispense", + "MedicationKnowledge", + "MedicationRequest", + "MedicationStatement", + "MedicinalProduct", + "MedicinalProductAuthorization", + "MedicinalProductContraindication", + "MedicinalProductIndication", + "MedicinalProductIngredient", + "MedicinalProductInteraction", + "MedicinalProductManufactured", + "MedicinalProductPackaged", + "MedicinalProductPharmaceutical", + "MedicinalProductUndesirableEffect", + "MessageDefinition", + "MessageHeader", + "MolecularSequence", + "NamingSystem", + "NutritionOrder", + "Observation", + "ObservationDefinition", + "OperationDefinition", + "OperationOutcome", + "Organization", + "OrganizationAffiliation", + "Patient", + "PaymentNotice", + "PaymentReconciliation", + "Person", + "PlanDefinition", + "Practitioner", + "PractitionerRole", + "Procedure", + "Provenance", + "Questionnaire", + "QuestionnaireResponse", + "RelatedPerson", + "RequestGroup", + "ResearchDefinition", + "ResearchElementDefinition", + "ResearchStudy", + "ResearchSubject", + "RiskAssessment", + "RiskEvidenceSynthesis", + "Schedule", + "SearchParameter", + "ServiceRequest", + "Slot", + "Specimen", + "SpecimenDefinition", + "StructureDefinition", + "StructureMap", + "Subscription", + "Substance", + "SubstanceNucleicAcid", + "SubstancePolymer", + "SubstanceProtein", + "SubstanceReferenceInformation", + "SubstanceSourceMaterial", + "SubstanceSpecification", + "SupplyDelivery", + "SupplyRequest", + "Task", + "TerminologyCapabilities", + "TestReport", + "TestScript", + "ValueSet", + "VerificationResult", + "VisionPrescription" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-evidence", + "code": "evidence", + "type": "token", + "expression": "Condition.evidence.code", + "base": [ + "Condition" + ], + "description": "Manifestation/symptom", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-onset-age", + "code": "onset-age", + "type": "quantity", + "expression": "Condition.onset.as(Age) | Condition.onset.as(Range)", + "base": [ + "Condition" + ], + "description": "Onsets as age or age range", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-onset-date", + "code": "onset-date", + "type": "date", + "expression": "Condition.onset.as(dateTime) | Condition.onset.as(Period)", + "base": [ + "Condition" + ], + "description": "Date related onsets (dateTime and Period)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-onset-info", + "code": "onset-info", + "type": "string", + "expression": "Condition.onset.as(string)", + "base": [ + "Condition" + ], + "description": "Onsets as a string", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-recorded-date", + "code": "recorded-date", + "type": "date", + "expression": "Condition.recordedDate", + "base": [ + "Condition" + ], + "description": "Date record was first recorded", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-severity", + "code": "severity", + "type": "token", + "expression": "Condition.severity", + "base": [ + "Condition" + ], + "description": "The severity of the condition", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-stage", + "code": "stage", + "type": "token", + "expression": "Condition.stage.summary", + "base": [ + "Condition" + ], + "description": "Simple summary (disease specific)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-subject", + "code": "subject", + "type": "reference", + "expression": "Condition.subject", + "base": [ + "Condition" + ], + "description": "Who has the condition?", + "target": [ + "Group", + "Patient" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Condition-verification-status", + "code": "verification-status", + "type": "token", + "expression": "Condition.verificationStatus", + "base": [ + "Condition" + ], + "description": "unconfirmed | provisional | differential | confirmed | refuted | entered-in-error", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-context-quantity", + "code": "context-quantity", + "type": "quantity", + "expression": "(CapabilityStatement.useContext.value as Quantity) | (CapabilityStatement.useContext.value as Range) | (CodeSystem.useContext.value as Quantity) | (CodeSystem.useContext.value as Range) | (CompartmentDefinition.useContext.value as Quantity) | (CompartmentDefinition.useContext.value as Range) | (ConceptMap.useContext.value as Quantity) | (ConceptMap.useContext.value as Range) | (GraphDefinition.useContext.value as Quantity) | (GraphDefinition.useContext.value as Range) | (ImplementationGuide.useContext.value as Quantity) | (ImplementationGuide.useContext.value as Range) | (MessageDefinition.useContext.value as Quantity) | (MessageDefinition.useContext.value as Range) | (NamingSystem.useContext.value as Quantity) | (NamingSystem.useContext.value as Range) | (OperationDefinition.useContext.value as Quantity) | (OperationDefinition.useContext.value as Range) | (SearchParameter.useContext.value as Quantity) | (SearchParameter.useContext.value as Range) | (StructureDefinition.useContext.value as Quantity) | (StructureDefinition.useContext.value as Range) | (StructureMap.useContext.value as Quantity) | (StructureMap.useContext.value as Range) | (TerminologyCapabilities.useContext.value as Quantity) | (TerminologyCapabilities.useContext.value as Range) | (ValueSet.useContext.value as Quantity) | (ValueSet.useContext.value as Range)", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): A quantity- or range-valued use context assigned to the capability statement\r\n* [CodeSystem](codesystem.html): A quantity- or range-valued use context assigned to the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): A quantity- or range-valued use context assigned to the compartment definition\r\n* [ConceptMap](conceptmap.html): A quantity- or range-valued use context assigned to the concept map\r\n* [GraphDefinition](graphdefinition.html): A quantity- or range-valued use context assigned to the graph definition\r\n* [ImplementationGuide](implementationguide.html): A quantity- or range-valued use context assigned to the implementation guide\r\n* [MessageDefinition](messagedefinition.html): A quantity- or range-valued use context assigned to the message definition\r\n* [NamingSystem](namingsystem.html): A quantity- or range-valued use context assigned to the naming system\r\n* [OperationDefinition](operationdefinition.html): A quantity- or range-valued use context assigned to the operation definition\r\n* [SearchParameter](searchparameter.html): A quantity- or range-valued use context assigned to the search parameter\r\n* [StructureDefinition](structuredefinition.html): A quantity- or range-valued use context assigned to the structure definition\r\n* [StructureMap](structuremap.html): A quantity- or range-valued use context assigned to the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): A quantity- or range-valued use context assigned to the terminology capabilities\r\n* [ValueSet](valueset.html): A quantity- or range-valued use context assigned to the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-context-type-quantity", + "code": "context-type-quantity", + "type": "composite", + "expression": "CapabilityStatement.useContext | CodeSystem.useContext | CompartmentDefinition.useContext | ConceptMap.useContext | GraphDefinition.useContext | ImplementationGuide.useContext | MessageDefinition.useContext | NamingSystem.useContext | OperationDefinition.useContext | SearchParameter.useContext | StructureDefinition.useContext | StructureMap.useContext | TerminologyCapabilities.useContext | ValueSet.useContext", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): A use context type and quantity- or range-based value assigned to the capability statement\r\n* [CodeSystem](codesystem.html): A use context type and quantity- or range-based value assigned to the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): A use context type and quantity- or range-based value assigned to the compartment definition\r\n* [ConceptMap](conceptmap.html): A use context type and quantity- or range-based value assigned to the concept map\r\n* [GraphDefinition](graphdefinition.html): A use context type and quantity- or range-based value assigned to the graph definition\r\n* [ImplementationGuide](implementationguide.html): A use context type and quantity- or range-based value assigned to the implementation guide\r\n* [MessageDefinition](messagedefinition.html): A use context type and quantity- or range-based value assigned to the message definition\r\n* [NamingSystem](namingsystem.html): A use context type and quantity- or range-based value assigned to the naming system\r\n* [OperationDefinition](operationdefinition.html): A use context type and quantity- or range-based value assigned to the operation definition\r\n* [SearchParameter](searchparameter.html): A use context type and quantity- or range-based value assigned to the search parameter\r\n* [StructureDefinition](structuredefinition.html): A use context type and quantity- or range-based value assigned to the structure definition\r\n* [StructureMap](structuremap.html): A use context type and quantity- or range-based value assigned to the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): A use context type and quantity- or range-based value assigned to the terminology capabilities\r\n* [ValueSet](valueset.html): A use context type and quantity- or range-based value assigned to the value set\r\n", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/conformance-context-type", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/conformance-context-quantity", + "expression": "value.as(Quantity) | value.as(Range)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-context-type-value", + "code": "context-type-value", + "type": "composite", + "expression": "CapabilityStatement.useContext | CodeSystem.useContext | CompartmentDefinition.useContext | ConceptMap.useContext | GraphDefinition.useContext | ImplementationGuide.useContext | MessageDefinition.useContext | NamingSystem.useContext | OperationDefinition.useContext | SearchParameter.useContext | StructureDefinition.useContext | StructureMap.useContext | TerminologyCapabilities.useContext | ValueSet.useContext", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): A use context type and value assigned to the capability statement\r\n* [CodeSystem](codesystem.html): A use context type and value assigned to the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): A use context type and value assigned to the compartment definition\r\n* [ConceptMap](conceptmap.html): A use context type and value assigned to the concept map\r\n* [GraphDefinition](graphdefinition.html): A use context type and value assigned to the graph definition\r\n* [ImplementationGuide](implementationguide.html): A use context type and value assigned to the implementation guide\r\n* [MessageDefinition](messagedefinition.html): A use context type and value assigned to the message definition\r\n* [NamingSystem](namingsystem.html): A use context type and value assigned to the naming system\r\n* [OperationDefinition](operationdefinition.html): A use context type and value assigned to the operation definition\r\n* [SearchParameter](searchparameter.html): A use context type and value assigned to the search parameter\r\n* [StructureDefinition](structuredefinition.html): A use context type and value assigned to the structure definition\r\n* [StructureMap](structuremap.html): A use context type and value assigned to the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): A use context type and value assigned to the terminology capabilities\r\n* [ValueSet](valueset.html): A use context type and value assigned to the value set\r\n", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/conformance-context-type", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/conformance-context", + "expression": "value.as(CodeableConcept)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-context-type", + "code": "context-type", + "type": "token", + "expression": "CapabilityStatement.useContext.code | CodeSystem.useContext.code | CompartmentDefinition.useContext.code | ConceptMap.useContext.code | GraphDefinition.useContext.code | ImplementationGuide.useContext.code | MessageDefinition.useContext.code | NamingSystem.useContext.code | OperationDefinition.useContext.code | SearchParameter.useContext.code | StructureDefinition.useContext.code | StructureMap.useContext.code | TerminologyCapabilities.useContext.code | ValueSet.useContext.code", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): A type of use context assigned to the capability statement\r\n* [CodeSystem](codesystem.html): A type of use context assigned to the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): A type of use context assigned to the compartment definition\r\n* [ConceptMap](conceptmap.html): A type of use context assigned to the concept map\r\n* [GraphDefinition](graphdefinition.html): A type of use context assigned to the graph definition\r\n* [ImplementationGuide](implementationguide.html): A type of use context assigned to the implementation guide\r\n* [MessageDefinition](messagedefinition.html): A type of use context assigned to the message definition\r\n* [NamingSystem](namingsystem.html): A type of use context assigned to the naming system\r\n* [OperationDefinition](operationdefinition.html): A type of use context assigned to the operation definition\r\n* [SearchParameter](searchparameter.html): A type of use context assigned to the search parameter\r\n* [StructureDefinition](structuredefinition.html): A type of use context assigned to the structure definition\r\n* [StructureMap](structuremap.html): A type of use context assigned to the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): A type of use context assigned to the terminology capabilities\r\n* [ValueSet](valueset.html): A type of use context assigned to the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-context", + "code": "context", + "type": "token", + "expression": "(CapabilityStatement.useContext.value as CodeableConcept) | (CodeSystem.useContext.value as CodeableConcept) | (CompartmentDefinition.useContext.value as CodeableConcept) | (ConceptMap.useContext.value as CodeableConcept) | (GraphDefinition.useContext.value as CodeableConcept) | (ImplementationGuide.useContext.value as CodeableConcept) | (MessageDefinition.useContext.value as CodeableConcept) | (NamingSystem.useContext.value as CodeableConcept) | (OperationDefinition.useContext.value as CodeableConcept) | (SearchParameter.useContext.value as CodeableConcept) | (StructureDefinition.useContext.value as CodeableConcept) | (StructureMap.useContext.value as CodeableConcept) | (TerminologyCapabilities.useContext.value as CodeableConcept) | (ValueSet.useContext.value as CodeableConcept)", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): A use context assigned to the capability statement\r\n* [CodeSystem](codesystem.html): A use context assigned to the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): A use context assigned to the compartment definition\r\n* [ConceptMap](conceptmap.html): A use context assigned to the concept map\r\n* [GraphDefinition](graphdefinition.html): A use context assigned to the graph definition\r\n* [ImplementationGuide](implementationguide.html): A use context assigned to the implementation guide\r\n* [MessageDefinition](messagedefinition.html): A use context assigned to the message definition\r\n* [NamingSystem](namingsystem.html): A use context assigned to the naming system\r\n* [OperationDefinition](operationdefinition.html): A use context assigned to the operation definition\r\n* [SearchParameter](searchparameter.html): A use context assigned to the search parameter\r\n* [StructureDefinition](structuredefinition.html): A use context assigned to the structure definition\r\n* [StructureMap](structuremap.html): A use context assigned to the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): A use context assigned to the terminology capabilities\r\n* [ValueSet](valueset.html): A use context assigned to the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-date", + "code": "date", + "type": "date", + "expression": "CapabilityStatement.date | CodeSystem.date | CompartmentDefinition.date | ConceptMap.date | GraphDefinition.date | ImplementationGuide.date | MessageDefinition.date | NamingSystem.date | OperationDefinition.date | SearchParameter.date | StructureDefinition.date | StructureMap.date | TerminologyCapabilities.date | ValueSet.date", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): The capability statement publication date\r\n* [CodeSystem](codesystem.html): The code system publication date\r\n* [CompartmentDefinition](compartmentdefinition.html): The compartment definition publication date\r\n* [ConceptMap](conceptmap.html): The concept map publication date\r\n* [GraphDefinition](graphdefinition.html): The graph definition publication date\r\n* [ImplementationGuide](implementationguide.html): The implementation guide publication date\r\n* [MessageDefinition](messagedefinition.html): The message definition publication date\r\n* [NamingSystem](namingsystem.html): The naming system publication date\r\n* [OperationDefinition](operationdefinition.html): The operation definition publication date\r\n* [SearchParameter](searchparameter.html): The search parameter publication date\r\n* [StructureDefinition](structuredefinition.html): The structure definition publication date\r\n* [StructureMap](structuremap.html): The structure map publication date\r\n* [TerminologyCapabilities](terminologycapabilities.html): The terminology capabilities publication date\r\n* [ValueSet](valueset.html): The value set publication date\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-description", + "code": "description", + "type": "string", + "expression": "CapabilityStatement.description | CodeSystem.description | CompartmentDefinition.description | ConceptMap.description | GraphDefinition.description | ImplementationGuide.description | MessageDefinition.description | NamingSystem.description | OperationDefinition.description | SearchParameter.description | StructureDefinition.description | StructureMap.description | TerminologyCapabilities.description | ValueSet.description", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): The description of the capability statement\r\n* [CodeSystem](codesystem.html): The description of the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): The description of the compartment definition\r\n* [ConceptMap](conceptmap.html): The description of the concept map\r\n* [GraphDefinition](graphdefinition.html): The description of the graph definition\r\n* [ImplementationGuide](implementationguide.html): The description of the implementation guide\r\n* [MessageDefinition](messagedefinition.html): The description of the message definition\r\n* [NamingSystem](namingsystem.html): The description of the naming system\r\n* [OperationDefinition](operationdefinition.html): The description of the operation definition\r\n* [SearchParameter](searchparameter.html): The description of the search parameter\r\n* [StructureDefinition](structuredefinition.html): The description of the structure definition\r\n* [StructureMap](structuremap.html): The description of the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): The description of the terminology capabilities\r\n* [ValueSet](valueset.html): The description of the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-identifier", + "code": "identifier", + "type": "token", + "expression": "CodeSystem.identifier | ConceptMap.identifier | MessageDefinition.identifier | StructureDefinition.identifier | StructureMap.identifier | ValueSet.identifier", + "base": [ + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CodeSystem](codesystem.html): External identifier for the code system\r\n* [ConceptMap](conceptmap.html): External identifier for the concept map\r\n* [MessageDefinition](messagedefinition.html): External identifier for the message definition\r\n* [StructureDefinition](structuredefinition.html): External identifier for the structure definition\r\n* [StructureMap](structuremap.html): External identifier for the structure map\r\n* [ValueSet](valueset.html): External identifier for the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-jurisdiction", + "code": "jurisdiction", + "type": "token", + "expression": "CapabilityStatement.jurisdiction | CodeSystem.jurisdiction | ConceptMap.jurisdiction | GraphDefinition.jurisdiction | ImplementationGuide.jurisdiction | MessageDefinition.jurisdiction | NamingSystem.jurisdiction | OperationDefinition.jurisdiction | SearchParameter.jurisdiction | StructureDefinition.jurisdiction | StructureMap.jurisdiction | TerminologyCapabilities.jurisdiction | ValueSet.jurisdiction", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): Intended jurisdiction for the capability statement\r\n* [CodeSystem](codesystem.html): Intended jurisdiction for the code system\r\n* [ConceptMap](conceptmap.html): Intended jurisdiction for the concept map\r\n* [GraphDefinition](graphdefinition.html): Intended jurisdiction for the graph definition\r\n* [ImplementationGuide](implementationguide.html): Intended jurisdiction for the implementation guide\r\n* [MessageDefinition](messagedefinition.html): Intended jurisdiction for the message definition\r\n* [NamingSystem](namingsystem.html): Intended jurisdiction for the naming system\r\n* [OperationDefinition](operationdefinition.html): Intended jurisdiction for the operation definition\r\n* [SearchParameter](searchparameter.html): Intended jurisdiction for the search parameter\r\n* [StructureDefinition](structuredefinition.html): Intended jurisdiction for the structure definition\r\n* [StructureMap](structuremap.html): Intended jurisdiction for the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): Intended jurisdiction for the terminology capabilities\r\n* [ValueSet](valueset.html): Intended jurisdiction for the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-name", + "code": "name", + "type": "string", + "expression": "CapabilityStatement.name | CodeSystem.name | CompartmentDefinition.name | ConceptMap.name | GraphDefinition.name | ImplementationGuide.name | MessageDefinition.name | NamingSystem.name | OperationDefinition.name | SearchParameter.name | StructureDefinition.name | StructureMap.name | TerminologyCapabilities.name | ValueSet.name", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): Computationally friendly name of the capability statement\r\n* [CodeSystem](codesystem.html): Computationally friendly name of the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): Computationally friendly name of the compartment definition\r\n* [ConceptMap](conceptmap.html): Computationally friendly name of the concept map\r\n* [GraphDefinition](graphdefinition.html): Computationally friendly name of the graph definition\r\n* [ImplementationGuide](implementationguide.html): Computationally friendly name of the implementation guide\r\n* [MessageDefinition](messagedefinition.html): Computationally friendly name of the message definition\r\n* [NamingSystem](namingsystem.html): Computationally friendly name of the naming system\r\n* [OperationDefinition](operationdefinition.html): Computationally friendly name of the operation definition\r\n* [SearchParameter](searchparameter.html): Computationally friendly name of the search parameter\r\n* [StructureDefinition](structuredefinition.html): Computationally friendly name of the structure definition\r\n* [StructureMap](structuremap.html): Computationally friendly name of the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): Computationally friendly name of the terminology capabilities\r\n* [ValueSet](valueset.html): Computationally friendly name of the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-publisher", + "code": "publisher", + "type": "string", + "expression": "CapabilityStatement.publisher | CodeSystem.publisher | CompartmentDefinition.publisher | ConceptMap.publisher | GraphDefinition.publisher | ImplementationGuide.publisher | MessageDefinition.publisher | NamingSystem.publisher | OperationDefinition.publisher | SearchParameter.publisher | StructureDefinition.publisher | StructureMap.publisher | TerminologyCapabilities.publisher | ValueSet.publisher", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): Name of the publisher of the capability statement\r\n* [CodeSystem](codesystem.html): Name of the publisher of the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): Name of the publisher of the compartment definition\r\n* [ConceptMap](conceptmap.html): Name of the publisher of the concept map\r\n* [GraphDefinition](graphdefinition.html): Name of the publisher of the graph definition\r\n* [ImplementationGuide](implementationguide.html): Name of the publisher of the implementation guide\r\n* [MessageDefinition](messagedefinition.html): Name of the publisher of the message definition\r\n* [NamingSystem](namingsystem.html): Name of the publisher of the naming system\r\n* [OperationDefinition](operationdefinition.html): Name of the publisher of the operation definition\r\n* [SearchParameter](searchparameter.html): Name of the publisher of the search parameter\r\n* [StructureDefinition](structuredefinition.html): Name of the publisher of the structure definition\r\n* [StructureMap](structuremap.html): Name of the publisher of the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): Name of the publisher of the terminology capabilities\r\n* [ValueSet](valueset.html): Name of the publisher of the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-status", + "code": "status", + "type": "token", + "expression": "CapabilityStatement.status | CodeSystem.status | CompartmentDefinition.status | ConceptMap.status | GraphDefinition.status | ImplementationGuide.status | MessageDefinition.status | NamingSystem.status | OperationDefinition.status | SearchParameter.status | StructureDefinition.status | StructureMap.status | TerminologyCapabilities.status | ValueSet.status", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): The current status of the capability statement\r\n* [CodeSystem](codesystem.html): The current status of the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): The current status of the compartment definition\r\n* [ConceptMap](conceptmap.html): The current status of the concept map\r\n* [GraphDefinition](graphdefinition.html): The current status of the graph definition\r\n* [ImplementationGuide](implementationguide.html): The current status of the implementation guide\r\n* [MessageDefinition](messagedefinition.html): The current status of the message definition\r\n* [NamingSystem](namingsystem.html): The current status of the naming system\r\n* [OperationDefinition](operationdefinition.html): The current status of the operation definition\r\n* [SearchParameter](searchparameter.html): The current status of the search parameter\r\n* [StructureDefinition](structuredefinition.html): The current status of the structure definition\r\n* [StructureMap](structuremap.html): The current status of the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): The current status of the terminology capabilities\r\n* [ValueSet](valueset.html): The current status of the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-title", + "code": "title", + "type": "string", + "expression": "CapabilityStatement.title | CodeSystem.title | ConceptMap.title | ImplementationGuide.title | MessageDefinition.title | OperationDefinition.title | StructureDefinition.title | StructureMap.title | TerminologyCapabilities.title | ValueSet.title", + "base": [ + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): The human-friendly name of the capability statement\r\n* [CodeSystem](codesystem.html): The human-friendly name of the code system\r\n* [ConceptMap](conceptmap.html): The human-friendly name of the concept map\r\n* [ImplementationGuide](implementationguide.html): The human-friendly name of the implementation guide\r\n* [MessageDefinition](messagedefinition.html): The human-friendly name of the message definition\r\n* [OperationDefinition](operationdefinition.html): The human-friendly name of the operation definition\r\n* [StructureDefinition](structuredefinition.html): The human-friendly name of the structure definition\r\n* [StructureMap](structuremap.html): The human-friendly name of the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): The human-friendly name of the terminology capabilities\r\n* [ValueSet](valueset.html): The human-friendly name of the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-url", + "code": "url", + "type": "uri", + "expression": "CapabilityStatement.url | CodeSystem.url | CompartmentDefinition.url | ConceptMap.url | GraphDefinition.url | ImplementationGuide.url | MessageDefinition.url | OperationDefinition.url | SearchParameter.url | StructureDefinition.url | StructureMap.url | TerminologyCapabilities.url | ValueSet.url", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): The uri that identifies the capability statement\r\n* [CodeSystem](codesystem.html): The uri that identifies the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): The uri that identifies the compartment definition\r\n* [ConceptMap](conceptmap.html): The uri that identifies the concept map\r\n* [GraphDefinition](graphdefinition.html): The uri that identifies the graph definition\r\n* [ImplementationGuide](implementationguide.html): The uri that identifies the implementation guide\r\n* [MessageDefinition](messagedefinition.html): The uri that identifies the message definition\r\n* [OperationDefinition](operationdefinition.html): The uri that identifies the operation definition\r\n* [SearchParameter](searchparameter.html): The uri that identifies the search parameter\r\n* [StructureDefinition](structuredefinition.html): The uri that identifies the structure definition\r\n* [StructureMap](structuremap.html): The uri that identifies the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): The uri that identifies the terminology capabilities\r\n* [ValueSet](valueset.html): The uri that identifies the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/conformance-version", + "code": "version", + "type": "token", + "expression": "CapabilityStatement.version | CodeSystem.version | CompartmentDefinition.version | ConceptMap.version | GraphDefinition.version | ImplementationGuide.version | MessageDefinition.version | OperationDefinition.version | SearchParameter.version | StructureDefinition.version | StructureMap.version | TerminologyCapabilities.version | ValueSet.version", + "base": [ + "SearchParameter", + "ValueSet" + ], + "description": "Multiple Resources: \r\n\r\n* [CapabilityStatement](capabilitystatement.html): The business version of the capability statement\r\n* [CodeSystem](codesystem.html): The business version of the code system\r\n* [CompartmentDefinition](compartmentdefinition.html): The business version of the compartment definition\r\n* [ConceptMap](conceptmap.html): The business version of the concept map\r\n* [GraphDefinition](graphdefinition.html): The business version of the graph definition\r\n* [ImplementationGuide](implementationguide.html): The business version of the implementation guide\r\n* [MessageDefinition](messagedefinition.html): The business version of the message definition\r\n* [OperationDefinition](operationdefinition.html): The business version of the operation definition\r\n* [SearchParameter](searchparameter.html): The business version of the search parameter\r\n* [StructureDefinition](structuredefinition.html): The business version of the structure definition\r\n* [StructureMap](structuremap.html): The business version of the structure map\r\n* [TerminologyCapabilities](terminologycapabilities.html): The business version of the terminology capabilities\r\n* [ValueSet](valueset.html): The business version of the value set\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-device-name", + "code": "device-name", + "type": "string", + "expression": "Device.deviceName.name | Device.type.coding.display | Device.type.text", + "base": [ + "Device" + ], + "description": "A server defined search that may match any of the string fields in Device.deviceName or Device.type.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/device-extensions-Device-din", + "code": "din", + "type": "token", + "expression": "Device.extension('http://hl7.org/fhir/SearchParameter/device-extensions-Device-din')", + "base": [ + "Device" + ], + "description": "The donation identification number (DIN)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-identifier", + "code": "identifier", + "type": "token", + "expression": "Device.identifier", + "base": [ + "Device" + ], + "description": "Instance id from manufacturer, owner, and others", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-location", + "code": "location", + "type": "reference", + "expression": "Device.location", + "base": [ + "Device" + ], + "description": "A location, where the resource is found", + "target": [ + "Location" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-manufacturer", + "code": "manufacturer", + "type": "string", + "expression": "Device.manufacturer", + "base": [ + "Device" + ], + "description": "The manufacturer of the device", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-model", + "code": "model", + "type": "string", + "expression": "Device.modelNumber", + "base": [ + "Device" + ], + "description": "The model of the device", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-organization", + "code": "organization", + "type": "reference", + "expression": "Device.owner", + "base": [ + "Device" + ], + "description": "The organization responsible for the device", + "target": [ + "Organization" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-patient", + "code": "patient", + "type": "reference", + "expression": "Device.patient", + "base": [ + "Device" + ], + "description": "Patient information, if the resource is affixed to a person", + "target": [ + "Patient" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-status", + "code": "status", + "type": "token", + "expression": "Device.status", + "base": [ + "Device" + ], + "description": "active | inactive | entered-in-error | unknown", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-type", + "code": "type", + "type": "token", + "expression": "Device.type", + "base": [ + "Device" + ], + "description": "The type of the device", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-udi-carrier", + "code": "udi-carrier", + "type": "string", + "expression": "Device.udiCarrier.carrierHRF", + "base": [ + "Device" + ], + "description": "UDI Barcode (RFID or other technology) string in *HRF* format.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-udi-di", + "code": "udi-di", + "type": "string", + "expression": "Device.udiCarrier.deviceIdentifier", + "base": [ + "Device" + ], + "description": "The udi Device Identifier (DI)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Device-url", + "code": "url", + "type": "uri", + "expression": "Device.url", + "base": [ + "Device" + ], + "description": "Network address to contact device", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/DomainResource-text", + "code": "_text", + "type": "string", + "expression": null, + "base": [ + "DomainResource" + ], + "description": "Search on the narrative of the resource", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-account", + "code": "account", + "type": "reference", + "expression": "Encounter.account", + "base": [ + "Encounter" + ], + "description": "The set of accounts that may be used for billing for this Encounter", + "target": [ + "Account" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-appointment", + "code": "appointment", + "type": "reference", + "expression": "Encounter.appointment", + "base": [ + "Encounter" + ], + "description": "The appointment that scheduled this encounter", + "target": [ + "Appointment" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-based-on", + "code": "based-on", + "type": "reference", + "expression": "Encounter.basedOn", + "base": [ + "Encounter" + ], + "description": "The ServiceRequest that initiated this encounter", + "target": [ + "ServiceRequest" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-class", + "code": "class", + "type": "token", + "expression": "Encounter.class", + "base": [ + "Encounter" + ], + "description": "Classification of patient encounter", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-diagnosis", + "code": "diagnosis", + "type": "reference", + "expression": "Encounter.diagnosis.condition", + "base": [ + "Encounter" + ], + "description": "The diagnosis or procedure relevant to the encounter", + "target": [ + "Condition", + "Procedure" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-episode-of-care", + "code": "episode-of-care", + "type": "reference", + "expression": "Encounter.episodeOfCare", + "base": [ + "Encounter" + ], + "description": "Episode(s) of care that this encounter should be recorded against", + "target": [ + "EpisodeOfCare" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-length", + "code": "length", + "type": "quantity", + "expression": "Encounter.length", + "base": [ + "Encounter" + ], + "description": "Length of encounter in days", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-location-period", + "code": "location-period", + "type": "date", + "expression": "Encounter.location.period", + "base": [ + "Encounter" + ], + "description": "Time period during which the patient was present at the location", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-location", + "code": "location", + "type": "reference", + "expression": "Encounter.location.location", + "base": [ + "Encounter" + ], + "description": "Location the encounter takes place", + "target": [ + "Location" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-part-of", + "code": "part-of", + "type": "reference", + "expression": "Encounter.partOf", + "base": [ + "Encounter" + ], + "description": "Another Encounter this encounter is part of", + "target": [ + "Encounter" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-participant-type", + "code": "participant-type", + "type": "token", + "expression": "Encounter.participant.type", + "base": [ + "Encounter" + ], + "description": "Role of participant in encounter", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-participant", + "code": "participant", + "type": "reference", + "expression": "Encounter.participant.individual", + "base": [ + "Encounter" + ], + "description": "Persons involved in the encounter other than the patient", + "target": [ + "Practitioner", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-practitioner", + "code": "practitioner", + "type": "reference", + "expression": "Encounter.participant.individual.where(resolve() is Practitioner)", + "base": [ + "Encounter" + ], + "description": "Persons involved in the encounter other than the patient", + "target": [ + "Practitioner" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-reason-code", + "code": "reason-code", + "type": "token", + "expression": "Encounter.reasonCode", + "base": [ + "Encounter" + ], + "description": "Coded reason the encounter takes place", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-reason-reference", + "code": "reason-reference", + "type": "reference", + "expression": "Encounter.reasonReference", + "base": [ + "Encounter" + ], + "description": "Reason the encounter takes place (reference)", + "target": [ + "Condition", + "Observation", + "Procedure", + "ImmunizationRecommendation" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-service-provider", + "code": "service-provider", + "type": "reference", + "expression": "Encounter.serviceProvider", + "base": [ + "Encounter" + ], + "description": "The organization (facility) responsible for this encounter", + "target": [ + "Organization" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-special-arrangement", + "code": "special-arrangement", + "type": "token", + "expression": "Encounter.hospitalization.specialArrangement", + "base": [ + "Encounter" + ], + "description": "Wheelchair, translator, stretcher, etc.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-status", + "code": "status", + "type": "token", + "expression": "Encounter.status", + "base": [ + "Encounter" + ], + "description": "planned | arrived | triaged | in-progress | onleave | finished | cancelled +", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Encounter-subject", + "code": "subject", + "type": "reference", + "expression": "Encounter.subject", + "base": [ + "Encounter" + ], + "description": "The patient or group present at the encounter", + "target": [ + "Group", + "Patient" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/example-extension", + "code": "part-agree", + "type": "reference", + "expression": "DocumentReference.extension('http://example.org/fhir/StructureDefinition/participation-agreement')", + "base": [ + "Patient" + ], + "description": "Search by url for a participation agreement, which is stored in a DocumentReference", + "target": [ + "DocumentReference" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/example-reference", + "code": "subject", + "type": "reference", + "expression": "Condition.subject", + "base": [ + "Condition" + ], + "description": "Search by condition subject", + "target": [ + "Organization" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/example", + "code": "_id", + "type": "token", + "expression": "id", + "base": [ + "Resource" + ], + "description": "Search by resource identifier - e.g. same as the read interaction, but can return included resources", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/filter", + "code": "_filter", + "type": "special", + "expression": null, + "base": [ + "Resource" + ], + "description": "This is the formal declaration for the _filter parameter, documented at [http://hl7.org/fhir/search_filter.html](http://hl7.org/fhir/search_filter.html)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-actual", + "code": "actual", + "type": "token", + "expression": "Group.actual", + "base": [ + "Group" + ], + "description": "Descriptive or actual", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-characteristic-value", + "code": "characteristic-value", + "type": "composite", + "expression": "Group.characteristic", + "base": [ + "Group" + ], + "description": "A composite of both characteristic and value", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/Group-characteristic", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Group-value", + "expression": "value" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-characteristic", + "code": "characteristic", + "type": "token", + "expression": "Group.characteristic.code", + "base": [ + "Group" + ], + "description": "Kind of characteristic", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-code", + "code": "code", + "type": "token", + "expression": "Group.code", + "base": [ + "Group" + ], + "description": "The kind of resources contained", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-exclude", + "code": "exclude", + "type": "token", + "expression": "Group.characteristic.exclude", + "base": [ + "Group" + ], + "description": "Group includes or excludes", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-identifier", + "code": "identifier", + "type": "token", + "expression": "Group.identifier", + "base": [ + "Group" + ], + "description": "Unique id", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-managing-entity", + "code": "managing-entity", + "type": "reference", + "expression": "Group.managingEntity", + "base": [ + "Group" + ], + "description": "Entity that is the custodian of the Group's definition", + "target": [ + "Practitioner", + "Organization", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-member", + "code": "member", + "type": "reference", + "expression": "Group.member.entity", + "base": [ + "Group" + ], + "description": "Reference to the group member", + "target": [ + "Practitioner", + "Group", + "Device", + "Medication", + "Patient", + "Substance", + "PractitionerRole" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-type", + "code": "type", + "type": "token", + "expression": "Group.type", + "base": [ + "Group" + ], + "description": "The type of resources the group contains", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Group-value", + "code": "value", + "type": "token", + "expression": "(Group.characteristic.value as CodeableConcept) | (Group.characteristic.value as boolean)", + "base": [ + "Group" + ], + "description": "Value held by characteristic", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-address-city", + "code": "address-city", + "type": "string", + "expression": "Patient.address.city | Person.address.city | Practitioner.address.city | RelatedPerson.address.city", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A city specified in an address\r\n* [Person](person.html): A city specified in an address\r\n* [Practitioner](practitioner.html): A city specified in an address\r\n* [RelatedPerson](relatedperson.html): A city specified in an address\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-address-country", + "code": "address-country", + "type": "string", + "expression": "Patient.address.country | Person.address.country | Practitioner.address.country | RelatedPerson.address.country", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A country specified in an address\r\n* [Person](person.html): A country specified in an address\r\n* [Practitioner](practitioner.html): A country specified in an address\r\n* [RelatedPerson](relatedperson.html): A country specified in an address\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-address-postalcode", + "code": "address-postalcode", + "type": "string", + "expression": "Patient.address.postalCode | Person.address.postalCode | Practitioner.address.postalCode | RelatedPerson.address.postalCode", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A postalCode specified in an address\r\n* [Person](person.html): A postal code specified in an address\r\n* [Practitioner](practitioner.html): A postalCode specified in an address\r\n* [RelatedPerson](relatedperson.html): A postal code specified in an address\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-address-state", + "code": "address-state", + "type": "string", + "expression": "Patient.address.state | Person.address.state | Practitioner.address.state | RelatedPerson.address.state", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A state specified in an address\r\n* [Person](person.html): A state specified in an address\r\n* [Practitioner](practitioner.html): A state specified in an address\r\n* [RelatedPerson](relatedperson.html): A state specified in an address\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-address-use", + "code": "address-use", + "type": "token", + "expression": "Patient.address.use | Person.address.use | Practitioner.address.use | RelatedPerson.address.use", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A use code specified in an address\r\n* [Person](person.html): A use code specified in an address\r\n* [Practitioner](practitioner.html): A use code specified in an address\r\n* [RelatedPerson](relatedperson.html): A use code specified in an address\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-address", + "code": "address", + "type": "string", + "expression": "Patient.address | Person.address | Practitioner.address | RelatedPerson.address", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A server defined search that may match any of the string fields in the Address, including line, city, district, state, country, postalCode, and/or text\r\n* [Person](person.html): A server defined search that may match any of the string fields in the Address, including line, city, district, state, country, postalCode, and/or text\r\n* [Practitioner](practitioner.html): A server defined search that may match any of the string fields in the Address, including line, city, district, state, country, postalCode, and/or text\r\n* [RelatedPerson](relatedperson.html): A server defined search that may match any of the string fields in the Address, including line, city, district, state, country, postalCode, and/or text\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-birthdate", + "code": "birthdate", + "type": "date", + "expression": "Patient.birthDate | Person.birthDate | RelatedPerson.birthDate", + "base": [ + "Patient", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): The patient's date of birth\r\n* [Person](person.html): The person's date of birth\r\n* [RelatedPerson](relatedperson.html): The Related Person's date of birth\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-email", + "code": "email", + "type": "token", + "expression": "Patient.telecom.where(system='email') | Person.telecom.where(system='email') | Practitioner.telecom.where(system='email') | PractitionerRole.telecom.where(system='email') | RelatedPerson.telecom.where(system='email')", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A value in an email contact\r\n* [Person](person.html): A value in an email contact\r\n* [Practitioner](practitioner.html): A value in an email contact\r\n* [PractitionerRole](practitionerrole.html): A value in an email contact\r\n* [RelatedPerson](relatedperson.html): A value in an email contact\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-family", + "code": "family", + "type": "string", + "expression": "Patient.name.family | Practitioner.name.family", + "base": [ + "Patient", + "Practitioner" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A portion of the family name of the patient\r\n* [Practitioner](practitioner.html): A portion of the family name\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-gender", + "code": "gender", + "type": "token", + "expression": "Patient.gender | Person.gender | Practitioner.gender | RelatedPerson.gender", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): Gender of the patient\r\n* [Person](person.html): The gender of the person\r\n* [Practitioner](practitioner.html): Gender of the practitioner\r\n* [RelatedPerson](relatedperson.html): Gender of the related person\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-given", + "code": "given", + "type": "string", + "expression": "Patient.name.given | Practitioner.name.given", + "base": [ + "Patient", + "Practitioner" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A portion of the given name of the patient\r\n* [Practitioner](practitioner.html): A portion of the given name\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-phone", + "code": "phone", + "type": "token", + "expression": "Patient.telecom.where(system='phone') | Person.telecom.where(system='phone') | Practitioner.telecom.where(system='phone') | PractitionerRole.telecom.where(system='phone') | RelatedPerson.telecom.where(system='phone')", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A value in a phone contact\r\n* [Person](person.html): A value in a phone contact\r\n* [Practitioner](practitioner.html): A value in a phone contact\r\n* [PractitionerRole](practitionerrole.html): A value in a phone contact\r\n* [RelatedPerson](relatedperson.html): A value in a phone contact\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-phonetic", + "code": "phonetic", + "type": "string", + "expression": "Patient.name | Person.name | Practitioner.name | RelatedPerson.name", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): A portion of either family or given name using some kind of phonetic matching algorithm\r\n* [Person](person.html): A portion of name using some kind of phonetic matching algorithm\r\n* [Practitioner](practitioner.html): A portion of either family or given name using some kind of phonetic matching algorithm\r\n* [RelatedPerson](relatedperson.html): A portion of name using some kind of phonetic matching algorithm\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/individual-telecom", + "code": "telecom", + "type": "token", + "expression": "Patient.telecom | Person.telecom | Practitioner.telecom | PractitionerRole.telecom | RelatedPerson.telecom", + "base": [ + "Patient", + "Practitioner", + "RelatedPerson" + ], + "description": "Multiple Resources: \r\n\r\n* [Patient](patient.html): The value in any kind of telecom details of the patient\r\n* [Person](person.html): The value in any kind of contact\r\n* [Practitioner](practitioner.html): The value in any kind of contact\r\n* [PractitionerRole](practitionerrole.html): The value in any kind of contact\r\n* [RelatedPerson](relatedperson.html): The value in any kind of contact\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/List-empty-reason", + "code": "empty-reason", + "type": "token", + "expression": "List.emptyReason", + "base": [ + "List" + ], + "description": "Why list is empty", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/List-item", + "code": "item", + "type": "reference", + "expression": "List.entry.item", + "base": [ + "List" + ], + "description": "Actual entry", + "target": [ + "Account", + "ActivityDefinition", + "AdverseEvent", + "AllergyIntolerance", + "Appointment", + "AppointmentResponse", + "AuditEvent", + "Basic", + "Binary", + "BiologicallyDerivedProduct", + "BodyStructure", + "Bundle", + "CapabilityStatement", + "CarePlan", + "CareTeam", + "CatalogEntry", + "ChargeItem", + "ChargeItemDefinition", + "Claim", + "ClaimResponse", + "ClinicalImpression", + "CodeSystem", + "Communication", + "CommunicationRequest", + "CompartmentDefinition", + "Composition", + "ConceptMap", + "Condition", + "Consent", + "Contract", + "Coverage", + "CoverageEligibilityRequest", + "CoverageEligibilityResponse", + "DetectedIssue", + "Device", + "DeviceDefinition", + "DeviceMetric", + "DeviceRequest", + "DeviceUseStatement", + "DiagnosticReport", + "DocumentManifest", + "DocumentReference", + "EffectEvidenceSynthesis", + "Encounter", + "Endpoint", + "EnrollmentRequest", + "EnrollmentResponse", + "EpisodeOfCare", + "EventDefinition", + "Evidence", + "EvidenceVariable", + "ExampleScenario", + "ExplanationOfBenefit", + "FamilyMemberHistory", + "Flag", + "Goal", + "GraphDefinition", + "Group", + "GuidanceResponse", + "HealthcareService", + "ImagingStudy", + "Immunization", + "ImmunizationEvaluation", + "ImmunizationRecommendation", + "ImplementationGuide", + "InsurancePlan", + "Invoice", + "Library", + "Linkage", + "List", + "Location", + "Measure", + "MeasureReport", + "Media", + "Medication", + "MedicationAdministration", + "MedicationDispense", + "MedicationKnowledge", + "MedicationRequest", + "MedicationStatement", + "MedicinalProduct", + "MedicinalProductAuthorization", + "MedicinalProductContraindication", + "MedicinalProductIndication", + "MedicinalProductIngredient", + "MedicinalProductInteraction", + "MedicinalProductManufactured", + "MedicinalProductPackaged", + "MedicinalProductPharmaceutical", + "MedicinalProductUndesirableEffect", + "MessageDefinition", + "MessageHeader", + "MolecularSequence", + "NamingSystem", + "NutritionOrder", + "Observation", + "ObservationDefinition", + "OperationDefinition", + "OperationOutcome", + "Organization", + "OrganizationAffiliation", + "Patient", + "PaymentNotice", + "PaymentReconciliation", + "Person", + "PlanDefinition", + "Practitioner", + "PractitionerRole", + "Procedure", + "Provenance", + "Questionnaire", + "QuestionnaireResponse", + "RelatedPerson", + "RequestGroup", + "ResearchDefinition", + "ResearchElementDefinition", + "ResearchStudy", + "ResearchSubject", + "RiskAssessment", + "RiskEvidenceSynthesis", + "Schedule", + "SearchParameter", + "ServiceRequest", + "Slot", + "Specimen", + "SpecimenDefinition", + "StructureDefinition", + "StructureMap", + "Subscription", + "Substance", + "SubstanceNucleicAcid", + "SubstancePolymer", + "SubstanceProtein", + "SubstanceReferenceInformation", + "SubstanceSourceMaterial", + "SubstanceSpecification", + "SupplyDelivery", + "SupplyRequest", + "Task", + "TerminologyCapabilities", + "TestReport", + "TestScript", + "ValueSet", + "VerificationResult", + "VisionPrescription" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/List-notes", + "code": "notes", + "type": "string", + "expression": "List.note.text", + "base": [ + "List" + ], + "description": "The annotation - text content (as markdown)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/List-source", + "code": "source", + "type": "reference", + "expression": "List.source", + "base": [ + "List" + ], + "description": "Who and/or what defined the list contents (aka Author)", + "target": [ + "Practitioner", + "Device", + "Patient", + "PractitionerRole" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/List-status", + "code": "status", + "type": "token", + "expression": "List.status", + "base": [ + "List" + ], + "description": "current | retired | entered-in-error", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/List-subject", + "code": "subject", + "type": "reference", + "expression": "List.subject", + "base": [ + "List" + ], + "description": "If all resources have the same subject", + "target": [ + "Group", + "Device", + "Patient", + "Location" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/List-title", + "code": "title", + "type": "string", + "expression": "List.title", + "base": [ + "List" + ], + "description": "Descriptive name for the list", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-authoredon", + "code": "authoredon", + "type": "date", + "expression": "MedicationRequest.authoredOn", + "base": [ + "MedicationRequest" + ], + "description": "Return prescriptions written on this date", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-category", + "code": "category", + "type": "token", + "expression": "MedicationRequest.category", + "base": [ + "MedicationRequest" + ], + "description": "Returns prescriptions with different categories", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-intended-dispenser", + "code": "intended-dispenser", + "type": "reference", + "expression": "MedicationRequest.dispenseRequest.performer", + "base": [ + "MedicationRequest" + ], + "description": "Returns prescriptions intended to be dispensed by this Organization", + "target": [ + "Organization" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-intended-performer", + "code": "intended-performer", + "type": "reference", + "expression": "MedicationRequest.performer", + "base": [ + "MedicationRequest" + ], + "description": "Returns the intended performer of the administration of the medication request", + "target": [ + "Practitioner", + "Organization", + "CareTeam", + "Device", + "Patient", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-intended-performertype", + "code": "intended-performertype", + "type": "token", + "expression": "MedicationRequest.performerType", + "base": [ + "MedicationRequest" + ], + "description": "Returns requests for a specific type of performer", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-intent", + "code": "intent", + "type": "token", + "expression": "MedicationRequest.intent", + "base": [ + "MedicationRequest" + ], + "description": "Returns prescriptions with different intents", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-priority", + "code": "priority", + "type": "token", + "expression": "MedicationRequest.priority", + "base": [ + "MedicationRequest" + ], + "description": "Returns prescriptions with different priorities", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-requester", + "code": "requester", + "type": "reference", + "expression": "MedicationRequest.requester", + "base": [ + "MedicationRequest" + ], + "description": "Returns prescriptions prescribed by this prescriber", + "target": [ + "Practitioner", + "Organization", + "Device", + "Patient", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/MedicationRequest-subject", + "code": "subject", + "type": "reference", + "expression": "MedicationRequest.subject", + "base": [ + "MedicationRequest" + ], + "description": "The identity of a patient to list orders for", + "target": [ + "Group", + "Patient" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/medications-date", + "code": "date", + "type": "date", + "expression": "MedicationRequest.dosageInstruction.timing.event", + "base": [ + "MedicationRequest" + ], + "description": "Multiple Resources: \r\n\r\n* [MedicationRequest](medicationrequest.html): Returns medication request to be administered on a specific date\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/medications-encounter", + "code": "encounter", + "type": "reference", + "expression": "MedicationRequest.encounter", + "base": [ + "MedicationRequest" + ], + "description": "Multiple Resources: \r\n\r\n* [MedicationRequest](medicationrequest.html): Return prescriptions with this encounter identifier\r\n", + "target": [ + "Encounter" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/medications-medication", + "code": "medication", + "type": "reference", + "expression": "(MedicationAdministration.medication as Reference) | (MedicationDispense.medication as Reference) | (MedicationRequest.medication as Reference) | (MedicationStatement.medication as Reference)", + "base": [ + "MedicationRequest" + ], + "description": "Multiple Resources: \r\n\r\n* [MedicationAdministration](medicationadministration.html): Return administrations of this medication resource\r\n* [MedicationDispense](medicationdispense.html): Returns dispenses of this medicine resource\r\n* [MedicationRequest](medicationrequest.html): Return prescriptions for this medication reference\r\n* [MedicationStatement](medicationstatement.html): Return statements of this medication reference\r\n", + "target": [ + "Medication" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/medications-status", + "code": "status", + "type": "token", + "expression": "MedicationAdministration.status | MedicationDispense.status | MedicationRequest.status | MedicationStatement.status", + "base": [ + "MedicationRequest" + ], + "description": "Multiple Resources: \r\n\r\n* [MedicationAdministration](medicationadministration.html): MedicationAdministration event status (for example one of active/paused/completed/nullified)\r\n* [MedicationDispense](medicationdispense.html): Returns dispenses with a specified dispense status\r\n* [MedicationRequest](medicationrequest.html): Status of the prescription\r\n* [MedicationStatement](medicationstatement.html): Return statements that match the given status\r\n", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-based-on", + "code": "based-on", + "type": "reference", + "expression": "Observation.basedOn", + "base": [ + "Observation" + ], + "description": "Reference to the service request.", + "target": [ + "CarePlan", + "MedicationRequest", + "NutritionOrder", + "DeviceRequest", + "ServiceRequest", + "ImmunizationRecommendation" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-category", + "code": "category", + "type": "token", + "expression": "Observation.category", + "base": [ + "Observation" + ], + "description": "The classification of the type of observation", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-code-value-concept", + "code": "code-value-concept", + "type": "composite", + "expression": "Observation", + "base": [ + "Observation" + ], + "description": "Code and coded value parameter pair", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/clinical-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-value-concept", + "expression": "value.as(CodeableConcept)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-code-value-date", + "code": "code-value-date", + "type": "composite", + "expression": "Observation", + "base": [ + "Observation" + ], + "description": "Code and date/time value parameter pair", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/clinical-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-value-date", + "expression": "value.as(DateTime) | value.as(Period)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-code-value-quantity", + "code": "code-value-quantity", + "type": "composite", + "expression": "Observation", + "base": [ + "Observation" + ], + "description": "Code and quantity value parameter pair", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/clinical-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-value-quantity", + "expression": "value.as(Quantity)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-code-value-string", + "code": "code-value-string", + "type": "composite", + "expression": "Observation", + "base": [ + "Observation" + ], + "description": "Code and string value parameter pair", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/clinical-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-value-string", + "expression": "value.as(string)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-combo-code-value-concept", + "code": "combo-code-value-concept", + "type": "composite", + "expression": "Observation | Observation.component", + "base": [ + "Observation" + ], + "description": "Code and coded value parameter pair, including in components", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-combo-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-combo-value-concept", + "expression": "value.as(CodeableConcept)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-combo-code-value-quantity", + "code": "combo-code-value-quantity", + "type": "composite", + "expression": "Observation | Observation.component", + "base": [ + "Observation" + ], + "description": "Code and quantity value parameter pair, including in components", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-combo-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-combo-value-quantity", + "expression": "value.as(Quantity)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-combo-code", + "code": "combo-code", + "type": "token", + "expression": "Observation.code | Observation.component.code", + "base": [ + "Observation" + ], + "description": "The code of the observation type or component type", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-combo-data-absent-reason", + "code": "combo-data-absent-reason", + "type": "token", + "expression": "Observation.dataAbsentReason | Observation.component.dataAbsentReason", + "base": [ + "Observation" + ], + "description": "The reason why the expected value in the element Observation.value[x] or Observation.component.value[x] is missing.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-combo-value-concept", + "code": "combo-value-concept", + "type": "token", + "expression": "(Observation.value as CodeableConcept) | (Observation.component.value as CodeableConcept)", + "base": [ + "Observation" + ], + "description": "The value or component value of the observation, if the value is a CodeableConcept", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-combo-value-quantity", + "code": "combo-value-quantity", + "type": "quantity", + "expression": "(Observation.value as Quantity) | (Observation.value as SampledData) | (Observation.component.value as Quantity) | (Observation.component.value as SampledData)", + "base": [ + "Observation" + ], + "description": "The value or component value of the observation, if the value is a Quantity, or a SampledData (just search on the bounds of the values in sampled data)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-component-code-value-concept", + "code": "component-code-value-concept", + "type": "composite", + "expression": "Observation.component", + "base": [ + "Observation" + ], + "description": "Component code and component coded value parameter pair", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-component-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-component-value-concept", + "expression": "value.as(CodeableConcept)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-component-code-value-quantity", + "code": "component-code-value-quantity", + "type": "composite", + "expression": "Observation.component", + "base": [ + "Observation" + ], + "description": "Component code and component quantity value parameter pair", + "target": [], + "component": [ + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-component-code", + "expression": "code" + }, + { + "definition": "http://hl7.org/fhir/SearchParameter/Observation-component-value-quantity", + "expression": "value.as(Quantity)" + } + ] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-component-code", + "code": "component-code", + "type": "token", + "expression": "Observation.component.code", + "base": [ + "Observation" + ], + "description": "The component code of the observation type", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-component-data-absent-reason", + "code": "component-data-absent-reason", + "type": "token", + "expression": "Observation.component.dataAbsentReason", + "base": [ + "Observation" + ], + "description": "The reason why the expected value in the element Observation.component.value[x] is missing.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-component-value-concept", + "code": "component-value-concept", + "type": "token", + "expression": "(Observation.component.value as CodeableConcept)", + "base": [ + "Observation" + ], + "description": "The value of the component observation, if the value is a CodeableConcept", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-component-value-quantity", + "code": "component-value-quantity", + "type": "quantity", + "expression": "(Observation.component.value as Quantity) | (Observation.component.value as SampledData)", + "base": [ + "Observation" + ], + "description": "The value of the component observation, if the value is a Quantity, or a SampledData (just search on the bounds of the values in sampled data)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-data-absent-reason", + "code": "data-absent-reason", + "type": "token", + "expression": "Observation.dataAbsentReason", + "base": [ + "Observation" + ], + "description": "The reason why the expected value in the element Observation.value[x] is missing.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-derived-from", + "code": "derived-from", + "type": "reference", + "expression": "Observation.derivedFrom", + "base": [ + "Observation" + ], + "description": "Related measurements the observation is made from", + "target": [ + "Media", + "Observation", + "ImagingStudy", + "MolecularSequence", + "QuestionnaireResponse", + "DocumentReference" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-device", + "code": "device", + "type": "reference", + "expression": "Observation.device", + "base": [ + "Observation" + ], + "description": "The Device that generated the observation data.", + "target": [ + "Device", + "DeviceMetric" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-focus", + "code": "focus", + "type": "reference", + "expression": "Observation.focus", + "base": [ + "Observation" + ], + "description": "The focus of an observation when the focus is not the patient of record.", + "target": [ + "Account", + "ActivityDefinition", + "AdverseEvent", + "AllergyIntolerance", + "Appointment", + "AppointmentResponse", + "AuditEvent", + "Basic", + "Binary", + "BiologicallyDerivedProduct", + "BodyStructure", + "Bundle", + "CapabilityStatement", + "CarePlan", + "CareTeam", + "CatalogEntry", + "ChargeItem", + "ChargeItemDefinition", + "Claim", + "ClaimResponse", + "ClinicalImpression", + "CodeSystem", + "Communication", + "CommunicationRequest", + "CompartmentDefinition", + "Composition", + "ConceptMap", + "Condition", + "Consent", + "Contract", + "Coverage", + "CoverageEligibilityRequest", + "CoverageEligibilityResponse", + "DetectedIssue", + "Device", + "DeviceDefinition", + "DeviceMetric", + "DeviceRequest", + "DeviceUseStatement", + "DiagnosticReport", + "DocumentManifest", + "DocumentReference", + "EffectEvidenceSynthesis", + "Encounter", + "Endpoint", + "EnrollmentRequest", + "EnrollmentResponse", + "EpisodeOfCare", + "EventDefinition", + "Evidence", + "EvidenceVariable", + "ExampleScenario", + "ExplanationOfBenefit", + "FamilyMemberHistory", + "Flag", + "Goal", + "GraphDefinition", + "Group", + "GuidanceResponse", + "HealthcareService", + "ImagingStudy", + "Immunization", + "ImmunizationEvaluation", + "ImmunizationRecommendation", + "ImplementationGuide", + "InsurancePlan", + "Invoice", + "Library", + "Linkage", + "List", + "Location", + "Measure", + "MeasureReport", + "Media", + "Medication", + "MedicationAdministration", + "MedicationDispense", + "MedicationKnowledge", + "MedicationRequest", + "MedicationStatement", + "MedicinalProduct", + "MedicinalProductAuthorization", + "MedicinalProductContraindication", + "MedicinalProductIndication", + "MedicinalProductIngredient", + "MedicinalProductInteraction", + "MedicinalProductManufactured", + "MedicinalProductPackaged", + "MedicinalProductPharmaceutical", + "MedicinalProductUndesirableEffect", + "MessageDefinition", + "MessageHeader", + "MolecularSequence", + "NamingSystem", + "NutritionOrder", + "Observation", + "ObservationDefinition", + "OperationDefinition", + "OperationOutcome", + "Organization", + "OrganizationAffiliation", + "Patient", + "PaymentNotice", + "PaymentReconciliation", + "Person", + "PlanDefinition", + "Practitioner", + "PractitionerRole", + "Procedure", + "Provenance", + "Questionnaire", + "QuestionnaireResponse", + "RelatedPerson", + "RequestGroup", + "ResearchDefinition", + "ResearchElementDefinition", + "ResearchStudy", + "ResearchSubject", + "RiskAssessment", + "RiskEvidenceSynthesis", + "Schedule", + "SearchParameter", + "ServiceRequest", + "Slot", + "Specimen", + "SpecimenDefinition", + "StructureDefinition", + "StructureMap", + "Subscription", + "Substance", + "SubstanceNucleicAcid", + "SubstancePolymer", + "SubstanceProtein", + "SubstanceReferenceInformation", + "SubstanceSourceMaterial", + "SubstanceSpecification", + "SupplyDelivery", + "SupplyRequest", + "Task", + "TerminologyCapabilities", + "TestReport", + "TestScript", + "ValueSet", + "VerificationResult", + "VisionPrescription" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/observation-genetic-Observation-amino-acid-change", + "code": "amino-acid-change", + "type": "string", + "expression": "Observation.extension('http://hl7.org/fhir/StructureDefinition/observation-geneticsAminoAcidChangeName')", + "base": [ + "Observation" + ], + "description": "HGVS Protein Change", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/observation-genetic-Observation-dna-variant", + "code": "dna-variant", + "type": "string", + "expression": "Observation.extension('http://hl7.org/fhir/StructureDefinition/observation-geneticsDnaVariant')", + "base": [ + "Observation" + ], + "description": "HGVS DNA variant", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/observation-genetic-Observation-gene-amino-acid-change", + "code": "gene-amino-acid-change", + "type": "string", + "expression": "Observation.extension('http://hl7.org/fhir/StructureDefinition/observation-geneticsAminoAcidChangeName')", + "base": [ + "Observation" + ], + "description": "HGNC gene symbol and HGVS Protein change", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/observation-genetic-Observation-gene-dnavariant", + "code": "gene-dnavariant", + "type": "string", + "expression": "Observation.extension('http://hl7.org/fhir/StructureDefinition/observation-geneticsDnaVariant')", + "base": [ + "Observation" + ], + "description": "HGNC gene symbol and HGVS DNA Variant", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/observation-genetic-Observation-gene-identifier", + "code": "gene-identifier", + "type": "token", + "expression": "Observation.extension('http://hl7.org/fhir/StructureDefinition/observation-geneticsGene')", + "base": [ + "Observation" + ], + "description": "HGNC gene symbol and identifier", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-has-member", + "code": "has-member", + "type": "reference", + "expression": "Observation.hasMember", + "base": [ + "Observation" + ], + "description": "Related resource that belongs to the Observation group", + "target": [ + "Observation", + "MolecularSequence", + "QuestionnaireResponse" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-method", + "code": "method", + "type": "token", + "expression": "Observation.method", + "base": [ + "Observation" + ], + "description": "The method used for the observation", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-part-of", + "code": "part-of", + "type": "reference", + "expression": "Observation.partOf", + "base": [ + "Observation" + ], + "description": "Part of referenced event", + "target": [ + "Immunization", + "MedicationDispense", + "MedicationAdministration", + "Procedure", + "ImagingStudy", + "MedicationStatement" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-performer", + "code": "performer", + "type": "reference", + "expression": "Observation.performer", + "base": [ + "Observation" + ], + "description": "Who performed the observation", + "target": [ + "Practitioner", + "Organization", + "CareTeam", + "Patient", + "PractitionerRole", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-specimen", + "code": "specimen", + "type": "reference", + "expression": "Observation.specimen", + "base": [ + "Observation" + ], + "description": "Specimen used for this observation", + "target": [ + "Specimen" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-status", + "code": "status", + "type": "token", + "expression": "Observation.status", + "base": [ + "Observation" + ], + "description": "The status of the observation", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-subject", + "code": "subject", + "type": "reference", + "expression": "Observation.subject", + "base": [ + "Observation" + ], + "description": "The subject that the observation is about", + "target": [ + "Group", + "Device", + "Patient", + "Location" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-value-concept", + "code": "value-concept", + "type": "token", + "expression": "(Observation.value as CodeableConcept)", + "base": [ + "Observation" + ], + "description": "The value of the observation, if the value is a CodeableConcept", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-value-date", + "code": "value-date", + "type": "date", + "expression": "(Observation.value as dateTime) | (Observation.value as Period)", + "base": [ + "Observation" + ], + "description": "The value of the observation, if the value is a date or period of time", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-value-quantity", + "code": "value-quantity", + "type": "quantity", + "expression": "(Observation.value as Quantity) | (Observation.value as SampledData)", + "base": [ + "Observation" + ], + "description": "The value of the observation, if the value is a Quantity, or a SampledData (just search on the bounds of the values in sampled data)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Observation-value-string", + "code": "value-string", + "type": "string", + "expression": "(Observation.value as string) | (Observation.value as CodeableConcept).text", + "base": [ + "Observation" + ], + "description": "The value of the observation, if the value is a string, and also searches in CodeableConcept.text", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-active", + "code": "active", + "type": "token", + "expression": "Organization.active", + "base": [ + "Organization" + ], + "description": "Is the Organization record active", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-address-city", + "code": "address-city", + "type": "string", + "expression": "Organization.address.city", + "base": [ + "Organization" + ], + "description": "A city specified in an address", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-address-country", + "code": "address-country", + "type": "string", + "expression": "Organization.address.country", + "base": [ + "Organization" + ], + "description": "A country specified in an address", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-address-postalcode", + "code": "address-postalcode", + "type": "string", + "expression": "Organization.address.postalCode", + "base": [ + "Organization" + ], + "description": "A postal code specified in an address", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-address-state", + "code": "address-state", + "type": "string", + "expression": "Organization.address.state", + "base": [ + "Organization" + ], + "description": "A state specified in an address", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-address-use", + "code": "address-use", + "type": "token", + "expression": "Organization.address.use", + "base": [ + "Organization" + ], + "description": "A use code specified in an address", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-address", + "code": "address", + "type": "string", + "expression": "Organization.address", + "base": [ + "Organization" + ], + "description": "A server defined search that may match any of the string fields in the Address, including line, city, district, state, country, postalCode, and/or text", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-endpoint", + "code": "endpoint", + "type": "reference", + "expression": "Organization.endpoint", + "base": [ + "Organization" + ], + "description": "Technical endpoints providing access to services operated for the organization", + "target": [ + "Endpoint" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-identifier", + "code": "identifier", + "type": "token", + "expression": "Organization.identifier", + "base": [ + "Organization" + ], + "description": "Any identifier for the organization (not the accreditation issuer's identifier)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-name", + "code": "name", + "type": "string", + "expression": "Organization.name | Organization.alias", + "base": [ + "Organization" + ], + "description": "A portion of the organization's name or alias", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-partof", + "code": "partof", + "type": "reference", + "expression": "Organization.partOf", + "base": [ + "Organization" + ], + "description": "An organization of which this organization forms a part", + "target": [ + "Organization" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-phonetic", + "code": "phonetic", + "type": "string", + "expression": "Organization.name", + "base": [ + "Organization" + ], + "description": "A portion of the organization's name using some kind of phonetic matching algorithm", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Organization-type", + "code": "type", + "type": "token", + "expression": "Organization.type", + "base": [ + "Organization" + ], + "description": "A code for the type of organization", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-active", + "code": "active", + "type": "token", + "expression": "Patient.active", + "base": [ + "Patient" + ], + "description": "Whether the patient record is active", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-death-date", + "code": "death-date", + "type": "date", + "expression": "(Patient.deceased as dateTime)", + "base": [ + "Patient" + ], + "description": "The date of death has been provided and satisfies this search value", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-deceased", + "code": "deceased", + "type": "token", + "expression": "Patient.deceased.exists() and Patient.deceased != false", + "base": [ + "Patient" + ], + "description": "This patient has been marked as deceased, or as a death date entered", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/patient-extensions-Patient-age", + "code": "age", + "type": "number", + "expression": null, + "base": [ + "Patient" + ], + "description": "Searches for patients based on age as calculated based on current date and date of birth. Deceased patients are excluded from the search.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/patient-extensions-Patient-birthOrderBoolean", + "code": "birthOrderBoolean", + "type": "token", + "expression": null, + "base": [ + "Patient" + ], + "description": "Search based on whether a patient was part of a multiple birth or not.", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/patient-extensions-Patient-mothersMaidenName", + "code": "mothersMaidenName", + "type": "string", + "expression": "Patient.extension('http://hl7.org/fhir/StructureDefinition/patient-extensions-Patient-mothersMaidenName')", + "base": [ + "Patient" + ], + "description": "Search based on patient's mother's maiden name", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-general-practitioner", + "code": "general-practitioner", + "type": "reference", + "expression": "Patient.generalPractitioner", + "base": [ + "Patient" + ], + "description": "Patient's nominated general practitioner, not the organization that manages the record", + "target": [ + "Practitioner", + "Organization", + "PractitionerRole" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-identifier", + "code": "identifier", + "type": "token", + "expression": "Patient.identifier", + "base": [ + "Patient" + ], + "description": "A patient identifier", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-language", + "code": "language", + "type": "token", + "expression": "Patient.communication.language", + "base": [ + "Patient" + ], + "description": "Language code (irrespective of use value)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-link", + "code": "link", + "type": "reference", + "expression": "Patient.link.other", + "base": [ + "Patient" + ], + "description": "All patients linked to the given patient", + "target": [ + "Patient", + "RelatedPerson" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-name", + "code": "name", + "type": "string", + "expression": "Patient.name", + "base": [ + "Patient" + ], + "description": "A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Patient-organization", + "code": "organization", + "type": "reference", + "expression": "Patient.managingOrganization", + "base": [ + "Patient" + ], + "description": "The organization that is the custodian of the patient record", + "target": [ + "Organization" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Practitioner-active", + "code": "active", + "type": "token", + "expression": "Practitioner.active", + "base": [ + "Practitioner" + ], + "description": "Whether the practitioner record is active", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Practitioner-communication", + "code": "communication", + "type": "token", + "expression": "Practitioner.communication", + "base": [ + "Practitioner" + ], + "description": "One of the languages that the practitioner can communicate with", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Practitioner-identifier", + "code": "identifier", + "type": "token", + "expression": "Practitioner.identifier", + "base": [ + "Practitioner" + ], + "description": "A practitioner's Identifier", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Practitioner-name", + "code": "name", + "type": "string", + "expression": "Practitioner.name", + "base": [ + "Practitioner" + ], + "description": "A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/RelatedPerson-active", + "code": "active", + "type": "token", + "expression": "RelatedPerson.active", + "base": [ + "RelatedPerson" + ], + "description": "Indicates if the related person record is active", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/RelatedPerson-identifier", + "code": "identifier", + "type": "token", + "expression": "RelatedPerson.identifier", + "base": [ + "RelatedPerson" + ], + "description": "An Identifier of the RelatedPerson", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/RelatedPerson-name", + "code": "name", + "type": "string", + "expression": "RelatedPerson.name", + "base": [ + "RelatedPerson" + ], + "description": "A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/RelatedPerson-patient", + "code": "patient", + "type": "reference", + "expression": "RelatedPerson.patient", + "base": [ + "RelatedPerson" + ], + "description": "The patient this related person is related to", + "target": [ + "Patient" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/RelatedPerson-relationship", + "code": "relationship", + "type": "token", + "expression": "RelatedPerson.relationship", + "base": [ + "RelatedPerson" + ], + "description": "The relationship between the patient and the relatedperson", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-content", + "code": "_content", + "type": "string", + "expression": null, + "base": [ + "Resource" + ], + "description": "Search on the entire content of the resource", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-id", + "code": "_id", + "type": "token", + "expression": "Resource.id", + "base": [ + "Resource" + ], + "description": "Logical id of this artifact", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-lastUpdated", + "code": "_lastUpdated", + "type": "date", + "expression": "Resource.meta.lastUpdated", + "base": [ + "Resource" + ], + "description": "When the resource version last changed", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-profile", + "code": "_profile", + "type": "uri", + "expression": "Resource.meta.profile", + "base": [ + "Resource" + ], + "description": "Profiles this resource claims to conform to", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-query", + "code": "_query", + "type": "token", + "expression": null, + "base": [ + "Resource" + ], + "description": "A custom search profile that describes a specific defined query operation", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-security", + "code": "_security", + "type": "token", + "expression": "Resource.meta.security", + "base": [ + "Resource" + ], + "description": "Security Labels applied to this resource", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-source", + "code": "_source", + "type": "uri", + "expression": "Resource.meta.source", + "base": [ + "Resource" + ], + "description": "Identifies where the resource comes from", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/Resource-tag", + "code": "_tag", + "type": "token", + "expression": "Resource.meta.tag", + "base": [ + "Resource" + ], + "description": "Tags applied to this resource", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/SearchParameter-base", + "code": "base", + "type": "token", + "expression": "SearchParameter.base", + "base": [ + "SearchParameter" + ], + "description": "The resource type(s) this search parameter applies to", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/SearchParameter-code", + "code": "code", + "type": "token", + "expression": "SearchParameter.code", + "base": [ + "SearchParameter" + ], + "description": "Code used in URL", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/SearchParameter-component", + "code": "component", + "type": "reference", + "expression": "SearchParameter.component.definition", + "base": [ + "SearchParameter" + ], + "description": "Defines how the part works", + "target": [ + "SearchParameter" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/SearchParameter-derived-from", + "code": "derived-from", + "type": "reference", + "expression": "SearchParameter.derivedFrom", + "base": [ + "SearchParameter" + ], + "description": "Original definition for the search parameter", + "target": [ + "SearchParameter" + ], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/SearchParameter-target", + "code": "target", + "type": "token", + "expression": "SearchParameter.target", + "base": [ + "SearchParameter" + ], + "description": "Types of resource (if a resource reference)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/SearchParameter-type", + "code": "type", + "type": "token", + "expression": "SearchParameter.type", + "base": [ + "SearchParameter" + ], + "description": "number | date | string | token | reference | composite | quantity | uri | special", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/ValueSet-code", + "code": "code", + "type": "token", + "expression": "ValueSet.expansion.contains.code | ValueSet.compose.include.concept.code", + "base": [ + "ValueSet" + ], + "description": "This special parameter searches for codes in the value set. See additional notes on the ValueSet resource", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/ValueSet-expansion", + "code": "expansion", + "type": "uri", + "expression": "ValueSet.expansion.identifier", + "base": [ + "ValueSet" + ], + "description": "Identifies the value set expansion (business identifier)", + "target": [], + "component": [] + }, + { + "url": "http://hl7.org/fhir/SearchParameter/ValueSet-reference", + "code": "reference", + "type": "uri", + "expression": "ValueSet.compose.include.system", + "base": [ + "ValueSet" + ], + "description": "A code system included or excluded in the value set or an imported value set", + "target": [], + "component": [] + } + ], + "compartments": [ + { + "code": "Device", + "url": "http://hl7.org/fhir/CompartmentDefinition/device", + "resource": [ + { + "code": "AuditEvent", + "param": [ + "agent" + ] + }, + { + "code": "Condition", + "param": [] + }, + { + "code": "Device", + "param": [] + }, + { + "code": "Encounter", + "param": [] + }, + { + "code": "Group", + "param": [ + "member" + ] + }, + { + "code": "List", + "param": [ + "subject", + "source" + ] + }, + { + "code": "MedicationRequest", + "param": [] + }, + { + "code": "Observation", + "param": [ + "subject", + "device" + ] + }, + { + "code": "Organization", + "param": [] + }, + { + "code": "Patient", + "param": [] + }, + { + "code": "Practitioner", + "param": [] + }, + { + "code": "RelatedPerson", + "param": [] + }, + { + "code": "SearchParameter", + "param": [] + }, + { + "code": "ValueSet", + "param": [] + } + ] + }, + { + "code": "Encounter", + "url": "http://hl7.org/fhir/CompartmentDefinition/encounter", + "resource": [ + { + "code": "AuditEvent", + "param": [] + }, + { + "code": "Condition", + "param": [ + "encounter" + ] + }, + { + "code": "Device", + "param": [] + }, + { + "code": "Encounter", + "param": [ + "{def}" + ] + }, + { + "code": "Group", + "param": [] + }, + { + "code": "List", + "param": [] + }, + { + "code": "MedicationRequest", + "param": [ + "encounter" + ] + }, + { + "code": "Observation", + "param": [ + "encounter" + ] + }, + { + "code": "Organization", + "param": [] + }, + { + "code": "Patient", + "param": [] + }, + { + "code": "Practitioner", + "param": [] + }, + { + "code": "RelatedPerson", + "param": [] + }, + { + "code": "SearchParameter", + "param": [] + }, + { + "code": "ValueSet", + "param": [] + } + ] + }, + { + "code": "Device", + "url": "http://hl7.org/fhir/CompartmentDefinition/example", + "resource": [] + }, + { + "code": "Patient", + "url": "http://hl7.org/fhir/CompartmentDefinition/patient", + "resource": [ + { + "code": "AuditEvent", + "param": [ + "patient" + ] + }, + { + "code": "Condition", + "param": [ + "patient", + "asserter" + ] + }, + { + "code": "Device", + "param": [] + }, + { + "code": "Encounter", + "param": [ + "patient" + ] + }, + { + "code": "Group", + "param": [ + "member" + ] + }, + { + "code": "List", + "param": [ + "subject", + "source" + ] + }, + { + "code": "MedicationRequest", + "param": [ + "subject" + ] + }, + { + "code": "Observation", + "param": [ + "subject", + "performer" + ] + }, + { + "code": "Organization", + "param": [] + }, + { + "code": "Patient", + "param": [ + "link" + ] + }, + { + "code": "Practitioner", + "param": [] + }, + { + "code": "RelatedPerson", + "param": [ + "patient" + ] + }, + { + "code": "SearchParameter", + "param": [] + }, + { + "code": "ValueSet", + "param": [] + } + ] + }, + { + "code": "Practitioner", + "url": "http://hl7.org/fhir/CompartmentDefinition/practitioner", + "resource": [ + { + "code": "AuditEvent", + "param": [ + "agent" + ] + }, + { + "code": "Condition", + "param": [ + "asserter" + ] + }, + { + "code": "Device", + "param": [] + }, + { + "code": "Encounter", + "param": [ + "practitioner", + "participant" + ] + }, + { + "code": "Group", + "param": [ + "member" + ] + }, + { + "code": "List", + "param": [ + "source" + ] + }, + { + "code": "MedicationRequest", + "param": [ + "requester" + ] + }, + { + "code": "Observation", + "param": [ + "performer" + ] + }, + { + "code": "Organization", + "param": [] + }, + { + "code": "Patient", + "param": [ + "general-practitioner" + ] + }, + { + "code": "Practitioner", + "param": [ + "{def}" + ] + }, + { + "code": "RelatedPerson", + "param": [] + }, + { + "code": "SearchParameter", + "param": [] + }, + { + "code": "ValueSet", + "param": [] + } + ] + }, + { + "code": "RelatedPerson", + "url": "http://hl7.org/fhir/CompartmentDefinition/relatedPerson", + "resource": [ + { + "code": "AuditEvent", + "param": [] + }, + { + "code": "Condition", + "param": [ + "asserter" + ] + }, + { + "code": "Device", + "param": [] + }, + { + "code": "Encounter", + "param": [ + "participant" + ] + }, + { + "code": "Group", + "param": [] + }, + { + "code": "List", + "param": [] + }, + { + "code": "MedicationRequest", + "param": [] + }, + { + "code": "Observation", + "param": [ + "performer" + ] + }, + { + "code": "Organization", + "param": [] + }, + { + "code": "Patient", + "param": [ + "link" + ] + }, + { + "code": "Practitioner", + "param": [] + }, + { + "code": "RelatedPerson", + "param": [ + "{def}" + ] + }, + { + "code": "SearchParameter", + "param": [] + }, + { + "code": "ValueSet", + "param": [] + } + ] + } + ], + "summary": { + "AuditEvent": [ + "id", + "meta", + "implicitRules", + "type", + "subtype", + "action", + "recorded", + "outcome", + "outcomeDesc", + "purposeOfEvent" + ], + "Condition": [ + "id", + "meta", + "implicitRules", + "identifier", + "clinicalStatus", + "verificationStatus", + "code", + "bodySite", + "subject", + "encounter", + "onset", + "recordedDate", + "recorder", + "asserter" + ], + "Device": [ + "id", + "meta", + "implicitRules", + "udiCarrier", + "status", + "safety" + ], + "Encounter": [ + "id", + "meta", + "implicitRules", + "identifier", + "status", + "class", + "type", + "serviceType", + "subject", + "episodeOfCare", + "participant", + "appointment", + "reasonCode", + "reasonReference", + "diagnosis" + ], + "Group": [ + "id", + "meta", + "implicitRules", + "identifier", + "active", + "type", + "actual", + "code", + "name", + "quantity", + "managingEntity" + ], + "List": [ + "id", + "meta", + "implicitRules", + "status", + "mode", + "title", + "code", + "subject", + "date", + "source" + ], + "MedicationRequest": [ + "id", + "meta", + "implicitRules", + "status", + "intent", + "priority", + "doNotPerform", + "reported", + "medication", + "subject", + "authoredOn", + "requester", + "performerType", + "instantiatesCanonical", + "instantiatesUri", + "basedOn", + "groupIdentifier" + ], + "Observation": [ + "id", + "meta", + "implicitRules", + "identifier", + "basedOn", + "partOf", + "status", + "code", + "subject", + "focus", + "encounter", + "effective", + "issued", + "performer", + "value", + "hasMember", + "derivedFrom", + "component" + ], + "Organization": [ + "id", + "meta", + "implicitRules", + "identifier", + "active", + "type", + "name", + "partOf" + ], + "Patient": [ + "id", + "meta", + "implicitRules", + "identifier", + "active", + "name", + "telecom", + "gender", + "birthDate", + "deceased", + "address", + "managingOrganization", + "link" + ], + "Practitioner": [ + "id", + "meta", + "implicitRules", + "identifier", + "active", + "name", + "telecom", + "address", + "gender", + "birthDate" + ], + "RelatedPerson": [ + "id", + "meta", + "implicitRules", + "identifier", + "active", + "patient", + "relationship", + "name", + "telecom", + "gender", + "birthDate", + "address" + ], + "SearchParameter": [ + "id", + "meta", + "implicitRules", + "url", + "version", + "name", + "status", + "experimental", + "date", + "publisher", + "contact", + "description", + "useContext", + "jurisdiction", + "code", + "base", + "type" + ], + "ValueSet": [ + "id", + "meta", + "implicitRules", + "url", + "identifier", + "version", + "name", + "title", + "status", + "experimental", + "date", + "publisher", + "contact", + "useContext", + "jurisdiction", + "immutable" + ] + }, + "mandatory": { + "AuditEvent": [ + "type", + "recorded", + "agent", + "source" + ], + "Condition": [ + "subject" + ], + "Device": [], + "Encounter": [ + "status", + "class" + ], + "Group": [ + "type", + "actual" + ], + "List": [ + "status", + "mode" + ], + "MedicationRequest": [ + "status", + "intent", + "medication", + "subject" + ], + "Observation": [ + "status", + "code" + ], + "Organization": [], + "Patient": [], + "Practitioner": [], + "RelatedPerson": [ + "patient" + ], + "SearchParameter": [ + "url", + "name", + "status", + "description", + "code", + "base", + "type" + ], + "ValueSet": [ + "status" + ] + } +} diff --git a/tests/ips/fhirpath-ips.test.js b/tests/ips/fhirpath-ips.test.js index 77736d93..9e3fd481 100644 --- a/tests/ips/fhirpath-ips.test.js +++ b/tests/ips/fhirpath-ips.test.js @@ -34,7 +34,9 @@ const ev = (expr, res = doc(), options) => evaluate(res, expr, options); describe('section()', () => { test('finds the sections with the code, nested ones too', () => { - expect(ev(`section('${L}', '11450-4').count()`)).toEqual([2]); + expect(ev(`section('${L}', '11450-4', 0, '*').count()`)).toEqual([2]); + // without bounds, one such section (as the Java DocumentFunctions): there are two, so none + expect(ev(`section('${L}', '11450-4')`)).toEqual([]); expect(ev(`section('${L}', '10160-0').entry.reference`)).toEqual(['urn:uuid:m1', 'urn:uuid:m2']); expect(ev(`section('${L}', '99999-9')`)).toEqual([]); expect(ev(`section('http://other', '11450-4')`)).toEqual([]); @@ -50,7 +52,7 @@ describe('section()', () => { test('takes Compositions, and several inputs each on its own', () => { expect(ev(`entry.resource.ofType(Composition).section('${L}', '10160-0').count()`)).toEqual([1]); - expect(evaluate(doc().entry[0].resource, `section('${L}', '11450-4').count()`)).toEqual([2]); + expect(evaluate(doc().entry[0].resource, `section('${L}', '11450-4', 0, '*').count()`)).toEqual([2]); // two documents: each is counted alone const one = doc(); one.entry[0].resource.section[1].section = []; @@ -69,7 +71,7 @@ describe('section()', () => { describe('entry()', () => { test('resolves the entries and matches their code, medicationCodeableConcept or vaccineCode', () => { - expect(ev(`section('${L}', '11450-4').entry('${S}', '38341003').resourceType`)).toEqual(['Condition', 'Condition']); + expect(ev(`section('${L}', '11450-4', 0, '*').entry('${S}', '38341003').resourceType`)).toEqual(['Condition', 'Condition']); expect(ev(`section('${L}', '10160-0').entry('${S}', '774421004').resourceType`)).toEqual(['MedicationStatement']); expect(ev(`section('${L}', '11369-6').entry('${S}', '836377006').resourceType`)).toEqual(['Immunization']); // what comes back can be navigated @@ -82,8 +84,8 @@ describe('entry()', () => { test('all or nothing for each section, by min..max', () => { // in the top problems section once, and in the nested one once - expect(ev(`section('${L}', '11450-4').entry('${S}', '38341003', 1, 1).count()`)).toEqual([2]); - expect(ev(`section('${L}', '11450-4').entry('${S}', '44054006', 1, 1).count()`)).toEqual([1]); + expect(ev(`section('${L}', '11450-4', 0, '*').entry('${S}', '38341003', 1, 1).count()`)).toEqual([2]); + expect(ev(`section('${L}', '11450-4', 0, '*').entry('${S}', '44054006', 1, 1).count()`)).toEqual([1]); expect(ev(`section('${L}', '11450-4').entry('${S}', '44054006', 0, 0)`)).toEqual([]); expect(ev(`section('${L}', '11450-4').entry('${S}', '38341003', 2, '*')`)).toEqual([]); }); @@ -98,7 +100,7 @@ describe('entry()', () => { const all = Object.fromEntries(doc().entry.map(e => [e.fullUrl, e.resource])); const seen = []; const resolve = (ref, c) => { seen.push([ref, c?.id]); return all[ref] || null; }; - expect(evaluate(comp, `section('${L}', '11450-4').entry('${S}', '38341003').count()`, { resolve })).toEqual([2]); + expect(evaluate(comp, `section('${L}', '11450-4', 0, '*').entry('${S}', '38341003').count()`, { resolve })).toEqual([2]); expect(seen).toContainEqual(['urn:uuid:p1', 'comp']); }); @@ -167,8 +169,8 @@ describe('entryIn() and resourcesIn()', () => { test('match by value set, synchronously when the answers are', () => { const membership = inVs; - expect(ev(`section('${L}', '11450-4').entryIn('${PROBLEMS}').count()`, doc(), { membership })).toEqual([3]); - expect(ev(`section('${L}', '11450-4').entryIn('${PROBLEMS}', 2, 2).count()`, doc(), { membership })).toEqual([2]); + expect(ev(`section('${L}', '11450-4', 0, '*').entryIn('${PROBLEMS}').count()`, doc(), { membership })).toEqual([3]); + expect(ev(`section('${L}', '11450-4', 0, '*').entryIn('${PROBLEMS}', 2, 2).count()`, doc(), { membership })).toEqual([2]); expect(ev(`section('${L}', '11450-4').entryIn('${MEDS}')`, doc(), { membership })).toEqual([]); expect(ev(`resourcesIn('${MEDS}').resourceType`, doc(), { membership })).toEqual(['MedicationStatement', 'Medication']); expect(ev(`resourcesIn('${MEDS}', 'Medication').count()`, doc(), { membership })).toEqual([1]); @@ -194,3 +196,72 @@ describe('entryIn() and resourcesIn()', () => { expect(() => ev(`resourcesIn('${PROBLEMS}')`, doc(), { membership })).toThrow(/async/i); }); }); + +describe('the section checks: isKnown(), hasData(), sameSubject() - as the Java DocumentFunctionsSectionTests', () => { + const ER = 'http://terminology.hl7.org/CodeSystem/list-empty-reason'; + const sec = (code, rest) => ({ code: { coding: [{ system: 'http://loinc.org', code }] }, ...rest }); + const reason = (code) => ({ emptyReason: { coding: [{ system: ER, code }] } }); + const doc = { + resourceType: 'Bundle', type: 'document', entry: [ + { + fullUrl: 'urn:uuid:c', + resource: { + resourceType: 'Composition', status: 'final', subject: { reference: 'urn:uuid:p' }, title: 'x', + section: [ + sec('11450-4', { entry: [{ reference: 'urn:uuid:c1' }] }), + sec('48765-2', reason('nilknown')), + sec('10160-0', reason('notasked')), + sec('46264-8', { text: { status: 'generated', div: '
    x
    ' } }), + sec('11369-6', { emptyReason: { text: 'we didn\'t look' } }), + sec('42348-3', { focus: { reference: 'urn:uuid:p' }, ...reason('nilknown') }), + sec('18776-5', { focus: { reference: 'urn:uuid:other' }, ...reason('nilknown') }), + sec('47519-4', { entry: [{ reference: 'urn:uuid:c1' }], section: [sec('30954-2', reason('withheld'))] }) + ] + } + }, + { fullUrl: 'urn:uuid:p', resource: { resourceType: 'Patient', name: [{ family: 'x' }] } }, + { fullUrl: 'urn:uuid:c1', resource: { resourceType: 'Condition', id: 'c1', code: { coding: [{ system: 'http://snomed.info/sct', code: '38341003' }] }, subject: { reference: 'urn:uuid:p' } } } + ] + }; + const s = (code) => `Bundle.section('http://loinc.org', '${code}')`; + const cases = [ + [`${s('11450-4')}.isKnown()`, [true]], [`${s('48765-2')}.isKnown()`, [true]], [`${s('10160-0')}.isKnown()`, [false]], + [`${s('46264-8')}.isKnown()`, [true]], [`${s('11369-6')}.isKnown()`, [false]], [`${s('30954-2')}.isKnown()`, [false]], + [`${s('11450-4')}.hasData()`, [true]], [`${s('48765-2')}.hasData()`, [true]], [`${s('10160-0')}.hasData()`, [true]], [`${s('46264-8')}.hasData()`, [false]], + [`${s('11450-4')}.sameSubject()`, [true]], [`${s('42348-3')}.sameSubject()`, [true]], [`${s('18776-5')}.sameSubject()`, [false]], + ['Bundle.entry.resource.ofType(Condition).sameSubject()', [true]], + [`${s('99999-9')}.isKnown()`, []], [`${s('99999-9')}.hasData()`, []], + ['Bundle.entry.resource.ofType(Condition).isKnown()', [false]], ['Bundle.entry.resource.ofType(Condition).hasData()', [false]], + [`${s('11450-4')}.where(isKnown() and hasData() and sameSubject()).exists()`, [true]], + [`${s('46264-8')}.where(isKnown() and hasData()).exists()`, [false]], + [`${s('18776-5')}.where(isKnown() and sameSubject()).exists()`, [false]], + [`${s('11450-4')}.where(hasData()).entry('http://snomed.info/sct', '38341003').exists()`, [true]], + // sections reached by ordinary navigation are sections too + ["Bundle.entry.resource.ofType(Composition).section.where(code.coding.code = '10160-0').isKnown()", [false]] + ]; + test.each(cases)('%s', (expression, expected) => { + expect(evaluate(doc, expression)).toEqual(expected); + }); + + test('sameSubject(other): the subject of other; and on resources, a subject compared by reference, else identifier', () => { + const vars = { vars: { resource: doc } }; + expect(evaluate(doc, `${s('18776-5')}.sameSubject(%resource.entry.resource.ofType(Condition))`, vars)).toEqual([false]); + expect(evaluate(doc, `${s('42348-3')}.sameSubject(%resource.entry.resource.ofType(Condition))`, vars)).toEqual([true]); + // other given, but empty: empty + expect(evaluate(doc, `${s('42348-3')}.sameSubject({})`)).toEqual([]); + const ids = (a, b) => ({ + resourceType: 'Bundle', type: 'document', entry: [ + { resource: { resourceType: 'Composition', subject: a, section: [] } }, + { resource: { resourceType: 'Observation', id: 'o', subject: b } } + ] + }); + const id = (value, system = 'http://x') => ({ identifier: { system, value } }); + expect(evaluate(ids(id('1'), id('1')), 'Bundle.entry.resource.ofType(Observation).sameSubject()')).toEqual([true]); + expect(evaluate(ids(id('1'), id('1', 'http://y')), 'Bundle.entry.resource.ofType(Observation).sameSubject()')).toEqual([false]); + expect(evaluate(ids(id('1'), { display: 'x' }), 'Bundle.entry.resource.ofType(Observation).sameSubject()')).toEqual([false]); + expect(evaluate(ids(id('1'), undefined), 'Bundle.entry.resource.ofType(Observation).sameSubject()')).toEqual([]); + // not a document: no Composition to compare with + const notDoc = { ...ids(id('1'), id('1')), type: 'collection' }; + expect(evaluate(notDoc, 'Bundle.entry.resource.ofType(Observation).sameSubject()')).toEqual([]); + }); +}); diff --git a/tests/ips/ips.test.js b/tests/ips/ips.test.js index 4bf10c7d..9f99d120 100644 --- a/tests/ips/ips.test.js +++ b/tests/ips/ips.test.js @@ -2233,7 +2233,7 @@ describe('sharing as SHL / VHL', () => { await post(app, 'demo', ips()); mod.store.savePatientComment(1, 'Mine', 'Jane'); const png = (r) => r.buffer(true).parse((res, cb) => { const c = []; res.on('data', d => c.push(d)); res.on('end', () => cb(null, Buffer.concat(c))); }); - let r = await png(request(app).get('/ips/demo/Bundle/1/$document?patient-notes=true').set('Host', 'example.org').set('Accept', 'application/smart-health-link')); + let r = await png(request(app).get('/ips/demo/Bundle/1/$document?patient-notes=true&format-type=shl').set('Host', 'example.org').set('Accept', 'image/png')); expect(r.status).toBe(200); expect(r.headers['content-type']).toBe('image/png'); expect(r.body.subarray(0, 8)).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])); @@ -2245,10 +2245,16 @@ describe('sharing as SHL / VHL', () => { const jwe = Buffer.from(mod.shlEntries.get('u1').files[0].cnt, 'base64').toString('utf8'); const shared = JSON.parse(Buffer.from((await jose.compactDecrypt(jwe, Buffer.from(payload.key, 'base64url'))).plaintext).toString('utf8')); expect(shared.entry[0].resource.section[0].title).toBe('Patient\'s Comments'); - r = await png(request(app).get('/ips/demo/Bundle/1/$document?_format=vhl').set('Host', 'example.org')); + // image/png on its own is a VHL + expect(calls.some(c => c.sign)).toBe(false); + r = await png(request(app).get('/ips/demo/Bundle/1/$document').set('Host', 'example.org').set('Accept', 'image/png')); expect(r.status).toBe(200); expect(r.headers['content-type']).toBe('image/png'); expect(calls.some(c => c.sign)).toBe(true); + // format-type decides: a QR code whatever Accept says + r = await png(request(app).get('/ips/demo/Bundle/1/$document?format-type=vhl').set('Host', 'example.org').set('Accept', 'application/fhir+json')); + expect(r.headers['content-type']).toBe('image/png'); + expect(r.headers['x-health-link']).toMatch(/^HC1:/); }); test('shares a document as an SHL: encrypted on the SHL server, the key in the link, the QR of the viewer link', async () => { @@ -2867,7 +2873,7 @@ describe('clinical profiles', () => { let mod; const L = 'http://loinc.org'; const S = 'http://snomed.info/sct'; - const rule = `Bundle.section('${L}', '11450-4', 1, '*').entry('${S}', '38341003').exists()`; + const rule = `Bundle.section('${L}', '11450-4').where(isKnown() and hasData()).entry('${S}', '38341003').exists()`; beforeEach(async () => { ({ app, mod } = await makeApp({ txServer: '/tx/r4' })); app.get('/tx/r4/metadata', (req, res) => res.type('application/fhir+json').send(JSON.stringify({ resourceType: 'CapabilityStatement' }))); @@ -2883,9 +2889,11 @@ describe('clinical profiles', () => { // the administrator, and the token the editor sends const asAdmin = async () => { const { agent } = await loginAs(app, 'admin', ADMIN_PASSWORD); - const page = await agent.get('/ips/StructureDefinition/new').set('Accept', 'text/html'); + // the list page has the New profile box, and the token its script sends + const page = await agent.get('/ips/StructureDefinition').set('Accept', 'text/html'); expect(page.status).toBe(200); - const csrf = JSON.parse(/window\.IPS_PROFILE = (.*?);<\/script>/.exec(page.text)[1]).csrf; + expect(page.text).toContain('id="ips-pf-new"'); + const csrf = /_csrf: "([^"]+)"/.exec(page.text)[1]; const send = (url, body) => agent.post(url).set('Origin', 'http://example.org').set('Host', 'example.org').set('Accept', 'application/json').send({ ...body, _csrf: csrf }); return { agent, send }; }; @@ -2907,7 +2915,7 @@ describe('clinical profiles', () => { expect(dl.headers['content-disposition']).toBe('attachment; filename="CardiologyReferral.json"'); // the pages: the rule as words for a shaped one, the expression for the other; no editing for a visitor const page = await request(app).get(`/ips/StructureDefinition/${id}`).set('Accept', 'text/html'); - expect(page.text).toContain('A problem list with hypertensionProblem List (LOINC|11450-4) [1..*]Code is SNOMED CT|38341003'); + expect(page.text).toContain('A problem list with hypertensionProblem List (LOINC|11450-4) - must be asked/known, must have supporting entriesCode is SNOMED CT|38341003'); expect(page.text).toContain('ExpectationSectionEntry'); expect(page.text).toContain('Bundle.entry.count() >= 2'); expect(page.text).toContain('Hypertension is activeConditions where Code is SNOMED CT|38341003.all(clinicalStatus.coding.code = 'active')'); @@ -2922,17 +2930,19 @@ describe('clinical profiles', () => { const listPage = await request(app).get('/ips/StructureDefinition').set('Accept', 'text/html'); expect(listPage.text).toContain('Cardiology referral'); expect(listPage.text).not.toContain('New profile'); - // the administrator's editor gets the shapes - const editor = await agent.get(`/ips/StructureDefinition/${id}/edit`).set('Accept', 'text/html'); + // the administrator's page gets the shapes; there is no full editor (an old link to it lands on the page) + expect((await agent.get(`/ips/StructureDefinition/${id}/edit`)).headers.location).toBe(`/ips/StructureDefinition/${id}`); + const editor = await agent.get(`/ips/StructureDefinition/${id}`).set('Accept', 'text/html'); + expect(editor.text).not.toContain('Edit all'); const cfg = JSON.parse(/window\.IPS_PROFILE = (.*?);<\/script>/.exec(editor.text)[1]); - expect(cfg.profile.constraints[0]).toMatchObject({ key: 'cp-1', shape: { section: { system: L, code: '11450-4', min: 1, max: '*' }, entry: { system: S, code: '38341003', min: null, max: null } } }); + expect(cfg.profile.constraints[0]).toMatchObject({ key: 'cp-1', shape: { section: { system: L, code: '11450-4', checks: ['isKnown', 'hasData'] }, entry: { system: S, code: '38341003', min: null, max: null } } }); expect(cfg.profile.constraints[1].shape).toBeNull(); expect(cfg.profile.constraints[1].rshape).toBeNull(); expect(cfg.profile.constraints[2].rshape).toEqual({ type: 'Condition', system: S, code: '38341003', rest: ".all(clinicalStatus.coding.code = 'active')" }); expect(cfg.parts.map(p => p[0])).toEqual(['section', 'resource', 'other']); expect(cfg.resourceTypes).toContain('Condition'); expect(cfg.sections[0]).toEqual({ code: '11450-4', title: 'Problem List' }); - expect(cfg.urls).toEqual({ save: `/ips/StructureDefinition/${id}`, lookup: '/ips/lookup', lookupVs: '/ips/lookup-vs', back: `/ips/StructureDefinition/${id}` }); + expect(cfg.urls).toEqual({ constraint: `/ips/StructureDefinition/${id}/constraint`, guide: `/ips/StructureDefinition/${id}/guide`, lookup: '/ips/lookup', lookupVs: '/ips/lookup-vs' }); // an edit keeps the url and the kept keys const saved = await send(`/ips/StructureDefinition/${id}`, { title: 'Cardiology referral v2', constraints: [{ key: 'cp-2', human: 'At least two sections', expression: 'Bundle.entry.count() >= 2' }, { human: 'Medications', expression: `Bundle.section('${L}', '10160-0', 1, 1).exists()` }] }); expect(saved.status).toBe(200); @@ -2971,29 +2981,29 @@ describe('clinical profiles', () => { test('the administrator adds, edits and deletes a rule at a time, on the profile\'s page', async () => { const { agent, send } = await asAdmin(); const vs = 'http://example.org/ValueSet/heart'; - const made = await send('/ips/StructureDefinition', { title: 'Rows', constraints: [{ human: 'Problems', expression: `Bundle.section('${L}', '11450-4', 1, 1).exists()` }, { human: 'Two entries', expression: 'Bundle.entry.count() >= 2' }] }); + const made = await send('/ips/StructureDefinition', { title: 'Rows', constraints: [{ human: 'Problems', expression: `Bundle.section('${L}', '11450-4').isKnown()` }, { human: 'Two entries', expression: 'Bundle.entry.count() >= 2' }] }); const id = made.body.id; const at = `/ips/StructureDefinition/${id}`; // the same page as a visitor's, with the rows' actions and the script const page = await agent.get(at).set('Accept', 'text/html'); - expect(page.text).toContain('ProblemsProblem List (LOINC|11450-4)'); + expect(page.text).toContain('ProblemsProblem List (LOINC|11450-4) - must be asked/known'); expect(page.text).toContain(`action="${at}/constraint/cp-1/delete"`); expect(page.text).toContain('