npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

segmenthl7tools

v1.0.11

Published

Ferramentas para manipulação de segmentos HL7

Readme

segmentHL7Tools


Sumário


Instalação

npm install segmenthl7tools
yarn add segmenthl7tools
pnpm add segmenthl7tools

Requer Node.js >= 20. Compatível com ES Modules e CommonJS.


Início Rápido

import {
  parseHL7Segment,
  createHL7Segment,
  validateHL7Segment,
  extractFieldValue,
  setFieldValue,
} from 'segmenthl7tools'

// Parsear um segmento
const parsed = parseHL7Segment('PID|1|12345|SMITH^JOHN|19800101|M')
console.log(parsed.segmentType) // "PID"
console.log(parsed.field3)      // "SMITH^JOHN"

// Criar um segmento
const segment = createHL7Segment('PID', ['1', '12345', 'SMITH^JOHN'])
console.log(segment) // "PID|1|12345|SMITH^JOHN"

// Validar
console.log(validateHL7Segment('MSH|^~\\&|APP|FAC')) // true
console.log(validateHL7Segment(''))                    // false

// Extrair campo
console.log(extractFieldValue('PID|1|12345', 2)) // "12345"
console.log(extractFieldValue('PID|1|12345', 9)) // null

// Modificar campo
console.log(setFieldValue('PID|1|12345|SMITH^JOHN', 2, '99999'))
// "PID|1|99999|SMITH^JOHN"

API

parseHL7Segment

parseHL7Segment(segment: string): ParsedHL7Segment

Parseia um segmento HL7 e retorna um objeto com segmentType e os campos indexados como field1, field2, ..., fieldN.

const result = parseHL7Segment(
  'MSH|^~\\&|SENDING_APP|SENDING_FAC||RECEIVING_FAC|20231201||ADT^A01|MSG001|P|2.5'
)

result.segmentType // "MSH"
result.field1      // "^~\\&"
result.field8      // "ADT^A01"
result.field11     // "2.5"

Lança Error se o argumento não for uma string válida.


createHL7Segment

createHL7Segment(segmentType: string, fields: string[]): string

Cria uma string de segmento HL7 a partir do tipo e de um array de campos.

createHL7Segment('PID', ['1', '12345', 'SMITH^JOHN', '19800101', 'M'])
// "PID|1|12345|SMITH^JOHN|19800101|M"

// Campos vazios intermediários são preservados
createHL7Segment('PID', ['1', '', 'SMITH^JOHN'])
// "PID|1||SMITH^JOHN"

// Array vazio retorna apenas o tipo
createHL7Segment('EVN', [])
// "EVN"

Lança Error se segmentType for inválido ou fields não for um array.


validateHL7Segment

validateHL7Segment(segment: string): boolean

Valida se uma string é um segmento HL7 bem formado. O tipo do segmento deve ter exatamente 3 caracteres alfanuméricos maiúsculos (/^[A-Z0-9]{3}$/).

| Entrada | Resultado | Motivo | |---|---|---| | "MSH\|^~\\&\|APP\|FAC" | true | Tipo válido | | "PID\|1\|12345" | true | Tipo válido | | "" | false | String vazia | | "\|APP\|FAC" | false | Sem tipo | | "AB\|campo" | false | Tipo com 2 chars | | "MSSH\|campo" | false | Tipo com 4 chars | | "pid\|campo" | false | Tipo em minúsculas |


extractFieldValue

extractFieldValue(segment: string, fieldIndex: number): string | null

Extrai o valor de um campo pelo índice (0-based, onde 0 é o segmentType).

  • Retorna '' para campos que existem mas estão vazios
  • Retorna null para índices além do range ou segmento inválido
const seg = 'PID|1|12345|SMITH^JOHN||M'

extractFieldValue(seg, 0)  // "PID"
extractFieldValue(seg, 3)  // "SMITH^JOHN"
extractFieldValue(seg, 4)  // "" — campo vazio
extractFieldValue(seg, 9)  // null — fora do range
extractFieldValue('', 0)   // null — segmento inválido

setFieldValue

setFieldValue(segment: string, fieldIndex: number, value: string): string

Define o valor de um campo específico. Preenche campos intermediários com '' automaticamente se o índice estiver além do tamanho atual do segmento.

setFieldValue('PID|1|12345|SMITH^JOHN', 2, '99999')
// "PID|1|99999|SMITH^JOHN"

// Cria campos vazios intermediários se necessário
setFieldValue('PID|1|12345', 5, 'M')
// "PID|1|12345|||M"

// Altera o tipo do segmento (índice 0)
setFieldValue('PID|1|12345', 0, 'NK1')
// "NK1|1|12345"

Lança Error se o segmento for inválido ou o índice for negativo.


Tipos

import type { HL7Segment, ParsedHL7Segment } from 'segmenthl7tools'
/** Estrutura para representar um segmento HL7 */
interface HL7Segment {
  segmentType: string
  fields: string[]
}

/** Retorno de parseHL7Segment */
interface ParsedHL7Segment {
  segmentType: string
  [key: string]: string // field1, field2, ...fieldN
}

Desenvolvimento

Pré-requisitos

  • Node.js >= 20
  • npm

Setup

git clone https://github.com/igorceranto/segmentHL7Tools.git
cd segmentHL7Tools
npm install

Scripts

| Comando | Descrição | |---|---| | npm run build | Build CJS + ESM + tipos | | npm run dev | Watch mode | | npm test | Rodar testes | | npm run test:ui | Testes com UI interativa | | npm run test:coverage | Testes com relatório de cobertura | | npm run type-check | Verificação de tipos TypeScript | | npm run biome:format | Formatar código | | npm run biome:lint | Linting | | npm run biome:check | Lint + format juntos | | npm run release | Criar e publicar release |

Estrutura

src/
├── __tests__/
│   ├── field-operations.test.ts
│   ├── parser.test.ts
│   └── validation.test.ts
├── functions/
│   ├── field-operations.ts
│   ├── index.ts
│   ├── parser.ts
│   └── validation.ts
├── types/
│   ├── hl7.ts
│   └── index.ts
└── index.ts

Qualidade

O projeto usa automações para garantir a qualidade do código:

  • Biome — linting e formatação
  • Vitest — testes com threshold de cobertura em 80%
  • TypeScript strict — verificação estática de tipos
  • Husky — hooks de pre-commit e pre-push
  • GitHub Actions — CI/CD em cada push e release

Contribuição

Contribuições são bem-vindas!

  1. Faça um fork do projeto
  2. Crie sua branch (git checkout -b feature/minha-feature)
  3. Faça commit das mudanças (git commit -m 'feat: adiciona minha feature')
  4. Push para a branch (git push origin feature/minha-feature)
  5. Abra um Pull Request

Bugs e sugestões via Issues.


Licença

MIT © ICeranto