# @atomic-ehr/fhir-canonical-manager 中文文档

规范地址：https://npmcn.com/package/%40atomic-ehr/fhir-canonical-manager/

版本：0\.0\.29
npm 元数据更新时间：2026-10-14T12:39:52.432Z
中文译文更新时间：2026-11-07T03:24:14.947Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40atomic-ehr/fhir-canonical-manager
原文对照：https://npmcn.com/package/%40atomic-ehr/fhir-canonical-manager/?lang=original
项目主页：https://github.com/atomic-ehr/fhir-canonical-manager#readme
源码仓库：https://github.com/atomic-ehr/fhir-canonical-manager

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：225 kB，123 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：typescript ^5
- 首次发布：2025-07-31T08:54:08.562Z
- 最新版本发布：2026-10-14T12:39:51.982Z
- 近 30 天下载量：9350（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：98（近 12 个月 69 个）

## 中文简介

[![npm canary](https://img.shields.io/npm/v/@atomic-ehr/fhir-canonical-manager/canary.svg?label=canary)](https://www.npmjs.com/package/@atomic-ehr/fhir-canonical-manager/v/canary) \[!\]\[npm版本\] (https://img.shields.io/npm/v/@原子-ehr/fhir-canonical-man) (中文(简体) )

## 安装

```sh
npm install @atomic-ehr/fhir-canonical-manager
```

也可以使用：`pnpm add @atomic-ehr/fhir-canonical-manager`、`yarn add @atomic-ehr/fhir-canonical-manager`、`bun add @atomic-ehr/fhir-canonical-manager`

## README

# @ 原子- ehr/ fhir- canonical- 管理器

[![npm canary](https://img.shields.io/npm/v/@atomic-ehr/fhir-canonical-manager/canary.svg?label=canary)](https://www.npmjs.com/package/@atomic-ehr/fhir-canonical-manager/v/canary) [![npm version](https://img.shields.io/npm/v/@atomic-ehr/fhir-canonical-manager.svg)](https://www.npmjs.com/package/@atomic-ehr/fhir-canonical-manager) [![CI](https://github.com/atomic-ehr/fhir-canonical-manager/actions/workflows/ci.yml/badge.svg)](https://github.com/atomic-ehr/fhir-canonical-manager/actions/workflows/ci.yml)

为 FHIR 资源设置的 TypeScript 软件包管理器,提供犬形URL 分辨率. 这个库帮助您通过一个简单,实用的API来发现,解析和管理 FHIR 软件包及其资源.

## 特征

-   🚀 **自动软件包管理** - 自动安装和管理FHIR软件包
-   💾 **持续缓存** - Caches 软件包元数据到磁盘,用于快速的后加载
-   🔍 **光学 URL 分辨率** - 将词汇URL解为特定资源版本
-   📦 **多个软件包支持** - 与多个FHIR包同时工作
-   🎯 **灵活搜索** - 按类型、类型、URL、版本或包搜索资源
-   ⚡ **业绩优化** - 有磁盘连续的内存缓存
-   🛠️ **类型脚本第一** - 全面类型的脚本支持
-   🩹 **软件包处理** - 可编成的补丁、犬科排斥、指数恢复和诊断报告
-   🖥️ **CLI 工具** - 用于软件包管理和资源发现的命令行接口

## 安装

```bash
bun install @atomic-ehr/fhir-canonical-manager
# or
npm install @atomic-ehr/fhir-canonical-manager
```

## 快速启动

```typescript
import { CanonicalManager } from '@atomic-ehr/fhir-canonical-manager';

// Create and initialize the manager
const manager = CanonicalManager({
    packages: ["hl7.fhir.r4.core"],
    workingDir: "tmp/fhir",
    registry: "https://fs.get-ig.org/pkgs/" // optional, default registry
});

await manager.init();

// Resolve and read a resource
const resource = await manager.resolve('http://hl7.org/fhir/StructureDefinition/Patient');
console.log(resource.url); // http://hl7.org/fhir/StructureDefinition/Patient
```

## CLI 使用量

软件包包括一个强大的命令行接口(`fcm`)用于管理FHIR包并搜索资源而无需写入代码.

### 安装

```bash
# Install globally
npm install -g @atomic-ehr/fhir-canonical-manager

# Or use with npx
npx @atomic-ehr/fhir-canonical-manager

# Or run directly with bunx
bunx @atomic-ehr/fhir-canonical-manager
```

### 开始

```bash
# Create a new project and initialize with FHIR packages
mkdir my-fhir-project && cd my-fhir-project
fcm init hl7.fhir.r4.core

# Search for resources
fcm search Patient

# Get a specific resource
fcm resolve http://hl7.org/fhir/StructureDefinition/Patient
```

### 图标

#### `fcm init`

在当前目录中初始化 FHIR 包 .

```bash
# Initialize with packages
fcm init hl7.fhir.r4.core hl7.fhir.us.core@5.0.1

# With custom registry
fcm init hl7.fhir.r4.core --registry https://packages.simplifier.net

# Initialize from existing package.json
fcm init
```

配置存储于 `package.json`数字 :

```json
{
  "fcm": {
    "packages": ["hl7.fhir.r4.core", "hl7.fhir.us.core@5.0.1"],
    "registry": "https://fs.get-ig.org/pkgs/"
  }
}
```

#### `fcm list`

列出已安装的软件包或资源 .

```bash
# List all packages
fcm list

# List resources in a package
fcm list hl7.fhir.r4.core

# Filter by type
fcm list hl7.fhir.r4.core --type StructureDefinition

# Output as JSON
fcm list --json
```

#### `fcm search`

搜索具有高级过滤和前缀匹配能力的资源.

**基本用途:**

```bash
# Search by URL pattern
fcm search Patient

# Prefix search - space-separated terms match URL components
fcm search str def pat  # Matches: StructureDefinition/Patient
```

**资源类型快捷键 :**

```bash
fcm search -sd          # All StructureDefinitions
fcm search -cs          # All CodeSystems
fcm search -vs          # All ValueSets
fcm search -sd patient  # Patient-related StructureDefinitions
```

**高级过滤 :**

```bash
# Filter by type (-t)
fcm search -t Extension              # All Extensions
fcm search -t Patient                # Resources with type="Patient"
fcm search -sd -t Patient            # Patient StructureDefinition specifically

# Filter by kind (-k)
fcm search -k resource               # All resources (Patient, Observation, etc.)
fcm search -k complex-type           # All complex types (HumanName, Address, etc.)
fcm search -k primitive-type         # All primitive types (string, boolean, etc.)

# Combine filters
fcm search -t Extension -k complex-type  # All Extension complex types
fcm search -sd pat -t Extension          # Patient-related Extensions

# Filter by package
fcm search allergy --package hl7.fhir.us.core

# Output as JSON
fcm search Patient --json
```

**输出格式 :** 默认情况下,结果以格式显示为每行1:

```
url, {"resourceType":"...", "kind":"...", "type":"..."}
```

示例输出 :

```
http://hl7.org/fhir/StructureDefinition/Patient, {"resourceType":"StructureDefinition","kind":"resource","type":"Patient"}
```

#### `fcm resolve`

获取资源 .

```bash
# Display resource
fcm resolve http://hl7.org/fhir/StructureDefinition/Patient

# Save to file
fcm resolve http://hl7.org/fhir/ValueSet/administrative-gender > gender.json

# Show only specific fields
fcm resolve http://hl7.org/fhir/StructureDefinition/Patient --fields url,type,kind
```

#### `fcm searchparam`

显示特定 FHIR 资源类型的搜索参数.

```bash
# Display search parameters for Patient resource
fcm searchparam Patient

# Output as JSON
fcm searchparam Observation --format json

# Export as CSV for spreadsheet analysis
fcm searchparam Encounter --format csv > encounter-params.csv
```

**输出格式 :**

-   **图表** (默认): 以多行格式显示每个参数,并有完整数据
-   **乔森**: 输出为 JSON 阵列, 有代码、 类型、 表达式和 URL 字段
-   **(单位:千美元)**: 导出为用于电子表格分析的 CSV

示例输出(表格式) :

```
Code:       active
Type:       token
Expression: Patient.active
URL:        http://hl7.org/fhir/SearchParameter/Patient-active
---
Code:       address
Type:       string
Expression: Patient.address | Person.address | Practitioner.address |
            RelatedPerson.address
URL:        http://hl7.org/fhir/SearchParameter/individual-address
---
Code:       identifier
Type:       token
Expression: Patient.identifier
URL:        http://hl7.org/fhir/SearchParameter/Patient-identifier
---

Total: 29 search parameters
```

### CLI 实例

```bash
# Set up a new FHIR project
mkdir my-fhir-project && cd my-fhir-project
fcm init hl7.fhir.r4.core

# Search for Observation-related resources
fcm search observation

# Get a specific resource and save it
fcm resolve http://hl7.org/fhir/StructureDefinition/Observation > observation.json

# List all ValueSets in JSON format
fcm search --type ValueSet --json > valuesets.json
```

### 快速引用

| 任务 | 命令 |
| --- | --- |
| 启动项目 | `fcm init hl7.fhir.r4.core` |
| 列表软件包 | `fcm list` |
| 列表软件包资源 | `fcm list hl7.fhir.r4.core` |
| 搜索所有资源 | `fcm search` |
| 按名称搜索 | `fcm search Patient` |
| 以前缀搜索 | `fcm search str def pat` |
| 所有结构定义 | `fcm search -sd` |
| 所有代码系统 | `fcm search -cs` |
| 所有值设置 | `fcm search -vs` |
| 按类型过滤 | `fcm search -t Extension` |
| 按类型过滤 | `fcm search -k resource` |
| 组合过滤器 | `fcm search -sd -t Patient` |
| 获取资源 | `fcm resolve <url>` |
| 获取搜索参数 | `fcm searchparam Patient` |
| 导出为 JSON | `fcm search --json` |
| 导出参数为 CSV | `fcm searchparam Patient --format csv` |
| 帮助 | `fcm --help` |

## 核心概念

### 软件包管理

管理器自动处理 FHIR 包安装 :

1.  创建工作目录, 如果它不存在
2.  初始化 a `package.json` 扶养管理
3.  使用 npm 安装指定的 FHIR 包
4.  扫描软件包 `.index.json` 文件
5.  构建所有资源的内在索引
6.  持久缓存到 `.fcm/cache/index.json`

### 资源分辨率

资源由下列机构确定:

-   **目录 URL**: FHIR 资源的唯一标识符
-   **参考编号**: 基于软件包和文件路径的不透明、决定性散列
-   **软件包上下文**: 可选软件包名称/版本限制

## API 参考

### `CanonicalManager(config)`

创建新实例的 Cononic 管理器 .

```typescript
interface Config {
  packages: string[];               // FHIR packages to install (e.g., ["hl7.fhir.r4.core"])
  workingDir: string;               // Directory for packages and cache
  registry?: string;                // NPM registry URL (optional)
  dropCache?: boolean;              // Rebuild the cache instead of loading it from disk
  patches?: Partial<Patches>;       // Per-phase handler lists (see "Patches & defect handling")
  packageIndex?: PackageIndexMode;  // How to treat shipped .index.json files (default "use")
  /** @deprecated use `patches` — equivalent to package/resource handlers */
  preprocessPackage?: (ctx: PreprocessContext) => PreprocessContext;
  /** @deprecated use `packageIndex` */
  ignorePackageIndex?: boolean;
}
```

示例

```typescript
const manager = CanonicalManager({
    packages: [
        "hl7.fhir.r4.core",
        "hl7.fhir.us.core@5.0.1"
    ],
    workingDir: "./fhir-packages",
    registry: "https://fs.get-ig.org/pkgs/"
});
```

### 补丁和缺陷处理( D)

真实世界 FHIR 包船缺陷(缺少依赖性,犬类 URL 类型, 无法使用的值设置绑定、 交叉版本类型引用、 腐败 `.index.json`) (中文(简体) ). CanonicalManager 揭露出三个把柄在他们周围工作.

#### `packageIndex` - 如何对待装运货物 `.index.json`

```typescript
type PackageIndexMode = "use" | "recover" | "regenerate";
```

-   **`"use"`** (默认) : 信任已发送的索引; 仅在目录是时扫描目录 缺席。 腐败指数是 **警告( e)** 大约但不在周围工作(比对先前的行为).
-   **`"recover"`**: 使用索引,但返回到 **每个包装** 目录扫描时 它腐败或不完整(不可解析,或磁盘上缺少的引用文件).
-   **`"regenerate"`**:忽略已运出索引并总是扫描.

`ignorePackageIndex` 是一个被贬值的别名( )`true` → `"regenerate"`, (中文(简体) ), `false` → `"use"`(三); 设置它和 `packageIndex` 掷出.

#### `patches` ——可相容的转变和排除

`patches` 是一个单 `Patches` 可选对象 **每阶段处理者名单**, (中文(简体) ), 按每个处理器转换的值键—— `packageJson`, (中文(简体) ), `indexEntry`,以及 `fhirResource`。 。 。 . 每个处理器收到其包ID、该值和诊断槽,然后返回 a 转换值或 `undefined` 以至无;处于相位的处理器从左到右运行。 这个 `indexEntry` 处理器也可以返回 `null` 改为 **丢入** 条子(它从未进入) 页:1 仅提供您需要的阶段; 已贬值 `preprocessPackage` 现附上 在您的包 Json/fhir 资源处理器之后 .

```typescript
import type { PackagePatch } from "@atomic-ehr/fhir-canonical-manager";

// A handler is (pkg, value, report) => transformedValue | undefined.
// Fix a package's declared version at the package phase:
const fixVersion: PackagePatch = (pkg, packageJson) => ({ ...packageJson, version: "1.2.3" });

// patches: { packageJson: [fixVersion] }
```

捆绑的补丁帮助从 `@atomic-ehr/fhir-canonical-manager/patch` 子路径 :

-   **范围界定组合器** —— 说 `inPackage(match, [handlers])` 仅应用于匹配包(名称, `{name, version}`,或上游)和巢; `inResource(url, [handlers])` 将资源处理器扩展到一个峡谷.
-   **明确修正** (单位:千美元)`packageJson` 页:1 `ensureDependency(deps)` 使包在给定的版本中声明每个依赖性(添加缺失的,调整不匹配的,从不增加包本身); `renamePackage(from, to)` 修补一个字形显示的名称.
-   **资源修正** (单位:千美元)`fhirResource` 页:1 `replaceText(from, to)` 替换整个串行体的字符串(typo'd Canonics,错误的参考目标,无法使用的 ValueSet 绑定值——范围!); `ensureCodes(url, codes)` 在不触及现有概念的情况下,将缺少的代码附加到代码系统中; `patchElement(elementId, (element) => element)` 重写一个结构定义要素(snapshot and difference)——例如拓宽或缩小其参考目标;以 `inResource(url, [...])`。 。 。 .
-   **索引修正** (单位:千美元)`indexEntry` 页:1 `excludeCanonical({package?, url, reason})` 从索引中去掉条条(产出) _财务报告和审定财务报表_ 将理由记录在 `report()`。 。 。 .
-   **接线** —— 说 `applyPatches`, (中文(简体) ), `matchPackage`。 。 。 .

譬如说, `excludeCanonical` 丢弃条条形体( 例如, R4 扩展名, 引用 R5 唯一类型) :

```typescript
import { CanonicalManager } from "@atomic-ehr/fhir-canonical-manager";
import { excludeCanonical } from "@atomic-ehr/fhir-canonical-manager/patch";

const manager = CanonicalManager({
    packages: ["hl7.fhir.uv.extensions.r4"],
    workingDir: "./fhir-packages",
    patches: {
        indexEntry: [
            excludeCanonical({
                url: "http://hl7.org/fhir/StructureDefinition/specimen-additive",
                reason: "Uses CodeableReference, not available in R4",
            }),
        ],
    },
});
```

> **缓存符 :** 上盘索引记录了包船的内容,所以管理者使用 不同 `patches` 可共享工作目录.
> 
> -   `indexEntry` 财务报告和审定财务报表 `fhirResource` 运行每个负载和每个读数——自由更改它们.
> -   `packageJson` 也在安装和扫描时间运行,并且是缓存软件包的一部分 元数据,所以改变它仍然需要 `dropCache: true` (或经清理的工作目录).

#### `report()` - 你为什么看见你看到的

```typescript
const report = manager.report(); // ReportEntry[]
//   { kind: "index-recovery"; package; reason; recovered }
//   | { kind: "exclusion"; package; url; reason }
//   | { kind: "deprecation"; message }
```

返回每个缺陷处理行动的记录(索引回收、排除、, 被贬损通知),因此下游工具可以解释一个犬科动物之所以缺失或被改变的原因.

> **缓存运行提醒 :** `exclusion` 每次运行、缓存或不记录条目,因为 页:1 `indexEntry` 相位运行在每个负载. `index-recovery` 条目仅在 **大楼** 索引,所以一个缓存的运行报告 对他们来说什么都没有——使用 `dropCache: true` 改为 如果您需要了解为什么一个软件包的索引被修复,则重建.

### `init(): Promise<void>`

初始化管理器 。 这种方法 :

-   确保工作目录存在
-   创建 `.fcm/cache` 目录
-   检查已存在的缓存
-   如果没有缓存:安装软件包并构建索引
-   如果缓存存在: 从磁盘装入( 快速启动)

```typescript
await manager.init();
```

### `resolve(url, options?): Promise<Resource>`

直接向 FHIR 资源解析 Canonic URL .

```typescript
// Simple resolution
const patient = await manager.resolve(
    'http://hl7.org/fhir/StructureDefinition/Patient'
);

// With package constraint
const patient = await manager.resolve(
    'http://hl7.org/fhir/StructureDefinition/Patient',
    { package: 'hl7.fhir.r4.core' }
);

// With version constraint
const patient = await manager.resolve(
    'http://hl7.org/fhir/StructureDefinition/Patient',
    { version: '4.0.1' }
);
```

### `resolveEntry(url, options?): Promise<IndexEntry>`

将条形URL确定为索引条目(只有元数据).

```typescript
const entry = await manager.resolveEntry(
    'http://hl7.org/fhir/StructureDefinition/Patient'
);

console.log(entry);
// {
//   id: "opaque-reference-id",
//   resourceType: "StructureDefinition",
//   url: "http://hl7.org/fhir/StructureDefinition/Patient",
//   version: "4.0.1",
//   kind: "resource",
//   type: "Patient",
//   package: { name: "hl7.fhir.r4.core", version: "4.0.1" }
// }
```

### `read(reference): Promise<Resource>`

使用其引用读取资源.

```typescript
const entry = await manager.resolveEntry(url);
const resource = await manager.read(entry);
```

### `search(params): Promise<Resource[]>`

搜索并返回全部资源匹配标准 .

```typescript
// Get all StructureDefinitions
const structures = await manager.search({
    type: 'StructureDefinition'
});

// Get all resources of kind "resource"
const resources = await manager.search({
    kind: 'resource'
});

// Complex search
const valuesets = await manager.search({
    type: 'ValueSet',
    package: { name: 'hl7.fhir.r4.core', version: '4.0.1' }
});
```

### `searchEntries(params): Promise<IndexEntry[]>`

搜索并返回索引条目(仅元数据).

```typescript
// Find all CodeSystems
const entries = await manager.searchEntries({
    type: 'CodeSystem'
});

// Find by URL
const entries = await manager.searchEntries({
    url: 'http://hl7.org/fhir/StructureDefinition/Patient'
});
```

搜索参数 :

-   `kind?: string` - 资源类型(例如“资源”、“数据类型”、“原始类型”)
-   `url?: string` - Canonical URL(精确匹配)
-   `type?: string` - 资源类型(例如“定义”、“价值”)
-   `version?: string` - 资源版本
-   `package?: PackageId` - 按软件包名称和版本过滤

### `packages(): Promise<PackageId[]>`

列出所有已装入的软件包.

```typescript
const packages = await manager.packages();
// [
//   { name: "hl7.fhir.r4.core", version: "4.0.1" },
//   { name: "hl7.fhir.us.core", version: "5.0.1" }
// ]
```

### `addPackages(packages: string[]): Promise<void>`

运行时添加(并在需要时安装)额外的FHIR包.

```typescript
await manager.addPackages(
    "hl7.fhir.us.core@5.0.1",
    "hl7.fhir.us.davinci-drug-formulary"
);
```

-   接受一个或多个包指定符: 名称或名称@ version
-   如果管理器尚未启用, 则会附加并正常 `init()` 安装流程控点
-   已显示的软件包被跳过( 专有)
-   安装了新的, `node_modules` 重新扫描,缓存持续
-   资源立即提供给 `resolve`, (中文(简体) ), `search`, CLI 命令

回返情况: `Promise<void>` (索引更新时的解析)

### `getSearchParametersForResource(resourceType): Promise<SearchParameter[]>`

获取适用于特定 FHIR 资源类型的所有搜索参数.

```typescript
// Get search parameters for Patient resource
const searchParams = await manager.getSearchParametersForResource('Patient');

// Each parameter contains FHIR SearchParameter fields
searchParams.forEach(param => {
    console.log(`${param.code}: ${param.type} - ${param.expression}`);
});

// Example output:
// identifier: token - Patient.identifier
// name: string - Patient.name
// birthdate: date - Patient.birthDate
// gender: token - Patient.gender
```

返回所有FHIR字段保存的搜索参数阵列资源,包括:

-   `url`: 搜索参数的分类 URL
-   `code`: 查询中使用的搜索参数名称
-   `type`: 参数类型(指针、字符串、日期、参考等)
-   `expression`: FHIRPath 表达式
-   `base`: 该参数适用于资源类型的矩阵
-   额外的 FHIR 搜索参数字段

### `destroy(): Promise<void>`

清理资源并清除内存的缓存(磁盘缓存持续存在).

```typescript
await manager.destroy();
```

## CLI 参考

这个 `fcm` 命令行接口提供了全面的FHIR资源管理能力.

### 命令概览

| 命令 | 说明 |
| --- | --- |
| `fcm init [packages...]` | 在当前目录中初始化 FHIR 包 |
| `fcm list [package]` | 列表软件包或资源 |
| `fcm search [terms...]` | 使用高级过滤器搜索资源 |
| `fcm resolve <url>` | 按犬类 URL 获取资源 |
| `fcm searchparam <resourceType>` | 显示资源类型的搜索参数 |

### 全球选项

-   `--help`, (中文(简体) ), `-h` - 显示帮助信息
-   `--version`, (中文(简体) ), `-v` - 显示版本编号
-   `--json` - 作为JSON的产出结果(可供列表、搜索、解析)

### 搜索选项

| 选项 | 说明 | 示例 |
| --- | --- | --- |
| `-sd` | 过滤到结构定义 | `fcm search -sd` |
| `-cs` | 过滤到代码系统 | `fcm search -cs` |
| `-vs` | 过滤到值Sets | `fcm search -vs` |
| `-t <type>` | 按类型字段过滤 | `fcm search -t Extension` |
| `-k <kind>` | 按类型字段过滤 | `fcm search -k resource` |
| `--type <resourceType>` | 通过资源过滤Type | `fcm search --type ValueSet` |
| `--package <name>` | 按软件包过滤 | `fcm search --package hl7.fhir.us.core` |

### 前缀搜索

搜索命令支持智能前缀匹配. 当您提供多个空间分隔术语时, 每个术语会被匹配为 URL 组件的前缀 :

```bash
# Search for "str" AND "def" AND "pat" as prefixes
fcm search str def pat

# This matches URLs like:
# - http://hl7.org/fhir/StructureDefinition/Patient
# - http://hl7.org/fhir/StructureDefinition/PatientContact
```

### 过滤组合

过滤器可以合并进行精确的搜索 :

```bash
# Find all Extension complex types
fcm search -t Extension -k complex-type

# Find Patient-related Extensions
fcm search -sd pat -t Extension

# Find all primitive types in US Core
fcm search -k primitive-type --package hl7.fhir.us.core
```

### 输出格式

**默认( 单行) :**

```
http://hl7.org/fhir/StructureDefinition/Patient, {"resourceType":"StructureDefinition","kind":"resource","type":"Patient"}
```

**JSON 格式 :**

```bash
fcm search Patient --json
```

返回完整的索引 Entry 对象为 JSON 阵列.

## 目录结构

初始化后,您的工作目录将包含:

```
workingDir/
├── package.json          # NPM package file
├── node_modules/         # Installed FHIR packages
│   ├── hl7.fhir.r4.core/
│   │   ├── package.json
│   │   ├── .index.json   # FHIR resource index
│   │   └── *.json        # FHIR resources
│   └── .../
└── .fcm/
    └── cache/
        └── index.json    # Cached index for fast startup
```

## 缓存格式

缓存作为JSON文件被存储,其结构如下:

```typescript
{
  entries: {
    "http://hl7.org/fhir/StructureDefinition/Patient": [
      {
        id: "hash-based-id",
        resourceType: "StructureDefinition",
        url: "http://hl7.org/fhir/StructureDefinition/Patient",
        version: "4.0.1",
        kind: "resource",
        type: "Patient",
        package: { name: "hl7.fhir.r4.core", version: "4.0.1" }
      }
    ]
  },
  packages: {
    "hl7.fhir.r4.core": {
      id: { name: "hl7.fhir.r4.core", version: "4.0.1" },
      path: "/path/to/node_modules/hl7.fhir.r4.core",
      canonical: "http://hl7.org/fhir",
      fhirVersions: ["4.0.1"]
    }
  },
  references: {
    "hash-based-id": {
      packageName: "hl7.fhir.r4.core",
      packageVersion: "4.0.1",
      filePath: "/path/to/resource.json",
      resourceType: "StructureDefinition",
      url: "http://hl7.org/fhir/StructureDefinition/Patient",
      version: "4.0.1"
    }
  }
}
```

## 高级使用

### 使用多个软件包

```typescript
const manager = CanonicalManager({
    packages: [
        "hl7.fhir.r4.core",
        "hl7.fhir.us.core@5.0.1",
        "hl7.fhir.us.davinci-drug-formulary"
    ],
    workingDir: "./fhir-packages"
});

await manager.init();

// Search across all packages
const allValueSets = await manager.search({ type: 'ValueSet' });

// Search in specific package
const usCoreProfiles = await manager.search({
    type: 'StructureDefinition',
    package: { name: 'hl7.fhir.us.core', version: '5.0.1' }
});
```

### 自定义注册配置

```typescript
// Use the default FHIR package registry
const manager = CanonicalManager({
    packages: ["hl7.fhir.r4.core"],
    workingDir: "./fhir-packages",
    registry: "https://fs.get-ig.org/pkgs/"
});

// Use a custom NPM registry
const manager = CanonicalManager({
    packages: ["hl7.fhir.r4.core"],
    workingDir: "./fhir-packages",
    registry: "https://my-private-registry.com"
});
```

### 建造 FHIR 验证器

```typescript
async function validateResource(resource: any, manager: CanonicalManager) {
    // Get the profile URL from the resource
    const profileUrl = resource.meta?.profile?.[0];
    if (!profileUrl) {
        throw new Error('No profile specified');
    }

    // Resolve the StructureDefinition
    const profile = await manager.resolve(profileUrl);

    // Validate resource against profile
    // ... validation logic ...
}
```

### 分析软件包依赖性

```typescript
async function analyzeValueSetDependencies(manager: CanonicalManager) {
    // Get all ValueSets
    const valueSets = await manager.search({ type: 'ValueSet' });

    const dependencies = new Map<string, Set<string>>();

    for (const vs of valueSets) {
        const vsPackage = vs.package?.name || 'unknown';

        // Check compose.include for external code systems
        if (vs.compose?.include) {
            for (const include of vs.compose.include) {
                if (include.system) {
                    try {
                        const cs = await manager.resolve(include.system);
                        const csPackage = cs.package?.name || 'unknown';

                        if (csPackage !== vsPackage) {
                            if (!dependencies.has(vsPackage)) {
                                dependencies.set(vsPackage, new Set());
                            }
                            dependencies.get(vsPackage)!.add(csPackage);
                        }
                    } catch {
                        // External code system not in our packages
                    }
                }
            }
        }
    }

    return dependencies;
}
```

## 业绩考量

### 启动性能

-   **首发**: 由于软件包安装和索引构建而放慢
-   **随后运行**: 从磁盘缓存加载快速启动
-   **缓存无效**: 删除 `.fcm/cache` 强制重建

### 内存使用

-   所有索引条目都保留在内存,以快速查找
-   资源内容按需加载
-   对于大型软件包,请考虑内存要求

### 最佳做法

1.  **重用管理器实例**: 创建一次, 使用多次
2.  **使用 `searchEntries()` 元数据**: 比 `search()` 当你不需要全部资源时
3.  **指定软件包限制**: 当知道软件包时更快的解析度
4.  **缓存工作目录**: 应用程序实例之间的共享

## 处理错误

管理器丢出错误 :

-   未初始化:呼叫 `init()` 采用其他方法之前
-   找不到资源 : Canonical URL 不存在
-   无效的引用: 引用ID无效
-   软件包安装失败:网络或登记问题

```typescript
try {
    const resource = await manager.resolve('http://invalid.url/Resource');
} catch (error) {
    console.error('Failed to resolve:', error.message);
}
```

## 类型脚本

```typescript
interface Reference {
    id: string;              // Opaque identifier
    resourceType: string;    // FHIR resource type
}

interface PackageId {
    name: string;           // Package name
    version: string;        // Package version
}

interface IndexEntry extends Reference {
    indexVersion: number;   // Index format version
    kind?: string;         // resource, datatype, primitive, etc.
    url?: string;          // Canonical URL
    type?: string;         // Specific type (e.g., "Patient")
    version?: string;      // Resource version
    package?: PackageId;   // Source package
}

interface Resource extends Reference {
    url?: string;          // Canonical URL
    version?: string;      // Resource version
    [key: string]: any;    // Other FHIR properties
}

interface SourceContext {
    id?: string;
    package?: PackageId;
    url?: string;
    path?: string;
}
```

## 发展

要安装依赖性 :

```bash
bun install
```

进行测试:

```bash
bun test
```

举例来说:

```bash
bun run example.ts
```

### 项目结构

```
fhir-canonical-manager/
├── src/
│   ├── index.ts          # Core library implementation
│   ├── compat.ts         # Bun/Node.js compatibility layer
│   └── cli/              # CLI implementation
│       ├── index.ts      # CLI entry point
│       ├── init.ts       # Init command
│       ├── list.ts       # List command
│       ├── search.ts     # Search command
│       └── resolve.ts    # Resolve command
├── test/
│   ├── index.test.ts     # Core library tests
│   ├── cli.test.ts       # CLI unit tests
│   └── cli-integration.test.ts # CLI integration tests
├── dist/                 # Compiled output (generated)
├── example.ts            # Usage example
├── package.json
├── tsconfig.json
└── README.md
```

## 所需资源

-   节点.js 18+或 Bun 1.0+
-   类型脚本 5.0+
-   软件包安装的网络访问

## 许可证

麻省理工学院

## 捐款

欢迎捐款! 请随意提交拉力请求.

### 发展指导方针

1.  单一文件中的所有代码 : `src/index.ts`
2.  功能编程风格
3.  除Node.js内建外,没有外部依赖关系
4.  综合测试 `test/index.test.ts`
5.  用 API 修改更新 README.md

## 常见问题

### @atomic-ehr/fhir-canonical-manager 是什么？

\[\!\]\[npm版本\] \(https://img\.shields\.io/npm/v/@原子-ehr/fhir-canonical-man\) \(中文\(简体\) \)

### 如何安装 @atomic-ehr/fhir-canonical-manager？

在项目目录运行 npm install @atomic-ehr/fhir-canonical-manager，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：typescript（^5）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。它还提供命令行工具 fcm，可以用 npx fcm 直接运行。

### @atomic-ehr/fhir-canonical-manager 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @atomic-ehr/fhir-canonical-manager 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @atomic-ehr/fhir-canonical-manager 可以商用吗？

@atomic-ehr/fhir-canonical-manager 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @atomic-ehr/fhir-canonical-manager 的下载量有多少？

根据 npm 官方下载统计，@atomic-ehr/fhir-canonical-manager 在 2026/10/07 – 2026/11/05 这 30 天内被下载 9,350 次，日均约 312 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @atomic-ehr/fhir-canonical-manager 还在维护吗？

最新版本 0\.0\.29 发布于 2026/10/14（24 天前）；至今共发布 98 个版本，其中过去 12 个月发布了 69 个；首次发布于 2025/07/31。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

