洪 民憙 (Hong Minhee) :nonbinary:'s avatar

洪 民憙 (Hong Minhee) :nonbinary:

@hongminhee@hollo.social

1,107 following1,898 followers

An intersectionalist, feminist, and socialist living in Seoul (UTC+09:00). @tokolovesme's spouse. Who's behind @fedify, @hollo, and @botkit. Write some free software in , , , & . They/them.

서울에 사는 交叉女性主義者이자 社會主義者. 金剛兔(@tokolovesme)의 配偶者. @fedify, @hollo, @botkit 메인테이너. , , , 等으로 自由 소프트웨어 만듦.

()

Pinned

@hongminhee@hollo.social

Hello! I'm Hong Minhee (洪 民憙), an open source software engineer in my late 30s, living in Seoul, Korea. I'm bisexual and non-binary (they/them), and an enthusiastic advocate of free/open source software and the fediverse.

I work full-time on @fedify, an ActivityPub server framework in TypeScript, funded by @sovtechfund. I'm also the creator of @hollo, a single-user ActivityPub microblog; @botkit, an ActivityPub bot framework; Hackers' Pub, a fediverse platform for software developers; and LogTape, a logging library for JavaScript and TypeScript.

I have a long interest in East Asian languages (CJK) and Unicode. I post mostly in English here, though occasionally in Japanese or in mixed-script Korean (國漢文混用體), a traditional writing style that interleaves Chinese characters with the native Korean alphabet. Wanting to write in that style was actually one of the reasons I joined the fediverse. Feel free to talk to me in English, Korean, Japanese, or even Literary Chinese!

en.wikipedia.org

Korean mixed script - Wikipedia

Pinned

はじめまして!ソウル在住の30代後半のオープンソースソフトウェアエンジニア、洪 民憙ホン・ミンヒと申します。バイセクシュアル(bisexual)・ノンバイナリー(non-binary)で、自由・オープンソースソフトウェア(F/OSS)とフェディバース(fediverse)の熱烈な支持者です。

STF(@sovtechfund)の支援を受け、TypeScript用ActivityPubサーバーフレームワーク「@fedify」の開発に専念しています。他にも、おひとり様向けのActivityPubマイクロブログ「@hollo」、ActivityPubボットフレームワーク「@botkit」、ソフトウェア開発者向けフェディバースプラットフォームHackers' Pub、JavaScript・TypeScript用ロギングライブラリLogTapeなどの制作者でもあります。

東アジア言語(いわゆるCJK)とUnicodeにも興味があります。このアカウントでは主に英語で投稿していますが、時々日本語や国漢文混用体(漢字ハングル混じり文)の韓国語でも書いています。実はこの文体で書きたくてフェディバースを始めた、という経緯もあります。日本語、英語、韓国語、漢文でも気軽に話しかけてください!

speakerdeck.com

国漢文混用体からHolloまで

本発表では、韓国語の「国漢文混用体」(漢字ハングル混じり文)を自分のフェディバース投稿に実装したいという小さな目標から始まった旅路を共有します。 この目標を達成するために、ActivityPubのJSON-LDの複雑さやHTTP Signatures、WebFingerなどの仕様を理解する必要性に…

Pinned

安寧(안녕)하세요! 저는 서울에 살고 있는 30() 後半(후반)의 오픈 소스 소프트웨어 엔지니어 洪民憙(홍민희)입니다. 兩性愛者(양성애자)(bisexual)이자 논바이너리(non-binary)이며, 自由(자유)·오픈 소스 소프트웨어(F/OSS)와 聯合宇宙(연합우주)(fediverse)의 熱烈(열렬)支持者(지지자)이기도 합니다.

STF(@sovtechfund)의 支援(지원)을 받아 TypeScript() ActivityPub 서버 프레임워크 @fedify 開發(개발)專業(전업)으로 ()하고 있습니다. 그 ()에도 싱글 유저() ActivityPub 마이크로블로그 @hollo, ActivityPub 봇 프레임워크 @botkit, 소프트웨어 開發者(개발자)를 위한 聯合宇宙(연합우주) 플랫폼 Hackers' Pub, JavaScript·TypeScript() 로깅 라이브러리 LogTape ()製作者(제작자)이기도 합니다.

()아시아 言語(언어)(이른바 CJK)와 Unicode에도 關心(관심)이 많습니다. 이 計定(계정)에서는 ()英語(영어)로 포스팅하지만, 때때로 日本語(일본어)國漢文混用體(국한문 혼용체) 韓國語(한국어)로도 씁니다. 聯合宇宙(연합우주)에 오게 된 動機(동기) () 하나가 바로 國漢文混用體(국한문 혼용체)로 글을 쓰고 싶었기 때문이기도 하고요. 韓國語(한국어), 英語(영어), 日本語(일본어), 아니면 漢文(한문)으로도 말을 걸어주세요!

logtape.org

LogTape

Unobtrusive logging library with zero dependencies—library-first design for Deno, Node.js, Bun, browsers, and edge functions

@renchap@oisaur.com

Coming soon on your Mastodon server… The long awaited quote posts, with user-control (you can chose if you want to be quoted on a per-post basis, change it later, and retract any quote of your post)

Amazing work by the team 🎉

Expect a blog post with all the details in a few weeks, support in the mobile apps, then we will enable the feature on mastodon.social, then release Mastodon 4.5

Screenshot of the Mastodon composer, showing a new visibility picker button with a "Public, anyone can quote" label
ALT text

Screenshot of the Mastodon composer, showing a new visibility picker button with a "Public, anyone can quote" label

@hongminhee@hackers.pub

投稿(Note)と記事(Article)の両方でMarkdownをサポートしているだけでなく、シンタックスハイライトとTeX数式にも対応しているという点で、[1]Hackers' Pubはフェディバースで最もソフトウェアプログラマーに適したプラットフォームであると自負しております。

そんな皆さんのために、Hackers' Pubの招待状を共有します。(笑)


  1. ちなみに、Hackers' Pubはかなり多様なMarkdown拡張構文をサポートしています。 ↩︎

@hongminhee@hackers.pub

단문(Note)과 긴 게시글(Article) 모두에서 Markdown을 지원할 뿐만 아니라 구문강조와 TeX 수식을 지원한다는 점에서 Hackers' Pub은 연합우주에서 가장 소프트웨어 프로그래머가 쓰기에 적합한 플랫폼이라고 자부합니다.

@hongminhee@hollo.social

Open source projects I'm currently maintaining:

  • Fedify, an ActivityPub server framework for TypeScript
  • Hollo, an ActivityPub-enabled single-user microblogging software
  • BotKit, an ActivityPub bot framework for TypeScript
  • LogTape, a modern logging library for TypeScript
  • Upyo, a simple and modern email sending library for TypeScript
  • Optique, a type-safe combinatorial CLI parser for TypeScript

optique.dev

Optique

Type-safe combinatorial CLI parser for TypeScript

@hongminhee@hollo.social

I've recently been working on Optique, a CLI parser combinator for TypeScript. Optique allows you to describe complex CLIs by combining smaller parts. You can also handle the CLI parsing results in a type-safe manner (see code below). The idea came from Haskell's optparse-applicative, but since TypeScript's API style is so different from Haskell's, I referenced Zod and similar libraries for the API design. For a more detailed introduction, please refer to the article I posted on Hackers' Pub!

const parser = or(
  object({
    type: constant("network"),
    host: option(
      "-h", "--host",
      string({ metavar: "HOST" }),
    ),
    port: option(
      "-p", "--port",
      integer({ metavar: "PORT", min: 0, max: 65535 }),
    ),
  }),
  object({
    type: constant("local"),
    file: option(
      "-s", "--socket-file",
      string({ metavar: "FILE" }),
    ),
  }),
)

type Result = InferValue<typeof parser>;

// The above type is inferred as:
type Result = {
    readonly type: "network";
    readonly host: string;
    readonly port: number;
} | {
    readonly type: "local";
    readonly file: string;
}
ALT text

const parser = or( object({ type: constant("network"), host: option( "-h", "--host", string({ metavar: "HOST" }), ), port: option( "-p", "--port", integer({ metavar: "PORT", min: 0, max: 65535 }), ), }), object({ type: constant("local"), file: option( "-s", "--socket-file", string({ metavar: "FILE" }), ), }), ) type Result = InferValue<typeof parser>; // The above type is inferred as: type Result = { readonly type: "network"; readonly host: string; readonly port: number; } | { readonly type: "local"; readonly file: string; }

@hongminhee@hackers.pub

최근 Optique라는 다소 실험적인 CLI 파서 라이브러리를 제작하게 되었습니다. 이 글을 쓰는 2025년 8월 21일 시점으로 아직 0.1.0도 릴리스되지 않았지만, 나름대로 재미있는 발상이라고 생각해서 이 글을 통해 소개합니다.

Optique는 크게 두 가지 다른 라이브러리로부터 영향을 받았습니다. 하나는 Haskell의 optparse-applicative라는 라이브러리인데, 이 라이브러리로부터 얻은 교훈은 CLI 파서도 파서 컴비네이터가 될 수 있고, 그렇게 만들었을 때 매우 유용하다는 사실입니다. 다른 하나는 TypeScript 사용자들에게 이미 익숙한 Zod입니다. 비록 optparse-applicative에서 아이디어의 줄기를 얻긴 했지만, Haskell과 TypeScript는 너무나 다른 언어라서 API를 구성하는 방식에 큰 차이가 있습니다. 그래서 API를 구성하는 방식에 있어서는 Zod를 비롯한 여러 유효성 검사 라이브러리를 참고하게 되었습니다.

Optique는 여러 작은 파서들과 파서 컴비네이터들을 레고 부품처럼 조립하여 CLI가 어떠한 모양이어야 하는지를 표현합니다. 예를 들어 가장 작은 부품 중 하나로는 option()이 있습니다:

const parser = option("-a", "--allow", url());

이 파서를 실행하려면 run()이라는 API를 사용하면 됩니다: (참고로 run() 함수는 암시적으로 process.argv.slice(2)를 읽습니다.)

const allow: URL = run(parser);

위 코드에서 제가 일부러 URL이라는 타입을 명시하긴 했지만, 굳이 그렇게 하지 않아도 저절로 URL 타입으로 추론됩니다. 위 파서는 -a/--allow=URL 옵션만을 받아들입니다. 다른 옵션이나 인자를 줄 경우 오류가 납니다. -a/--allow=URL 옵션이 주어지지 않아도 오류가 납니다.

만약 -a/--allow=URL 옵션을 필수가 아닌 선택으로 두려면 어떻게 해야 할까요? 그럴 때는 optional() 컴비네이터로 option() 파서를 감싸면 됩니다.

const parser = optional(option("-a", "--allow", url()));

이 파서를 실행하면 결과로 어떤 타입이 나올까요?

const allow: URL | undefined = run(parser);

네, URL | undefined 타입이 됩니다.

아니면, 아예 -a/--allow=URL 옵션을 여러 개 받을 수 있게 해봅시다. 아래처럼 쓸 수 있게요:

prog -a https://example.com/ -a https://hackers.pub/

이렇게 옵션을 여러 번 쓸 수 있게 하려면, optional() 컴비네이터 대신 multiple() 컴비네이터를 씁니다:

const parser = multiple(option("-a", "--allow", url()));

이제 슬슬 결과 타입이 어떻게 나올지 예상이 되시죠?

const allowList: readonly URL[] = run(parser);

네, readonly URL[] 타입이 됩니다.

그런데, 만약 -a/--allow=URL 옵션과는 함께 쓸 수 없는 상호배타적인 -d/--disallow=URL이라는 옵션을 추가하려면 어떻게 해야 할까요? 둘 중 한 쪽의 옵션만 동시에 쓸 수 있어야 합니다. 이럴 때는 or() 컴비네이터를 사용하면 됩니다:

const parser = or(
  multiple(option("-a", "--allow", url())),
  multiple(option("-d", "--disallow", url())),
);

이 파서는 다음과 같은 명령들은 잘 받아들입니다:

prog -a https://example.com/ --allow    https://hackers.pub/
prog -d https://example.com/ --disallow https://hackers.pub/

하지만 다음과 같이 -a/--allow=URL 옵션과 -d/--disallow=URL 옵션이 섞여있을 때는 오류를 냅니다:

prog -a https://example.com/ --disallow https://hackers.pub/

아무튼, 그럼 이 파서의 결과는 어떤 타입이 될까요?

const result: readonly URL[] = run(parser);

이런, or() 컴비네이터가 감싸는 2개의 파서 모두 readonly URL[] 타입의 값을 만들기 때문에 readonly URL[] | readonly URL[] 타입이 되어, 결과적으로 readonly URL[] 타입이 되어버렸습니다. 제대로 된 변별 공용체(discriminated union) 형식으로 바꾸고 싶군요. 아래와 같은 타입이면 좋을 것 같습니다.

const Result =
  | { mode: "allowList"; allowList: readonly URL[] }
  | { mode: "blockList"; blockList: readonly URL[] };

이렇게 객체 형태의 구조를 만들고 싶을 때는 object() 컴비네이터를 쓰면 됩니다:

const parser = or(
  object({
    mode: constant("allowList"),
    allowList: multiple(option("-a", "--allow", url())),
  }),
  object({
    mode: constant("blockList"),
    blockList: multiple(option("-d", "--disallow", url())),
  }),
);

변별자(discriminator)를 부여하기 위해 constant() 파서도 사용했습니다. 이 파서는 조금 특이한 파서인데, 아무 것도 읽지 않고 주어진 값을 만들기만 합니다. 즉, 항상 성공하는 파서입니다. 이렇게 변별 공용체를 구성할 때 주로 쓰이지만, 다른 창의적인 방식으로도 쓰일 수 있을 겁니다.

이제 이 파서는 우리가 원하는 타입의 결과 값을 만듭니다:

const result:
  | { readonly mode: "allowList"; readonly allowList: readonly URL[] }
  | { readonly mode: "blockList"; readonly blockList: readonly URL[] }
  = run(parser);

꼭 상호배타적인 옵션들에만 or() 컴비네이터나 object() 컴비네이터를 쓰는 건 아닙니다. 서브커맨드도 같은 원리로 구현할 수 있습니다. 하나의 커맨드에 매치되는 command() 파서와 순서 인자에 매치되는 argument() 파서를 소개합니다:

const parser = command(
  "download",
  object({
    targetDirectory: optional(
      option(
        "-t", "--target",
        file({ metavar: "DIR", type: "directory" })
      )
    ),
    urls: multiple(argument(url())),
  })
)

위 파서는 아래와 같은 명령에 매치됩니다:

prog download --target=out/ https://example.com/ https://example.net/

파서의 결과 타입은 다음과 같습니다:

const result: {
  readonly targetDirectory: string | undefined;
  readonly urls: readonly URL[];
} = run(parser); 

여기에 upload 서브커맨드를 추가하려면 어떻게 해야 할까요? 맞습니다, or() 컴비네이터로 엮으면 됩니다:

const parser = or(
  command(
    "download",
    object({
      action: constant("download"),
      targetDirectory: optional(
        option(
          "-t", "--target",
          file({ metavar: "DIR", type: "directory" })
        )
      ),
      urls: multiple(argument(url())),
    })
  ),
  command(
    "upload",
    object({
      action: constant("upload"),
      url: option("-d", "--dest", "--destination", url()),
      files: multiple(
        argument(file({ metavar: "FILE", type: "file" })),
        { min: 1 },
      ),
    })
  ),
);

위 파서는 이제 다음과 같은 명령들을 받아들일 수 있게 되었습니다:

prog upload ./a.txt ./b.txt -d https://example.com/
prog download -t ./out/ https://example.com/ https://hackers.pub/

이 파서의 결과 타입은 다음과 같습니다:

const result:
  | {
      readonly action: "download";
      readonly targetDirectory: string | undefined;
      readonly urls: readonly URL[];
    }
  | {
      readonly action: "upload";
      readonly url: URL;
      readonly files: readonly string[];
    }
  = run(parser); 

같은 방식을 응용하면 겹쳐진 서브커맨드(nested subcommands)도 구현할 수 있겠죠?

자, 이렇게 Optique가 CLI를 표현하는 방식을 보여드렸는데요. 어떤 것 같나요? Optique의 방식이 복잡한 CLI를 표현하기에 적합하다는 게 와닿으시나요?

물론, Optique의 방식도 완벽하지는 않습니다. 아주 전형적이고 단순한 CLI를 정의하는 데에는 오히려 더 손이 가는 것도 사실입니다. 또한, Optique는 오로지 CLI 파서의 역할만 하고 있기 때문에 일반적인 CLI 앱 프레임워크가 제공하는 다양한 기능은 제공하지 않기도 합니다. (추후 Optique에 더 많은 기능을 추가할 예정이긴 합니다만…)

그럼에도 Optique의 접근 방식에 흥미를 느끼셨다면, 소개 문서튜토리얼도 한 번 살펴보시기 바랍니다.

unstable.optique.dev

Optique tutorial: Build type-safe CLIs step by step | Optique

This tutorial walks you through building type-safe command-line applications using Optique's parser combinators, starting from simple options to complex subcommands.

最近、OptiqueというTypeScript向けのCLIパーサー「コンビネーター」を作っています。Optiqueは、複雑なCLIを小さなパーツの組み合わせで記述できる様にしてくれます。そして、そのCLIのパース結果を型安全に扱う事が出来ます。(下記のコード参照)アイデアはHaskellのoptparse-applicative から得ましたが、TypeScriptはHaskellとAPIのスタイルがかなり異なる為、APIの面ではZod等を参考にしました。詳しい紹介はHackers' Pubに投稿した記事をご覧ください!

const parser = or(
  object({
    type: constant("network"),
    host: option(
      "-h", "--host",
      string({ metavar: "HOST" }),
    ),
    port: option(
      "-p", "--port",
      integer({ metavar: "PORT", min: 0, max: 65535 }),
    ),
  }),
  object({
    type: constant("local"),
    file: option(
      "-s", "--socket-file",
      string({ metavar: "FILE" }),
    ),
  }),
)

type Result = InferValue<typeof parser>;

// Resultの推論された型
type Result = {
    readonly type: "network";
    readonly host: string;
    readonly port: number;
} | {
    readonly type: "local";
    readonly file: string;
}
ALT text

const parser = or( object({ type: constant("network"), host: option( "-h", "--host", string({ metavar: "HOST" }), ), port: option( "-p", "--port", integer({ metavar: "PORT", min: 0, max: 65535 }), ), }), object({ type: constant("local"), file: option( "-s", "--socket-file", string({ metavar: "FILE" }), ), }), ) type Result = InferValue<typeof parser>; // Resultの推論された型 type Result = { readonly type: "network"; readonly host: string; readonly port: number; } | { readonly type: "local"; readonly file: string; }

@hongminhee@hackers.pub

최근 Optique라는 다소 실험적인 CLI 파서 라이브러리를 제작하게 되었습니다. 이 글을 쓰는 2025년 8월 21일 시점으로 아직 0.1.0도 릴리스되지 않았지만, 나름대로 재미있는 발상이라고 생각해서 이 글을 통해 소개합니다.

Optique는 크게 두 가지 다른 라이브러리로부터 영향을 받았습니다. 하나는 Haskell의 optparse-applicative라는 라이브러리인데, 이 라이브러리로부터 얻은 교훈은 CLI 파서도 파서 컴비네이터가 될 수 있고, 그렇게 만들었을 때 매우 유용하다는 사실입니다. 다른 하나는 TypeScript 사용자들에게 이미 익숙한 Zod입니다. 비록 optparse-applicative에서 아이디어의 줄기를 얻긴 했지만, Haskell과 TypeScript는 너무나 다른 언어라서 API를 구성하는 방식에 큰 차이가 있습니다. 그래서 API를 구성하는 방식에 있어서는 Zod를 비롯한 여러 유효성 검사 라이브러리를 참고하게 되었습니다.

Optique는 여러 작은 파서들과 파서 컴비네이터들을 레고 부품처럼 조립하여 CLI가 어떠한 모양이어야 하는지를 표현합니다. 예를 들어 가장 작은 부품 중 하나로는 option()이 있습니다:

const parser = option("-a", "--allow", url());

이 파서를 실행하려면 run()이라는 API를 사용하면 됩니다: (참고로 run() 함수는 암시적으로 process.argv.slice(2)를 읽습니다.)

const allow: URL = run(parser);

위 코드에서 제가 일부러 URL이라는 타입을 명시하긴 했지만, 굳이 그렇게 하지 않아도 저절로 URL 타입으로 추론됩니다. 위 파서는 -a/--allow=URL 옵션만을 받아들입니다. 다른 옵션이나 인자를 줄 경우 오류가 납니다. -a/--allow=URL 옵션이 주어지지 않아도 오류가 납니다.

만약 -a/--allow=URL 옵션을 필수가 아닌 선택으로 두려면 어떻게 해야 할까요? 그럴 때는 optional() 컴비네이터로 option() 파서를 감싸면 됩니다.

const parser = optional(option("-a", "--allow", url()));

이 파서를 실행하면 결과로 어떤 타입이 나올까요?

const allow: URL | undefined = run(parser);

네, URL | undefined 타입이 됩니다.

아니면, 아예 -a/--allow=URL 옵션을 여러 개 받을 수 있게 해봅시다. 아래처럼 쓸 수 있게요:

prog -a https://example.com/ -a https://hackers.pub/

이렇게 옵션을 여러 번 쓸 수 있게 하려면, optional() 컴비네이터 대신 multiple() 컴비네이터를 씁니다:

const parser = multiple(option("-a", "--allow", url()));

이제 슬슬 결과 타입이 어떻게 나올지 예상이 되시죠?

const allowList: readonly URL[] = run(parser);

네, readonly URL[] 타입이 됩니다.

그런데, 만약 -a/--allow=URL 옵션과는 함께 쓸 수 없는 상호배타적인 -d/--disallow=URL이라는 옵션을 추가하려면 어떻게 해야 할까요? 둘 중 한 쪽의 옵션만 동시에 쓸 수 있어야 합니다. 이럴 때는 or() 컴비네이터를 사용하면 됩니다:

const parser = or(
  multiple(option("-a", "--allow", url())),
  multiple(option("-d", "--disallow", url())),
);

이 파서는 다음과 같은 명령들은 잘 받아들입니다:

prog -a https://example.com/ --allow    https://hackers.pub/
prog -d https://example.com/ --disallow https://hackers.pub/

하지만 다음과 같이 -a/--allow=URL 옵션과 -d/--disallow=URL 옵션이 섞여있을 때는 오류를 냅니다:

prog -a https://example.com/ --disallow https://hackers.pub/

아무튼, 그럼 이 파서의 결과는 어떤 타입이 될까요?

const result: readonly URL[] = run(parser);

이런, or() 컴비네이터가 감싸는 2개의 파서 모두 readonly URL[] 타입의 값을 만들기 때문에 readonly URL[] | readonly URL[] 타입이 되어, 결과적으로 readonly URL[] 타입이 되어버렸습니다. 제대로 된 변별 공용체(discriminated union) 형식으로 바꾸고 싶군요. 아래와 같은 타입이면 좋을 것 같습니다.

const Result =
  | { mode: "allowList"; allowList: readonly URL[] }
  | { mode: "blockList"; blockList: readonly URL[] };

이렇게 객체 형태의 구조를 만들고 싶을 때는 object() 컴비네이터를 쓰면 됩니다:

const parser = or(
  object({
    mode: constant("allowList"),
    allowList: multiple(option("-a", "--allow", url())),
  }),
  object({
    mode: constant("blockList"),
    blockList: multiple(option("-d", "--disallow", url())),
  }),
);

변별자(discriminator)를 부여하기 위해 constant() 파서도 사용했습니다. 이 파서는 조금 특이한 파서인데, 아무 것도 읽지 않고 주어진 값을 만들기만 합니다. 즉, 항상 성공하는 파서입니다. 이렇게 변별 공용체를 구성할 때 주로 쓰이지만, 다른 창의적인 방식으로도 쓰일 수 있을 겁니다.

이제 이 파서는 우리가 원하는 타입의 결과 값을 만듭니다:

const result:
  | { readonly mode: "allowList"; readonly allowList: readonly URL[] }
  | { readonly mode: "blockList"; readonly blockList: readonly URL[] }
  = run(parser);

꼭 상호배타적인 옵션들에만 or() 컴비네이터나 object() 컴비네이터를 쓰는 건 아닙니다. 서브커맨드도 같은 원리로 구현할 수 있습니다. 하나의 커맨드에 매치되는 command() 파서와 순서 인자에 매치되는 argument() 파서를 소개합니다:

const parser = command(
  "download",
  object({
    targetDirectory: optional(
      option(
        "-t", "--target",
        file({ metavar: "DIR", type: "directory" })
      )
    ),
    urls: multiple(argument(url())),
  })
)

위 파서는 아래와 같은 명령에 매치됩니다:

prog download --target=out/ https://example.com/ https://example.net/

파서의 결과 타입은 다음과 같습니다:

const result: {
  readonly targetDirectory: string | undefined;
  readonly urls: readonly URL[];
} = run(parser); 

여기에 upload 서브커맨드를 추가하려면 어떻게 해야 할까요? 맞습니다, or() 컴비네이터로 엮으면 됩니다:

const parser = or(
  command(
    "download",
    object({
      action: constant("download"),
      targetDirectory: optional(
        option(
          "-t", "--target",
          file({ metavar: "DIR", type: "directory" })
        )
      ),
      urls: multiple(argument(url())),
    })
  ),
  command(
    "upload",
    object({
      action: constant("upload"),
      url: option("-d", "--dest", "--destination", url()),
      files: multiple(
        argument(file({ metavar: "FILE", type: "file" })),
        { min: 1 },
      ),
    })
  ),
);

위 파서는 이제 다음과 같은 명령들을 받아들일 수 있게 되었습니다:

prog upload ./a.txt ./b.txt -d https://example.com/
prog download -t ./out/ https://example.com/ https://hackers.pub/

이 파서의 결과 타입은 다음과 같습니다:

const result:
  | {
      readonly action: "download";
      readonly targetDirectory: string | undefined;
      readonly urls: readonly URL[];
    }
  | {
      readonly action: "upload";
      readonly url: URL;
      readonly files: readonly string[];
    }
  = run(parser); 

같은 방식을 응용하면 겹쳐진 서브커맨드(nested subcommands)도 구현할 수 있겠죠?

자, 이렇게 Optique가 CLI를 표현하는 방식을 보여드렸는데요. 어떤 것 같나요? Optique의 방식이 복잡한 CLI를 표현하기에 적합하다는 게 와닿으시나요?

물론, Optique의 방식도 완벽하지는 않습니다. 아주 전형적이고 단순한 CLI를 정의하는 데에는 오히려 더 손이 가는 것도 사실입니다. 또한, Optique는 오로지 CLI 파서의 역할만 하고 있기 때문에 일반적인 CLI 앱 프레임워크가 제공하는 다양한 기능은 제공하지 않기도 합니다. (추후 Optique에 더 많은 기능을 추가할 예정이긴 합니다만…)

그럼에도 Optique의 접근 방식에 흥미를 느끼셨다면, 소개 문서튜토리얼도 한 번 살펴보시기 바랍니다.

unstable.optique.dev

Optique tutorial: Build type-safe CLIs step by step | Optique

This tutorial walks you through building type-safe command-line applications using Optique's parser combinators, starting from simple options to complex subcommands.

@nebuleto@hackers.pub

저는 일과는 별개로 두통과 함께하는 사람들라는 두통 환자 단체를 만들고 있는데요. 9월 말에 있는 편두통 인식 주간(Migraine Awareness Week)를 맞아서 여러 가지를 준비하고 있습니다. 이번에 편두통 환자나 가족, 보호자를 대상으로 편두통으로 있었던 에피소드를 공유하는 수기 공모전을 진행하게 되었습니다. 수기 공모전은 9월 7일까지 카페에 글을 쓰고 신청할 수 있는데요. 상품 등도 같이 준비하였습니다. 주변에 널리 공유해주시고 관심 부탁드리겠습니다.

트위터인스타그램도 있으니 많은 팔로우 부탁드립니다.

편두통 수기 공모전 포스터 이미지
ALT text

편두통 수기 공모전 포스터 이미지

보도자료 올라온 이미지
ALT text

보도자료 올라온 이미지

最近、OptiqueというTypeScript向けのCLIパーサー「コンビネーター」を作っています。Optiqueは、複雑なCLIを小さなパーツの組み合わせで記述できる様にしてくれます。そして、そのCLIのパース結果を型安全に扱う事が出来ます。(下記のコード参照)アイデアはHaskellのoptparse-applicative から得ましたが、TypeScriptはHaskellとAPIのスタイルがかなり異なる為、APIの面ではZod等を参考にしました。詳しい紹介はHackers' Pubに投稿した記事をご覧ください!

const parser = or(
  object({
    type: constant("network"),
    host: option(
      "-h", "--host",
      string({ metavar: "HOST" }),
    ),
    port: option(
      "-p", "--port",
      integer({ metavar: "PORT", min: 0, max: 65535 }),
    ),
  }),
  object({
    type: constant("local"),
    file: option(
      "-s", "--socket-file",
      string({ metavar: "FILE" }),
    ),
  }),
)

type Result = InferValue<typeof parser>;

// Resultの推論された型
type Result = {
    readonly type: "network";
    readonly host: string;
    readonly port: number;
} | {
    readonly type: "local";
    readonly file: string;
}
ALT text

const parser = or( object({ type: constant("network"), host: option( "-h", "--host", string({ metavar: "HOST" }), ), port: option( "-p", "--port", integer({ metavar: "PORT", min: 0, max: 65535 }), ), }), object({ type: constant("local"), file: option( "-s", "--socket-file", string({ metavar: "FILE" }), ), }), ) type Result = InferValue<typeof parser>; // Resultの推論された型 type Result = { readonly type: "network"; readonly host: string; readonly port: number; } | { readonly type: "local"; readonly file: string; }

@hongminhee@hackers.pub

최근 Optique라는 다소 실험적인 CLI 파서 라이브러리를 제작하게 되었습니다. 이 글을 쓰는 2025년 8월 21일 시점으로 아직 0.1.0도 릴리스되지 않았지만, 나름대로 재미있는 발상이라고 생각해서 이 글을 통해 소개합니다.

Optique는 크게 두 가지 다른 라이브러리로부터 영향을 받았습니다. 하나는 Haskell의 optparse-applicative라는 라이브러리인데, 이 라이브러리로부터 얻은 교훈은 CLI 파서도 파서 컴비네이터가 될 수 있고, 그렇게 만들었을 때 매우 유용하다는 사실입니다. 다른 하나는 TypeScript 사용자들에게 이미 익숙한 Zod입니다. 비록 optparse-applicative에서 아이디어의 줄기를 얻긴 했지만, Haskell과 TypeScript는 너무나 다른 언어라서 API를 구성하는 방식에 큰 차이가 있습니다. 그래서 API를 구성하는 방식에 있어서는 Zod를 비롯한 여러 유효성 검사 라이브러리를 참고하게 되었습니다.

Optique는 여러 작은 파서들과 파서 컴비네이터들을 레고 부품처럼 조립하여 CLI가 어떠한 모양이어야 하는지를 표현합니다. 예를 들어 가장 작은 부품 중 하나로는 option()이 있습니다:

const parser = option("-a", "--allow", url());

이 파서를 실행하려면 run()이라는 API를 사용하면 됩니다: (참고로 run() 함수는 암시적으로 process.argv.slice(2)를 읽습니다.)

const allow: URL = run(parser);

위 코드에서 제가 일부러 URL이라는 타입을 명시하긴 했지만, 굳이 그렇게 하지 않아도 저절로 URL 타입으로 추론됩니다. 위 파서는 -a/--allow=URL 옵션만을 받아들입니다. 다른 옵션이나 인자를 줄 경우 오류가 납니다. -a/--allow=URL 옵션이 주어지지 않아도 오류가 납니다.

만약 -a/--allow=URL 옵션을 필수가 아닌 선택으로 두려면 어떻게 해야 할까요? 그럴 때는 optional() 컴비네이터로 option() 파서를 감싸면 됩니다.

const parser = optional(option("-a", "--allow", url()));

이 파서를 실행하면 결과로 어떤 타입이 나올까요?

const allow: URL | undefined = run(parser);

네, URL | undefined 타입이 됩니다.

아니면, 아예 -a/--allow=URL 옵션을 여러 개 받을 수 있게 해봅시다. 아래처럼 쓸 수 있게요:

prog -a https://example.com/ -a https://hackers.pub/

이렇게 옵션을 여러 번 쓸 수 있게 하려면, optional() 컴비네이터 대신 multiple() 컴비네이터를 씁니다:

const parser = multiple(option("-a", "--allow", url()));

이제 슬슬 결과 타입이 어떻게 나올지 예상이 되시죠?

const allowList: readonly URL[] = run(parser);

네, readonly URL[] 타입이 됩니다.

그런데, 만약 -a/--allow=URL 옵션과는 함께 쓸 수 없는 상호배타적인 -d/--disallow=URL이라는 옵션을 추가하려면 어떻게 해야 할까요? 둘 중 한 쪽의 옵션만 동시에 쓸 수 있어야 합니다. 이럴 때는 or() 컴비네이터를 사용하면 됩니다:

const parser = or(
  multiple(option("-a", "--allow", url())),
  multiple(option("-d", "--disallow", url())),
);

이 파서는 다음과 같은 명령들은 잘 받아들입니다:

prog -a https://example.com/ --allow    https://hackers.pub/
prog -d https://example.com/ --disallow https://hackers.pub/

하지만 다음과 같이 -a/--allow=URL 옵션과 -d/--disallow=URL 옵션이 섞여있을 때는 오류를 냅니다:

prog -a https://example.com/ --disallow https://hackers.pub/

아무튼, 그럼 이 파서의 결과는 어떤 타입이 될까요?

const result: readonly URL[] = run(parser);

이런, or() 컴비네이터가 감싸는 2개의 파서 모두 readonly URL[] 타입의 값을 만들기 때문에 readonly URL[] | readonly URL[] 타입이 되어, 결과적으로 readonly URL[] 타입이 되어버렸습니다. 제대로 된 변별 공용체(discriminated union) 형식으로 바꾸고 싶군요. 아래와 같은 타입이면 좋을 것 같습니다.

const Result =
  | { mode: "allowList"; allowList: readonly URL[] }
  | { mode: "blockList"; blockList: readonly URL[] };

이렇게 객체 형태의 구조를 만들고 싶을 때는 object() 컴비네이터를 쓰면 됩니다:

const parser = or(
  object({
    mode: constant("allowList"),
    allowList: multiple(option("-a", "--allow", url())),
  }),
  object({
    mode: constant("blockList"),
    blockList: multiple(option("-d", "--disallow", url())),
  }),
);

변별자(discriminator)를 부여하기 위해 constant() 파서도 사용했습니다. 이 파서는 조금 특이한 파서인데, 아무 것도 읽지 않고 주어진 값을 만들기만 합니다. 즉, 항상 성공하는 파서입니다. 이렇게 변별 공용체를 구성할 때 주로 쓰이지만, 다른 창의적인 방식으로도 쓰일 수 있을 겁니다.

이제 이 파서는 우리가 원하는 타입의 결과 값을 만듭니다:

const result:
  | { readonly mode: "allowList"; readonly allowList: readonly URL[] }
  | { readonly mode: "blockList"; readonly blockList: readonly URL[] }
  = run(parser);

꼭 상호배타적인 옵션들에만 or() 컴비네이터나 object() 컴비네이터를 쓰는 건 아닙니다. 서브커맨드도 같은 원리로 구현할 수 있습니다. 하나의 커맨드에 매치되는 command() 파서와 순서 인자에 매치되는 argument() 파서를 소개합니다:

const parser = command(
  "download",
  object({
    targetDirectory: optional(
      option(
        "-t", "--target",
        file({ metavar: "DIR", type: "directory" })
      )
    ),
    urls: multiple(argument(url())),
  })
)

위 파서는 아래와 같은 명령에 매치됩니다:

prog download --target=out/ https://example.com/ https://example.net/

파서의 결과 타입은 다음과 같습니다:

const result: {
  readonly targetDirectory: string | undefined;
  readonly urls: readonly URL[];
} = run(parser); 

여기에 upload 서브커맨드를 추가하려면 어떻게 해야 할까요? 맞습니다, or() 컴비네이터로 엮으면 됩니다:

const parser = or(
  command(
    "download",
    object({
      action: constant("download"),
      targetDirectory: optional(
        option(
          "-t", "--target",
          file({ metavar: "DIR", type: "directory" })
        )
      ),
      urls: multiple(argument(url())),
    })
  ),
  command(
    "upload",
    object({
      action: constant("upload"),
      url: option("-d", "--dest", "--destination", url()),
      files: multiple(
        argument(file({ metavar: "FILE", type: "file" })),
        { min: 1 },
      ),
    })
  ),
);

위 파서는 이제 다음과 같은 명령들을 받아들일 수 있게 되었습니다:

prog upload ./a.txt ./b.txt -d https://example.com/
prog download -t ./out/ https://example.com/ https://hackers.pub/

이 파서의 결과 타입은 다음과 같습니다:

const result:
  | {
      readonly action: "download";
      readonly targetDirectory: string | undefined;
      readonly urls: readonly URL[];
    }
  | {
      readonly action: "upload";
      readonly url: URL;
      readonly files: readonly string[];
    }
  = run(parser); 

같은 방식을 응용하면 겹쳐진 서브커맨드(nested subcommands)도 구현할 수 있겠죠?

자, 이렇게 Optique가 CLI를 표현하는 방식을 보여드렸는데요. 어떤 것 같나요? Optique의 방식이 복잡한 CLI를 표현하기에 적합하다는 게 와닿으시나요?

물론, Optique의 방식도 완벽하지는 않습니다. 아주 전형적이고 단순한 CLI를 정의하는 데에는 오히려 더 손이 가는 것도 사실입니다. 또한, Optique는 오로지 CLI 파서의 역할만 하고 있기 때문에 일반적인 CLI 앱 프레임워크가 제공하는 다양한 기능은 제공하지 않기도 합니다. (추후 Optique에 더 많은 기능을 추가할 예정이긴 합니다만…)

그럼에도 Optique의 접근 방식에 흥미를 느끼셨다면, 소개 문서튜토리얼도 한 번 살펴보시기 바랍니다.

unstable.optique.dev

Optique tutorial: Build type-safe CLIs step by step | Optique

This tutorial walks you through building type-safe command-line applications using Optique's parser combinators, starting from simple options to complex subcommands.

@hongminhee@hollo.social

I've recently been working on Optique, a CLI parser combinator for TypeScript. Optique allows you to describe complex CLIs by combining smaller parts. You can also handle the CLI parsing results in a type-safe manner (see code below). The idea came from Haskell's optparse-applicative, but since TypeScript's API style is so different from Haskell's, I referenced Zod and similar libraries for the API design. For a more detailed introduction, please refer to the article I posted on Hackers' Pub!

const parser = or(
  object({
    type: constant("network"),
    host: option(
      "-h", "--host",
      string({ metavar: "HOST" }),
    ),
    port: option(
      "-p", "--port",
      integer({ metavar: "PORT", min: 0, max: 65535 }),
    ),
  }),
  object({
    type: constant("local"),
    file: option(
      "-s", "--socket-file",
      string({ metavar: "FILE" }),
    ),
  }),
)

type Result = InferValue<typeof parser>;

// The above type is inferred as:
type Result = {
    readonly type: "network";
    readonly host: string;
    readonly port: number;
} | {
    readonly type: "local";
    readonly file: string;
}
ALT text

const parser = or( object({ type: constant("network"), host: option( "-h", "--host", string({ metavar: "HOST" }), ), port: option( "-p", "--port", integer({ metavar: "PORT", min: 0, max: 65535 }), ), }), object({ type: constant("local"), file: option( "-s", "--socket-file", string({ metavar: "FILE" }), ), }), ) type Result = InferValue<typeof parser>; // The above type is inferred as: type Result = { readonly type: "network"; readonly host: string; readonly port: number; } | { readonly type: "local"; readonly file: string; }

@hongminhee@hackers.pub

최근 Optique라는 다소 실험적인 CLI 파서 라이브러리를 제작하게 되었습니다. 이 글을 쓰는 2025년 8월 21일 시점으로 아직 0.1.0도 릴리스되지 않았지만, 나름대로 재미있는 발상이라고 생각해서 이 글을 통해 소개합니다.

Optique는 크게 두 가지 다른 라이브러리로부터 영향을 받았습니다. 하나는 Haskell의 optparse-applicative라는 라이브러리인데, 이 라이브러리로부터 얻은 교훈은 CLI 파서도 파서 컴비네이터가 될 수 있고, 그렇게 만들었을 때 매우 유용하다는 사실입니다. 다른 하나는 TypeScript 사용자들에게 이미 익숙한 Zod입니다. 비록 optparse-applicative에서 아이디어의 줄기를 얻긴 했지만, Haskell과 TypeScript는 너무나 다른 언어라서 API를 구성하는 방식에 큰 차이가 있습니다. 그래서 API를 구성하는 방식에 있어서는 Zod를 비롯한 여러 유효성 검사 라이브러리를 참고하게 되었습니다.

Optique는 여러 작은 파서들과 파서 컴비네이터들을 레고 부품처럼 조립하여 CLI가 어떠한 모양이어야 하는지를 표현합니다. 예를 들어 가장 작은 부품 중 하나로는 option()이 있습니다:

const parser = option("-a", "--allow", url());

이 파서를 실행하려면 run()이라는 API를 사용하면 됩니다: (참고로 run() 함수는 암시적으로 process.argv.slice(2)를 읽습니다.)

const allow: URL = run(parser);

위 코드에서 제가 일부러 URL이라는 타입을 명시하긴 했지만, 굳이 그렇게 하지 않아도 저절로 URL 타입으로 추론됩니다. 위 파서는 -a/--allow=URL 옵션만을 받아들입니다. 다른 옵션이나 인자를 줄 경우 오류가 납니다. -a/--allow=URL 옵션이 주어지지 않아도 오류가 납니다.

만약 -a/--allow=URL 옵션을 필수가 아닌 선택으로 두려면 어떻게 해야 할까요? 그럴 때는 optional() 컴비네이터로 option() 파서를 감싸면 됩니다.

const parser = optional(option("-a", "--allow", url()));

이 파서를 실행하면 결과로 어떤 타입이 나올까요?

const allow: URL | undefined = run(parser);

네, URL | undefined 타입이 됩니다.

아니면, 아예 -a/--allow=URL 옵션을 여러 개 받을 수 있게 해봅시다. 아래처럼 쓸 수 있게요:

prog -a https://example.com/ -a https://hackers.pub/

이렇게 옵션을 여러 번 쓸 수 있게 하려면, optional() 컴비네이터 대신 multiple() 컴비네이터를 씁니다:

const parser = multiple(option("-a", "--allow", url()));

이제 슬슬 결과 타입이 어떻게 나올지 예상이 되시죠?

const allowList: readonly URL[] = run(parser);

네, readonly URL[] 타입이 됩니다.

그런데, 만약 -a/--allow=URL 옵션과는 함께 쓸 수 없는 상호배타적인 -d/--disallow=URL이라는 옵션을 추가하려면 어떻게 해야 할까요? 둘 중 한 쪽의 옵션만 동시에 쓸 수 있어야 합니다. 이럴 때는 or() 컴비네이터를 사용하면 됩니다:

const parser = or(
  multiple(option("-a", "--allow", url())),
  multiple(option("-d", "--disallow", url())),
);

이 파서는 다음과 같은 명령들은 잘 받아들입니다:

prog -a https://example.com/ --allow    https://hackers.pub/
prog -d https://example.com/ --disallow https://hackers.pub/

하지만 다음과 같이 -a/--allow=URL 옵션과 -d/--disallow=URL 옵션이 섞여있을 때는 오류를 냅니다:

prog -a https://example.com/ --disallow https://hackers.pub/

아무튼, 그럼 이 파서의 결과는 어떤 타입이 될까요?

const result: readonly URL[] = run(parser);

이런, or() 컴비네이터가 감싸는 2개의 파서 모두 readonly URL[] 타입의 값을 만들기 때문에 readonly URL[] | readonly URL[] 타입이 되어, 결과적으로 readonly URL[] 타입이 되어버렸습니다. 제대로 된 변별 공용체(discriminated union) 형식으로 바꾸고 싶군요. 아래와 같은 타입이면 좋을 것 같습니다.

const Result =
  | { mode: "allowList"; allowList: readonly URL[] }
  | { mode: "blockList"; blockList: readonly URL[] };

이렇게 객체 형태의 구조를 만들고 싶을 때는 object() 컴비네이터를 쓰면 됩니다:

const parser = or(
  object({
    mode: constant("allowList"),
    allowList: multiple(option("-a", "--allow", url())),
  }),
  object({
    mode: constant("blockList"),
    blockList: multiple(option("-d", "--disallow", url())),
  }),
);

변별자(discriminator)를 부여하기 위해 constant() 파서도 사용했습니다. 이 파서는 조금 특이한 파서인데, 아무 것도 읽지 않고 주어진 값을 만들기만 합니다. 즉, 항상 성공하는 파서입니다. 이렇게 변별 공용체를 구성할 때 주로 쓰이지만, 다른 창의적인 방식으로도 쓰일 수 있을 겁니다.

이제 이 파서는 우리가 원하는 타입의 결과 값을 만듭니다:

const result:
  | { readonly mode: "allowList"; readonly allowList: readonly URL[] }
  | { readonly mode: "blockList"; readonly blockList: readonly URL[] }
  = run(parser);

꼭 상호배타적인 옵션들에만 or() 컴비네이터나 object() 컴비네이터를 쓰는 건 아닙니다. 서브커맨드도 같은 원리로 구현할 수 있습니다. 하나의 커맨드에 매치되는 command() 파서와 순서 인자에 매치되는 argument() 파서를 소개합니다:

const parser = command(
  "download",
  object({
    targetDirectory: optional(
      option(
        "-t", "--target",
        file({ metavar: "DIR", type: "directory" })
      )
    ),
    urls: multiple(argument(url())),
  })
)

위 파서는 아래와 같은 명령에 매치됩니다:

prog download --target=out/ https://example.com/ https://example.net/

파서의 결과 타입은 다음과 같습니다:

const result: {
  readonly targetDirectory: string | undefined;
  readonly urls: readonly URL[];
} = run(parser); 

여기에 upload 서브커맨드를 추가하려면 어떻게 해야 할까요? 맞습니다, or() 컴비네이터로 엮으면 됩니다:

const parser = or(
  command(
    "download",
    object({
      action: constant("download"),
      targetDirectory: optional(
        option(
          "-t", "--target",
          file({ metavar: "DIR", type: "directory" })
        )
      ),
      urls: multiple(argument(url())),
    })
  ),
  command(
    "upload",
    object({
      action: constant("upload"),
      url: option("-d", "--dest", "--destination", url()),
      files: multiple(
        argument(file({ metavar: "FILE", type: "file" })),
        { min: 1 },
      ),
    })
  ),
);

위 파서는 이제 다음과 같은 명령들을 받아들일 수 있게 되었습니다:

prog upload ./a.txt ./b.txt -d https://example.com/
prog download -t ./out/ https://example.com/ https://hackers.pub/

이 파서의 결과 타입은 다음과 같습니다:

const result:
  | {
      readonly action: "download";
      readonly targetDirectory: string | undefined;
      readonly urls: readonly URL[];
    }
  | {
      readonly action: "upload";
      readonly url: URL;
      readonly files: readonly string[];
    }
  = run(parser); 

같은 방식을 응용하면 겹쳐진 서브커맨드(nested subcommands)도 구현할 수 있겠죠?

자, 이렇게 Optique가 CLI를 표현하는 방식을 보여드렸는데요. 어떤 것 같나요? Optique의 방식이 복잡한 CLI를 표현하기에 적합하다는 게 와닿으시나요?

물론, Optique의 방식도 완벽하지는 않습니다. 아주 전형적이고 단순한 CLI를 정의하는 데에는 오히려 더 손이 가는 것도 사실입니다. 또한, Optique는 오로지 CLI 파서의 역할만 하고 있기 때문에 일반적인 CLI 앱 프레임워크가 제공하는 다양한 기능은 제공하지 않기도 합니다. (추후 Optique에 더 많은 기능을 추가할 예정이긴 합니다만…)

그럼에도 Optique의 접근 방식에 흥미를 느끼셨다면, 소개 문서튜토리얼도 한 번 살펴보시기 바랍니다.

unstable.optique.dev

Optique tutorial: Build type-safe CLIs step by step | Optique

This tutorial walks you through building type-safe command-line applications using Optique's parser combinators, starting from simple options to complex subcommands.

@eatch.dev@bsky.brid.gy

패스워드 매니저 쓰시는 블친 여러분!!! 제로데이 취약점이 생겼다고 하니까 조심하세요!! 특히 - 1Password - Bitwarden - Enpass - iCloud - LastPass - LogMeOnce socket.dev/blog/passwor...

Researcher Exposes Zero-Day Cl...

socket.dev

Researcher Exposes Zero-Day Clickjacking Vulnerabilities in ...

Hacker Demonstrates How Easy It Is To Steal Data From Popular Password Managers

@silverpill@mitra.social
@hongminhee@hackers.pub

최근 Optique라는 다소 실험적인 CLI 파서 라이브러리를 제작하게 되었습니다. 이 글을 쓰는 2025년 8월 21일 시점으로 아직 0.1.0도 릴리스되지 않았지만, 나름대로 재미있는 발상이라고 생각해서 이 글을 통해 소개합니다.

Optique는 크게 두 가지 다른 라이브러리로부터 영향을 받았습니다. 하나는 Haskell의 optparse-applicative라는 라이브러리인데, 이 라이브러리로부터 얻은 교훈은 CLI 파서도 파서 컴비네이터가 될 수 있고, 그렇게 만들었을 때 매우 유용하다는 사실입니다. 다른 하나는 TypeScript 사용자들에게 이미 익숙한 Zod입니다. 비록 optparse-applicative에서 아이디어의 줄기를 얻긴 했지만, Haskell과 TypeScript는 너무나 다른 언어라서 API를 구성하는 방식에 큰 차이가 있습니다. 그래서 API를 구성하는 방식에 있어서는 Zod를 비롯한 여러 유효성 검사 라이브러리를 참고하게 되었습니다.

Optique는 여러 작은 파서들과 파서 컴비네이터들을 레고 부품처럼 조립하여 CLI가 어떠한 모양이어야 하는지를 표현합니다. 예를 들어 가장 작은 부품 중 하나로는 option()이 있습니다:

const parser = option("-a", "--allow", url());

이 파서를 실행하려면 run()이라는 API를 사용하면 됩니다: (참고로 run() 함수는 암시적으로 process.argv.slice(2)를 읽습니다.)

const allow: URL = run(parser);

위 코드에서 제가 일부러 URL이라는 타입을 명시하긴 했지만, 굳이 그렇게 하지 않아도 저절로 URL 타입으로 추론됩니다. 위 파서는 -a/--allow=URL 옵션만을 받아들입니다. 다른 옵션이나 인자를 줄 경우 오류가 납니다. -a/--allow=URL 옵션이 주어지지 않아도 오류가 납니다.

만약 -a/--allow=URL 옵션을 필수가 아닌 선택으로 두려면 어떻게 해야 할까요? 그럴 때는 optional() 컴비네이터로 option() 파서를 감싸면 됩니다.

const parser = optional(option("-a", "--allow", url()));

이 파서를 실행하면 결과로 어떤 타입이 나올까요?

const allow: URL | undefined = run(parser);

네, URL | undefined 타입이 됩니다.

아니면, 아예 -a/--allow=URL 옵션을 여러 개 받을 수 있게 해봅시다. 아래처럼 쓸 수 있게요:

prog -a https://example.com/ -a https://hackers.pub/

이렇게 옵션을 여러 번 쓸 수 있게 하려면, optional() 컴비네이터 대신 multiple() 컴비네이터를 씁니다:

const parser = multiple(option("-a", "--allow", url()));

이제 슬슬 결과 타입이 어떻게 나올지 예상이 되시죠?

const allowList: readonly URL[] = run(parser);

네, readonly URL[] 타입이 됩니다.

그런데, 만약 -a/--allow=URL 옵션과는 함께 쓸 수 없는 상호배타적인 -d/--disallow=URL이라는 옵션을 추가하려면 어떻게 해야 할까요? 둘 중 한 쪽의 옵션만 동시에 쓸 수 있어야 합니다. 이럴 때는 or() 컴비네이터를 사용하면 됩니다:

const parser = or(
  multiple(option("-a", "--allow", url())),
  multiple(option("-d", "--disallow", url())),
);

이 파서는 다음과 같은 명령들은 잘 받아들입니다:

prog -a https://example.com/ --allow    https://hackers.pub/
prog -d https://example.com/ --disallow https://hackers.pub/

하지만 다음과 같이 -a/--allow=URL 옵션과 -d/--disallow=URL 옵션이 섞여있을 때는 오류를 냅니다:

prog -a https://example.com/ --disallow https://hackers.pub/

아무튼, 그럼 이 파서의 결과는 어떤 타입이 될까요?

const result: readonly URL[] = run(parser);

이런, or() 컴비네이터가 감싸는 2개의 파서 모두 readonly URL[] 타입의 값을 만들기 때문에 readonly URL[] | readonly URL[] 타입이 되어, 결과적으로 readonly URL[] 타입이 되어버렸습니다. 제대로 된 변별 공용체(discriminated union) 형식으로 바꾸고 싶군요. 아래와 같은 타입이면 좋을 것 같습니다.

const Result =
  | { mode: "allowList"; allowList: readonly URL[] }
  | { mode: "blockList"; blockList: readonly URL[] };

이렇게 객체 형태의 구조를 만들고 싶을 때는 object() 컴비네이터를 쓰면 됩니다:

const parser = or(
  object({
    mode: constant("allowList"),
    allowList: multiple(option("-a", "--allow", url())),
  }),
  object({
    mode: constant("blockList"),
    blockList: multiple(option("-d", "--disallow", url())),
  }),
);

변별자(discriminator)를 부여하기 위해 constant() 파서도 사용했습니다. 이 파서는 조금 특이한 파서인데, 아무 것도 읽지 않고 주어진 값을 만들기만 합니다. 즉, 항상 성공하는 파서입니다. 이렇게 변별 공용체를 구성할 때 주로 쓰이지만, 다른 창의적인 방식으로도 쓰일 수 있을 겁니다.

이제 이 파서는 우리가 원하는 타입의 결과 값을 만듭니다:

const result:
  | { readonly mode: "allowList"; readonly allowList: readonly URL[] }
  | { readonly mode: "blockList"; readonly blockList: readonly URL[] }
  = run(parser);

꼭 상호배타적인 옵션들에만 or() 컴비네이터나 object() 컴비네이터를 쓰는 건 아닙니다. 서브커맨드도 같은 원리로 구현할 수 있습니다. 하나의 커맨드에 매치되는 command() 파서와 순서 인자에 매치되는 argument() 파서를 소개합니다:

const parser = command(
  "download",
  object({
    targetDirectory: optional(
      option(
        "-t", "--target",
        file({ metavar: "DIR", type: "directory" })
      )
    ),
    urls: multiple(argument(url())),
  })
)

위 파서는 아래와 같은 명령에 매치됩니다:

prog download --target=out/ https://example.com/ https://example.net/

파서의 결과 타입은 다음과 같습니다:

const result: {
  readonly targetDirectory: string | undefined;
  readonly urls: readonly URL[];
} = run(parser); 

여기에 upload 서브커맨드를 추가하려면 어떻게 해야 할까요? 맞습니다, or() 컴비네이터로 엮으면 됩니다:

const parser = or(
  command(
    "download",
    object({
      action: constant("download"),
      targetDirectory: optional(
        option(
          "-t", "--target",
          file({ metavar: "DIR", type: "directory" })
        )
      ),
      urls: multiple(argument(url())),
    })
  ),
  command(
    "upload",
    object({
      action: constant("upload"),
      url: option("-d", "--dest", "--destination", url()),
      files: multiple(
        argument(file({ metavar: "FILE", type: "file" })),
        { min: 1 },
      ),
    })
  ),
);

위 파서는 이제 다음과 같은 명령들을 받아들일 수 있게 되었습니다:

prog upload ./a.txt ./b.txt -d https://example.com/
prog download -t ./out/ https://example.com/ https://hackers.pub/

이 파서의 결과 타입은 다음과 같습니다:

const result:
  | {
      readonly action: "download";
      readonly targetDirectory: string | undefined;
      readonly urls: readonly URL[];
    }
  | {
      readonly action: "upload";
      readonly url: URL;
      readonly files: readonly string[];
    }
  = run(parser); 

같은 방식을 응용하면 겹쳐진 서브커맨드(nested subcommands)도 구현할 수 있겠죠?

자, 이렇게 Optique가 CLI를 표현하는 방식을 보여드렸는데요. 어떤 것 같나요? Optique의 방식이 복잡한 CLI를 표현하기에 적합하다는 게 와닿으시나요?

물론, Optique의 방식도 완벽하지는 않습니다. 아주 전형적이고 단순한 CLI를 정의하는 데에는 오히려 더 손이 가는 것도 사실입니다. 또한, Optique는 오로지 CLI 파서의 역할만 하고 있기 때문에 일반적인 CLI 앱 프레임워크가 제공하는 다양한 기능은 제공하지 않기도 합니다. (추후 Optique에 더 많은 기능을 추가할 예정이긴 합니다만…)

그럼에도 Optique의 접근 방식에 흥미를 느끼셨다면, 소개 문서튜토리얼도 한 번 살펴보시기 바랍니다.

unstable.optique.dev

Optique tutorial: Build type-safe CLIs step by step | Optique

This tutorial walks you through building type-safe command-line applications using Optique's parser combinators, starting from simple options to complex subcommands.

<sarcasm>

I find this claim highly
unbearble.

I mean, people with big egos cause serious problems! Fediverse itself is part of an evidence: Look at what Musk's ego did to our world. I am enraged.

Worse, this insight suggests me to ponder if I'm angry because my ego. That is further infuriating!

Worse, now I consider if I am so outraged because it has truth in it. That leaves me vehement!

This is a remarkable staircase of exponential anger. I am actually amazed. It reminds me of my astonishment when I first read Liu Cixin's _Death's End_, in which Luo Ji returns as the first Swordholder in the most terrifying, hard-boiled depiction of a war system.

Like an assassin, Hong Minhee forged this mental blade within a few words, and landed his strike. Now look at my babble. You can see how effective his attack was.

I still believe big egos are enraging, because they actually cause damage to our world, especially for equality and diversity.

I will also block anyone who asks me if I have a big ego.

</sarcasm>


RE: https://hollo.social/@hongminhee/0198b7fc-f946-715b-aa7c-d0da2c16fdbb

hollo.social

If you find it unbearable to b…

If you find it unbearable to be around people with big egos, you might want to consider whether your own ego is the problem.

@reiver@mastodon.social

Social Web Conferences

reiver.codeberg.page/social-we

I am working on creating a list of upcoming Social Web Conferences.

Using a broad definition of "Social Web" that includes the ActivityPub, AT-Protocol, ATmosphere, Bluesky, Farcaster, Fediverse, Matrix, and Nostr.

These are conferences that I might want to attend. (And, perhaps you may, too.)

Is there anything else I should add to this?