output.ts
This file
Path
apps/cli/src/output.ts
197 lines · 5.4 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 1why, one step back1// Notes go to stderr only, so `--json` stdout is always exactly one document.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 2–11why, one step back2import type { View } from "@repo/protocol/cli";3import { Envelope } from "@repo/protocol/envelope";4import type { Refusal } from "@repo/protocol/refusal";5import { explain } from "@repo/protocol/render";6import { Console, Context, Effect, Layer, Schema } from "effect";7import type { Array } from "effect";89import { Policy } from "./policy.ts";10import type { Mode } from "./policy.ts";11Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862
line 12why, one step back12export { endRefused, Reported } from "@repo/protocol/cli";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 13–115why, one step back1314export type { View } from "@repo/protocol/cli";1516export type { Mode } from "./policy.ts";1718export class Output extends Context.Service<19 Output,20 {21 readonly mode: Mode;22 readonly success: (input: {23 readonly command: string;24 readonly json: boolean;25 readonly data: unknown;26 readonly view: View;27 }) => Effect.Effect<void>;28 readonly refused: (input: {29 readonly command: string;30 readonly json: boolean;31 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;32 }) => Effect.Effect<void>;33 readonly plan: (input: {34 readonly command: string;35 readonly json: boolean;36 readonly payload: unknown;37 }) => Effect.Effect<void>;38 readonly note: (text: string) => Effect.Effect<void>;39 }40>()("cli/Output") {}4142const encodeEnvelope = Schema.encodeEffect(43 Schema.fromJsonString(Envelope(Schema.Unknown))44);4546const printEnvelope = (envelope: Envelope<unknown>) =>47 encodeEnvelope(envelope).pipe(Effect.orDie, Effect.flatMap(Console.log));4849const capitalized = (word: string) =>50 `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`;5152const asMarkdownList = (lines: readonly string[]) =>53 lines.map((line) => {54 const detail = /^ {2}(?<key>[a-z]+): (?<value>.*)$/u.exec(line)?.groups;5556 if (detail?.key === undefined || detail.value === undefined) {57 return `- ${line}`;58 }5960 const value = detail.key === "next" ? `\`${detail.value}\`` : detail.value;6162 return ` - ${capitalized(detail.key)}: ${value}`;63 });6465const planText = (mode: Mode, command: string, json: string) =>66 mode === "human"67 ? `${command} would send this, and sent nothing:\n${json}`68 : [69 `\`${command}\` would send this, and sent nothing (--dry-run):`,70 "",71 "```json",72 json,73 "```",74 ].join("\n");7576const outputFor = (mode: Mode): Output["Service"] => ({77 mode,78 note: (text) => Console.error(text),79 plan: ({ command, json, payload }) =>80 json81 ? printEnvelope({82 command,83 data: { dryRun: true, payload },84 ok: true,85 v: 1,86 })87 : Console.log(planText(mode, command, JSON.stringify(payload, null, 2))),88 refused: ({ command, json, refusals }) => {89 if (json) {90 return printEnvelope({ command, ok: false, refusals, v: 1 });91 }9293 const lines = explain(refusals);9495 return Console.error(96 (mode === "human" ? lines : asMarkdownList(lines)).join("\n")97 );98 },99 success: ({ command, data, json, view }) => {100 if (json) {101 return printEnvelope({ command, data, ok: true, v: 1 });102 }103104 return Console.log(105 mode === "human" ? (view.text ?? view.markdown) : view.markdown106 );107 },108});109110export const OutputPlain = Layer.succeed(Output)(outputFor("human"));111112export const OutputLive: Layer.Layer<Output, never, Policy> = Layer.effect(113 Output114)(Effect.map(Effect.service(Policy), ({ mode }) => outputFor(mode)));115Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 116why, one step back116/** effect/cli prints help on stdout for a misuse too: held, it is dropped after a misuse and printed otherwise. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 117–197why, one step back117export const holdStdout = (real: Console.Console) => {118 const held: (readonly unknown[])[] = [];119 let open = false;120121 // Each method hands its call to the real console; only `log` waits.122 const console: Console.Console = {123 assert: (condition, ...args: readonly unknown[]) => {124 real.assert(condition, ...args);125 },126 clear: () => {127 real.clear();128 },129 count: (label) => {130 real.count(label);131 },132 countReset: (label) => {133 real.countReset(label);134 },135 debug: (...args: readonly unknown[]) => {136 real.debug(...args);137 },138 dir: (item, options) => {139 real.dir(item, options);140 },141 dirxml: (...args: readonly unknown[]) => {142 real.dirxml(...args);143 },144 error: (...args: readonly unknown[]) => {145 real.error(...args);146 },147 group: (...args: readonly unknown[]) => {148 real.group(...args);149 },150 groupCollapsed: (...args: readonly unknown[]) => {151 real.groupCollapsed(...args);152 },153 groupEnd: () => {154 real.groupEnd();155 },156 info: (...args: readonly unknown[]) => {157 real.info(...args);158 },159 log: (...args: readonly unknown[]) => {160 if (open) {161 real.log(...args);162 } else {163 held.push(args);164 }165 },166 table: (data, properties) => {167 real.table(data, properties);168 },169 time: (label) => {170 real.time(label);171 },172 timeEnd: (label) => {173 real.timeEnd(label);174 },175 timeLog: (label, ...args: readonly unknown[]) => {176 real.timeLog(label, ...args);177 },178 trace: (...args: readonly unknown[]) => {179 real.trace(...args);180 },181 warn: (...args: readonly unknown[]) => {182 real.warn(...args);183 },184 };185186 return {187 console,188 open: Effect.sync(() => {189 open = true;190 }),191 release: Effect.sync(() => {192 for (const args of held.splice(0)) {193 real.log(...args);194 }195 }),196 };197};