Skip to content

Conversation

@rvlb
Copy link
Contributor

@rvlb rvlb commented Nov 28, 2025

Summary by Sourcery

Add support for building a Directory instance from the hosted VCI snapshot and extend tests to cover snapshot fetching and error handling.

New Features:

  • Introduce Directory.fromVCI to construct a Directory from the published VCI snapshot JSON.

Tests:

  • Add tests that validate Directory.fromVCI builds a directory from a mocked VCI snapshot and throws on failed fetch responses.
  • Refactor directory tests to reuse shared sample JSON and assertions for both fromJSON and fromVCI paths.

Closes #4

@sourcery-ai
Copy link

sourcery-ai bot commented Nov 28, 2025

Reviewer's Guide

Adds a new Directory.fromVCI helper that builds a Directory from the published VCI snapshot JSON, and extends tests to cover VCI fetching behavior while refactoring shared directory test data into a reusable fixture-style helper.

Sequence diagram for Directory.fromVCI VCI snapshot download flow

sequenceDiagram
  actor Caller
  participant Directory
  participant FetchAPI
  participant VciSnapshotService

  Caller->>Directory: fromVCI()
  Directory->>FetchAPI: fetch(vci_snapshot_url)
  FetchAPI->>VciSnapshotService: HTTP GET /vci_snapshot.json
  VciSnapshotService-->>FetchAPI: HTTP response

  alt response status ok
    FetchAPI-->>Directory: JSON body
    Directory->>Directory: fromJSON(vciDirectoryJson)
    Directory-->>Caller: Directory instance
  else response status not ok
    FetchAPI-->>Directory: non ok response
    Directory-->>Caller: Error
  end
Loading

Class diagram for Directory with new fromVCI helper

classDiagram
  class Directory {
    - issuerInfo
    + getIssuerInfo()
    + static fromJSON(directoryJson)
    + static fromVCI() Promise_Directory
  }
Loading

File-Level Changes

Change Details Files
Add Directory.fromVCI static method to construct a directory from the VCI snapshot hosted by The Commons Project.
  • Introduce an async static fromVCI method on Directory that fetches the VCI snapshot JSON from the vci-directory GitHub repository using fetch
  • Validate the HTTP response, throwing a descriptive Error when response.ok is false and including the HTTP status code in the message
  • Parse the response JSON and delegate construction to the existing Directory.fromJSON factory
src/shc/directory.ts
Extend and refactor Directory tests to cover VCI snapshot fetching and reuse common sample directory JSON assertions.
  • Extract the inline directory JSON used in tests into a shared SAMPLE_DIRECTORY_JSON constant for reuse
  • Add an assertDirectoryFromSampleJson helper that encapsulates common expectations for issuer counts, keys, and CRLs
  • Add a test that stubs global fetch to return SAMPLE_DIRECTORY_JSON for the VCI snapshot URL and verifies Directory.fromVCI builds the expected Directory
  • Add a test that stubs global fetch to simulate a non-OK VCI snapshot response and asserts Directory.fromVCI throws with the expected error message
  • Update the existing 'should create a directory from JSON' test to use SAMPLE_DIRECTORY_JSON and the new assertion helper
test/shc/directory.test.ts

Possibly linked issues

  • #N/A: PR adds Directory.fromVCI that downloads the official VCI snapshot JSON, directly implementing requested VCI Directory support.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions
Copy link

github-actions bot commented Nov 28, 2025

Coverage Report

Status Category Percentage Covered / Total
🔵 Lines 95.9% 1943 / 2026
🔵 Statements 95.9% 1943 / 2026
🔵 Functions 98.5% 132 / 134
🔵 Branches 90.23% 610 / 676
File Coverage
File Stmts Branches Functions Lines Uncovered Lines
Changed Files
src/shc/directory.ts 100% 100% 100% 100%
Generated in workflow #108 for commit efab59b by the Vitest Coverage Report Action

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • In the tests that monkey-patch globalThis.fetch, consider wrapping the override in a try/finally (or using an afterEach hook) to ensure fetch is always restored even if the test fails, rather than relying on manual reassignment at the end of each test.
  • You may want to make the VCI snapshot URL configurable (e.g., an optional parameter to fromVCI or a constant exported from the module), which would improve flexibility for different environments and simplify testing without hardcoding the URL in the method.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the tests that monkey-patch `globalThis.fetch`, consider wrapping the override in a `try/finally` (or using an `afterEach` hook) to ensure `fetch` is always restored even if the test fails, rather than relying on manual reassignment at the end of each test.
- You may want to make the VCI snapshot URL configurable (e.g., an optional parameter to `fromVCI` or a constant exported from the module), which would improve flexibility for different environments and simplify testing without hardcoding the URL in the method.

## Individual Comments

### Comment 1
<location> `src/shc/directory.ts:44-45` </location>
<code_context>
+   * const directory = await Directory.fromVCI()
+   */
+  static async fromVCI(): Promise<Directory> {
+    const vciSnapshotResponse = await fetch(
+      'https://raw.githubusercontent.com/the-commons-project/vci-directory/main/logs/vci_snapshot.json'
+    )
+    if (!vciSnapshotResponse.ok) {
</code_context>

<issue_to_address>
**suggestion:** The hard-coded VCI snapshot URL reduces flexibility and testability.

Inlining the snapshot URL makes it harder to adapt if the endpoint changes, to point to other environments (staging/mirror), or to override in tests. Please extract this URL into a constant, configuration value, or optional parameter so callers can override it without code changes.

Suggested implementation:

```typescript
  /**
   * This helper fetches a well-known VCI snapshot JSON file and delegates to
   * `Directory.fromJSON` to produce a `Directory` instance. If the snapshot
   * cannot be retrieved (non-2xx response) the function throws an Error.
   *
   * @param snapshotUrl Optional URL to the VCI snapshot JSON. Defaults to the
   *   public GitHub-hosted snapshot but can be overridden for alternative
   *   environments or tests.
   * @returns A {@link Directory} populated from the VCI snapshot
   * @throws Error when the VCI snapshot HTTP fetch returns a non-OK status
   * @example
   * const directory = await Directory.fromVCI()
   * @example
   * const directory = await Directory.fromVCI('https://staging.example.com/vci_snapshot.json')
   */
  static async fromVCI(
    snapshotUrl: string = 'https://raw.githubusercontent.com/the-commons-project/vci-directory/main/logs/vci_snapshot.json'
  ): Promise<Directory> {
    const vciSnapshotResponse = await fetch(snapshotUrl)

```

```typescript
    if (!vciSnapshotResponse.ok) {
      throw new Error(
        `Failed to fetch VCI Directory snapshot with status ${vciSnapshotResponse.status}`
      )
    }
    const vciDirectoryJson = await vciSnapshotResponse.json()
    return Directory.fromJSON(vciDirectoryJson)
  }

```

If there are existing tests or call sites that rely on `Directory.fromVCI()` without parameters, they will continue to work unchanged because the new `snapshotUrl` parameter has a default value. You may optionally:
1. Add new tests that call `Directory.fromVCI(customUrl)` to verify behavior against alternate endpoints.
2. If your project prefers centralized configuration over default parameters, you could also introduce a shared `DEFAULT_VCI_SNAPSHOT_URL` constant and reuse it in this method and elsewhere.
</issue_to_address>

### Comment 2
<location> `test/shc/directory.test.ts:113-122` </location>
<code_context>
+  it('should create a directory from the VCI snapshot', async () => {
</code_context>

<issue_to_address>
**suggestion (testing):** Add assertions that `Directory.fromVCI` calls `fetch` with the expected snapshot URL

This test only checks the happy-path behavior with the mocked response body; it doesn’t verify that `Directory.fromVCI` calls `fetch` with the correct snapshot URL or that it’s called once. To make the test more robust against URL or call-pattern regressions, add expectations like:

```ts
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(fetchMock).toHaveBeenCalledWith(
  'https://raw.githubusercontent.com/the-commons-project/vci-directory/main/logs/vci_snapshot.json'
)
```

Suggested implementation:

```typescript
  it('should create a directory from the VCI snapshot', async () => {
    const originalFetch = globalThis.fetch
    const fetchMock = vi.fn().mockImplementation((url: string) => {
      if (
        url ===
        'https://raw.githubusercontent.com/the-commons-project/vci-directory/main/logs/vci_snapshot.json'
      ) {
        return Promise.resolve({
          ok: true,
          json: async () => SAMPLE_DIRECTORY_JSON,
        })
      }

      return Promise.resolve({ ok: false, status: 404 })

```

To fully implement your suggestion, you should also, within this same test:
1. Assign the mock to `globalThis.fetch` before invoking the code under test:
   ```ts
   globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
   ```
2. After the `await Directory.fromVCI()` (or equivalent call), add:
   ```ts
   expect(fetchMock).toHaveBeenCalledTimes(1)
   expect(fetchMock).toHaveBeenCalledWith(
     'https://raw.githubusercontent.com/the-commons-project/vci-directory/main/logs/vci_snapshot.json'
   )
   ```
3. Restore `globalThis.fetch` to `originalFetch` at the end of the test (if not already done) to avoid leaking the mock into other tests:
   ```ts
   globalThis.fetch = originalFetch
   ```
These additions will ensure the test asserts both the exact URL used for the VCI snapshot and that `fetch` is called exactly once.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@vercel
Copy link

vercel bot commented Nov 28, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
medplum-shl Ready Ready Preview Comment Dec 5, 2025 7:03pm

@rvlb rvlb requested a review from fjsj November 28, 2025 19:40
Copy link
Member

@fjsj fjsj left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check comment

@rvlb rvlb merged commit 52246c9 into main Dec 5, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SHC VCI Directory support

3 participants