@woodger/t-invest-node-sdk 0.5.4 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/application/services/unary-limiter.js +35 -8
- package/dist/bootstrap/args/command-options.d.ts +7 -1
- package/dist/bootstrap/args/command-options.js +10 -3
- package/dist/bootstrap/cli/help-catalog.d.ts +7 -7
- package/dist/bootstrap/cli/help-catalog.js +20 -26
- package/dist/bootstrap/cli/registry.d.ts +1 -1
- package/dist/bootstrap/commands/broker-report/cli.js +1 -1
- package/dist/bootstrap/commands/dividends-foreign-issuer/cli.js +1 -1
- package/dist/bootstrap/commands/order-book/cli.d.ts +3 -3
- package/dist/bootstrap/commands/order-book/cli.js +1 -1
- package/dist/bootstrap/commands/stream-run/config.d.ts +29 -6
- package/dist/bootstrap/commands/stream-run/config.js +17 -54
- package/dist/bootstrap/commands/stream-run/reporter.js +2 -0
- package/dist/bootstrap/commands/stream-run/request.mapper.js +70 -40
- package/dist/bootstrap/commands/stream-run/stream-session.js +7 -2
- package/dist/bootstrap/t-invest-node-sdk.js +13 -11
- package/dist/generated/common.js +2 -2
- package/dist/generated/google/api/field_behavior.js +2 -2
- package/dist/generated/google/protobuf/descriptor.js +2 -2
- package/dist/generated/google/protobuf/timestamp.js +2 -2
- package/dist/generated/instruments.js +2 -2
- package/dist/generated/marketdata.js +2 -2
- package/dist/generated/operations.js +2 -2
- package/dist/generated/orders.js +2 -2
- package/dist/generated/sandbox.js +2 -2
- package/dist/generated/signals.js +2 -2
- package/dist/generated/stoporders.js +2 -2
- package/dist/generated/users.js +2 -2
- package/dist/infrastructure/transport/grpc/sdk-call-error.js +5 -6
- package/dist/infrastructure/transport/grpc/sdk-client.d.ts +2 -2
- package/docs/architecture.md +4 -2
- package/docs/clean-architecture/adapters.md +7 -124
- package/docs/clean-architecture/api-commands.md +6 -160
- package/docs/clean-architecture/application.md +101 -1
- package/docs/clean-architecture/cli-output-boundaries.md +72 -29
- package/docs/clean-architecture/dto.md +9 -100
- package/docs/clean-architecture/index.md +6 -44
- package/docs/cli-reference.md +132 -0
- package/docs/cli-stream-configuration.md +5 -3
- package/docs/cli-stream-reference.md +5 -2
- package/docs/guides/custom-unary-limiter.md +11 -7
- package/docs/guides/errors-and-lifecycle.md +21 -0
- package/docs/index.md +2 -3
- package/docs/roadmap.md +1 -28
- package/package.json +9 -8
- package/readme.md +5 -41
|
@@ -4,120 +4,17 @@
|
|
|
4
4
|
|
|
5
5
|
## Контекст
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
- `account`;
|
|
12
|
-
- `instrument`;
|
|
13
|
-
- `market`;
|
|
14
|
-
- `order`;
|
|
15
|
-
- `stop-order`;
|
|
16
|
-
- `operation`;
|
|
17
|
-
- `sandbox`;
|
|
18
|
-
- `stream`;
|
|
19
|
-
- `dev`.
|
|
20
|
-
|
|
21
|
-
Technical и legacy paths работают как compatibility aliases, но help и документация показывают только preferred paths. Registry хранит один canonical definition на команду и передаёт остальные пути через first-class aliases `icore`. В resolved command поля `name` и `path` содержат preferred identity, а `matchedPath` — введённый путь. Текущий CLI contract:
|
|
22
|
-
|
|
23
|
-
- `account list` -> `sdk.users.getAccounts` (`account get-accounts`, `users get-accounts`);
|
|
24
|
-
- `account info` -> `sdk.users.getInfo` (`account get-info`, `users get-info`);
|
|
25
|
-
- `account margin` -> `sdk.users.getMarginAttributes` (`account get-margin-attributes`, `users get-margin-attributes`);
|
|
26
|
-
- `account tariff` -> `sdk.users.getUserTariff` (`account get-user-tariff`, `users get-user-tariff`);
|
|
27
|
-
- `market candles` -> `sdk.marketData.getCandles` (`market get-candles`, `marketdata get-candles`);
|
|
28
|
-
- `market close-prices` -> `sdk.marketData.getClosePrices` (`market get-close-prices`, `marketdata get-close-prices`);
|
|
29
|
-
- `market last-prices` -> `sdk.marketData.getLastPrices` (`market get-last-prices`, `marketdata get-last-prices`);
|
|
30
|
-
- `market trades` -> `sdk.marketData.getLastTrades` (`market get-last-trades`, `marketdata get-last-trades`);
|
|
31
|
-
- `market order-book` -> `sdk.marketData.getOrderBook` (`market get-order-book`, `marketdata get-order-book`);
|
|
32
|
-
- `market status` -> `sdk.marketData.getTradingStatus` (`market get-trading-status`, `marketdata get-trading-status`);
|
|
33
|
-
- `market statuses` -> `sdk.marketData.getTradingStatuses` (`market get-trading-statuses`, `marketdata get-trading-statuses`);
|
|
34
|
-
- `instrument search` -> `sdk.instruments.findInstrument` (`instrument find-instrument`, `instruments find-instrument`);
|
|
35
|
-
- `instrument show` -> `sdk.instruments.getInstrumentBy` (`instrument get-instrument-by`, `instruments get-instrument-by`);
|
|
36
|
-
- `instrument dividends` -> `sdk.instruments.getDividends` (`instrument get-dividends`, `instruments get-dividends`);
|
|
37
|
-
- `instrument schedules` -> `sdk.instruments.tradingSchedules` (`instrument trading-schedules`, `instruments trading-schedules`);
|
|
38
|
-
- `instrument favorite list` -> `sdk.instruments.getFavorites` (`instrument get-favorites`, `instruments get-favorites`);
|
|
39
|
-
- `instrument favorite edit` -> `sdk.instruments.editFavorites` (`instrument edit-favorites`, `instruments edit-favorites`);
|
|
40
|
-
- `instrument share list` -> `sdk.instruments.shares` (`instrument shares`, `instruments shares`);
|
|
41
|
-
- `instrument share show` -> `sdk.instruments.shareBy` (`instrument share-by`, `instruments share-by`);
|
|
42
|
-
- `instrument bond list` -> `sdk.instruments.bonds` (`instrument bonds`, `instruments bonds`);
|
|
43
|
-
- `instrument bond show` -> `sdk.instruments.bondBy` (`instrument bond-by`, `instruments bond-by`);
|
|
44
|
-
- `instrument bond coupons` -> `sdk.instruments.getBondCoupons` (`instrument get-bond-coupons`, `instruments get-bond-coupons`);
|
|
45
|
-
- `instrument bond accrued` -> `sdk.instruments.getAccruedInterests` (`instrument get-accrued-interests`, `instruments get-accrued-interests`);
|
|
46
|
-
- `instrument etf list` -> `sdk.instruments.etfs` (`instrument etfs`, `instruments etfs`);
|
|
47
|
-
- `instrument etf show` -> `sdk.instruments.etfBy` (`instrument etf-by`, `instruments etf-by`);
|
|
48
|
-
- `instrument currency list` -> `sdk.instruments.currencies` (`instrument currencies`, `instruments currencies`);
|
|
49
|
-
- `instrument currency show` -> `sdk.instruments.currencyBy` (`instrument currency-by`, `instruments currency-by`);
|
|
50
|
-
- `instrument future list` -> `sdk.instruments.futures` (`instrument futures`, `instruments futures`);
|
|
51
|
-
- `instrument future show` -> `sdk.instruments.futureBy` (`instrument future-by`, `instruments future-by`);
|
|
52
|
-
- `instrument future margin` -> `sdk.instruments.getFuturesMargin` (`instrument get-futures-margin`, `instruments get-futures-margin`);
|
|
53
|
-
- `instrument option list` -> `sdk.instruments.optionsBy` (`instrument options-by`, `instruments options-by`);
|
|
54
|
-
- `instrument option show` -> `sdk.instruments.optionBy` (`instrument option-by`, `instruments option-by`);
|
|
55
|
-
- `instrument asset list` -> `sdk.instruments.getAssets` (`instrument get-assets`, `instruments get-assets`);
|
|
56
|
-
- `instrument asset show` -> `sdk.instruments.getAssetBy` (`instrument get-asset-by`, `instruments get-asset-by`);
|
|
57
|
-
- `instrument brand list` -> `sdk.instruments.getBrands` (`instrument get-brands`, `instruments get-brands`);
|
|
58
|
-
- `instrument brand show` -> `sdk.instruments.getBrandBy` (`instrument get-brand-by`, `instruments get-brand-by`);
|
|
59
|
-
- `instrument country list` -> `sdk.instruments.getCountries` (`instrument get-countries`, `instruments get-countries`);
|
|
60
|
-
- `order list` -> `sdk.orders.getOrders` (`order get-orders`, `orders get-orders`);
|
|
61
|
-
- `order show` -> `sdk.orders.getOrderState` (`order get-order-state`, `orders get-order-state`);
|
|
62
|
-
- `order place` -> `sdk.orders.postOrder` (`order post-order`, `orders post-order`);
|
|
63
|
-
- `order cancel` -> `sdk.orders.cancelOrder` (`order cancel-order`, `orders cancel-order`);
|
|
64
|
-
- `order replace` -> `sdk.orders.replaceOrder` (`order replace-order`, `orders replace-order`);
|
|
65
|
-
- `operation list` -> `sdk.operations.getOperations` (`operation get-operations`, `operations get-operations`);
|
|
66
|
-
- `operation page` -> `sdk.operations.getOperationsByCursor` (`operation get-operations-by-cursor`, `operations get-operations-by-cursor`);
|
|
67
|
-
- `operation broker-report` -> `sdk.operations.getBrokerReport` (`operation get-broker-report`, `operations get-broker-report`);
|
|
68
|
-
- `operation foreign-dividends-report` -> `sdk.operations.getDividendsForeignIssuer` (`operation get-dividends-foreign-issuer`, `operations get-dividends-foreign-issuer`);
|
|
69
|
-
- `operation portfolio` -> `sdk.operations.getPortfolio` (`operation get-portfolio`, `operations get-portfolio`);
|
|
70
|
-
- `operation positions` -> `sdk.operations.getPositions` (`operation get-positions`, `operations get-positions`);
|
|
71
|
-
- `operation withdraw-limits` -> `sdk.operations.getWithdrawLimits` (`operation get-withdraw-limits`, `operations get-withdraw-limits`);
|
|
72
|
-
- `stop-order list` -> `sdk.stopOrders.getStopOrders` (`stop-order get-stop-orders`, `stoporders get-stop-orders`);
|
|
73
|
-
- `stop-order place` -> `sdk.stopOrders.postStopOrder` (`stop-order post-stop-order`, `stoporders post-stop-order`);
|
|
74
|
-
- `stop-order cancel` -> `sdk.stopOrders.cancelStopOrder` (`stop-order cancel-stop-order`, `stoporders cancel-stop-order`);
|
|
75
|
-
- `sandbox account list` -> `sdk.sandbox.getSandboxAccounts` (`sandbox get-sandbox-accounts`);
|
|
76
|
-
- `sandbox account open` -> `sdk.sandbox.openSandboxAccount` (`sandbox open-sandbox-account`);
|
|
77
|
-
- `sandbox account close` -> `sdk.sandbox.closeSandboxAccount` (`sandbox close-sandbox-account`);
|
|
78
|
-
- `sandbox order list` -> `sdk.sandbox.getSandboxOrders` (`sandbox get-sandbox-orders`);
|
|
79
|
-
- `sandbox order show` -> `sdk.sandbox.getSandboxOrderState` (`sandbox get-sandbox-order-state`);
|
|
80
|
-
- `sandbox order place` -> `sdk.sandbox.postSandboxOrder` (`sandbox post-sandbox-order`);
|
|
81
|
-
- `sandbox order replace` -> `sdk.sandbox.replaceSandboxOrder` (`sandbox replace-sandbox-order`);
|
|
82
|
-
- `sandbox order cancel` -> `sdk.sandbox.cancelSandboxOrder` (`sandbox cancel-sandbox-order`);
|
|
83
|
-
- `sandbox position list` -> `sdk.sandbox.getSandboxPositions` (`sandbox get-sandbox-positions`);
|
|
84
|
-
- `sandbox operation list` -> `sdk.sandbox.getSandboxOperations` (`sandbox get-sandbox-operations`);
|
|
85
|
-
- `sandbox operation page` -> `sdk.sandbox.getSandboxOperationsByCursor` (`sandbox get-sandbox-operations-by-cursor`);
|
|
86
|
-
- `sandbox portfolio` -> `sdk.sandbox.getSandboxPortfolio` (`sandbox get-sandbox-portfolio`);
|
|
87
|
-
- `sandbox withdraw-limits` -> `sdk.sandbox.getSandboxWithdrawLimits` (`sandbox get-sandbox-withdraw-limits`);
|
|
88
|
-
- `sandbox pay-in` -> `sdk.sandbox.sandboxPayIn` (`sandbox sandbox-pay-in`);
|
|
89
|
-
- `stream run` -> поток выбирается в JSON config;
|
|
90
|
-
- `dev compile-proto` -> TypeScript contract generation (`compile-proto`).
|
|
91
|
-
- `help` -> встроенная справка по CLI, домену или команде;
|
|
92
|
-
- `version` -> версия пакета.
|
|
7
|
+
Поддерживаемые команды, preferred paths, compatibility aliases, действующие stream-возможности и ограничения описаны в [справочнике CLI](../cli-reference.md). Здесь приведены правила устройства command layer.
|
|
8
|
+
|
|
9
|
+
Registry хранит один canonical definition на команду и передаёт остальные пути через first-class aliases `icore`. В resolved command поля `name` и `path` содержат preferred identity, а `matchedPath` — введённый путь.
|
|
93
10
|
|
|
94
11
|
Добавляйте API-команды по одной, когда выбран конкретный SDK method и понятен CLI-контракт. Preferred path должен попасть в command definition и help, а technical/legacy aliases — только в единый alias layer, который передаёт их в native command definition `icore`.
|
|
95
12
|
|
|
96
13
|
## Отложенные расширения
|
|
97
14
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
Действующие команды с side effects входят в текущий CLI-контракт и по умолчанию требуют явный `--confirm` через `defaultConfig.requireSideEffectConfirmation`. CLI не генерирует idempotency keys автоматически: `order place` принимает `--order-id`, а `order replace` — `--idempotency-key`.
|
|
101
|
-
|
|
102
|
-
`sandbox pay-in` принимает `--currency=rub|usd`. CLI parser отклоняет неизвестные currency values, а для явно неподдержанного provider-кейса `--currency=usd` команда возвращает ошибку.
|
|
103
|
-
|
|
104
|
-
Для Stream API есть отдельная utility-команда `stream run --config=PATH`. Контракт долгоживущих подписок, завершения процесса и формата событий описан в [справочнике потокового CLI](../cli-stream-reference.md) и [справочнике его конфигурации](../cli-stream-configuration.md).
|
|
105
|
-
|
|
106
|
-
Сейчас CLI поддерживает server-side streams и статический initial request contract для bidirectional market data stream:
|
|
107
|
-
|
|
108
|
-
- `sdk.marketdataStream.marketDataStream`;
|
|
109
|
-
- `sdk.marketdataStream.marketDataServerSideStream`;
|
|
110
|
-
- `sdk.operationsStream.portfolioStream`;
|
|
111
|
-
- `sdk.operationsStream.positionsStream`;
|
|
112
|
-
- `sdk.ordersStream.tradesStream`.
|
|
113
|
-
|
|
114
|
-
Динамические bidirectional request sources остаются отложенным API-контрактом.
|
|
15
|
+
Динамические bidirectional request sources остаются отложенным API-контрактом. Перед расширением stream command сверьте поведение со [справочником потокового CLI](../cli-stream-reference.md) и [справочником конфигурации](../cli-stream-configuration.md); любое изменение контракта нужно описать отдельно.
|
|
115
16
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
- `sdk.instruments.options` - deprecated в generated contract; вместо него используется `instrument option list` / `sdk.instruments.optionsBy`.
|
|
119
|
-
|
|
120
|
-
Перед расширением stream command сверьте поведение с этими reference-документами и отдельно опишите любое изменение контракта.
|
|
17
|
+
## Command flow
|
|
121
18
|
|
|
122
19
|
В command flow участвуют несколько ответственностей:
|
|
123
20
|
|
|
@@ -244,61 +141,10 @@ report/event contract -> command-specific output values
|
|
|
244
141
|
|
|
245
142
|
## Важное разделение
|
|
246
143
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
```text
|
|
250
|
-
application report/command-local event -> command-specific output values
|
|
251
|
-
```
|
|
252
|
-
|
|
253
|
-
Это CLI adapter/presentation policy в command reporter-е.
|
|
254
|
-
|
|
255
|
-
```text
|
|
256
|
-
output values -> JSON/CSV/table string
|
|
257
|
-
```
|
|
258
|
-
|
|
259
|
-
Это generic format mechanics `icore`.
|
|
260
|
-
|
|
261
|
-
```text
|
|
262
|
-
string/AsyncIterable -> TerminalApp -> Output.write -> stdout
|
|
263
|
-
```
|
|
264
|
-
|
|
265
|
-
Это normal output через `icore` facade, собранный project runner-ом.
|
|
266
|
-
|
|
267
|
-
```text
|
|
268
|
-
warnings/errors -> Output.error -> stderr
|
|
269
|
-
```
|
|
270
|
-
|
|
271
|
-
Output boundary не должен знать, как строить JSON, CSV или table.
|
|
144
|
+
Reporter выбирает смысл и структуру пользовательского вывода, render primitives выполняют общую механику формата, а terminal output доставляет готовый результат. Потоки stdout и stderr и ограничения output boundary описаны в [основной границе форматирования и вывода](./cli-output-boundaries.md#основная-граница).
|
|
272
145
|
|
|
273
146
|
## Принятое разделение
|
|
274
147
|
|
|
275
|
-
```text
|
|
276
|
-
src/bootstrap
|
|
277
|
-
index.ts
|
|
278
|
-
args/
|
|
279
|
-
command-options.ts
|
|
280
|
-
instrument-id-options.ts
|
|
281
|
-
instruments-args.ts
|
|
282
|
-
side-effect-args.ts
|
|
283
|
-
cli/
|
|
284
|
-
contract.ts
|
|
285
|
-
error.ts
|
|
286
|
-
registry.ts
|
|
287
|
-
runner.ts
|
|
288
|
-
commands/
|
|
289
|
-
<command-adapter>/
|
|
290
|
-
cli.ts
|
|
291
|
-
reporter.ts
|
|
292
|
-
|
|
293
|
-
src/infrastructure
|
|
294
|
-
report-values.ts
|
|
295
|
-
|
|
296
|
-
external dependency
|
|
297
|
-
icore
|
|
298
|
-
renderJson/renderCsv/renderCsvRow/renderTextTable
|
|
299
|
-
TerminalApp/Output
|
|
300
|
-
```
|
|
301
|
-
|
|
302
148
|
Граница:
|
|
303
149
|
|
|
304
150
|
- `bootstrap/commands/*/cli.ts` - command definition, API-specific orchestration и вызов общего SDK lifecycle;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Application-слой
|
|
2
2
|
|
|
3
|
-
> Type: Design Note. Здесь
|
|
3
|
+
> Type: Design Note. Здесь описаны роль `application`-слоя, DTO, отчёты и mapping между boundaries текущего SDK. Canonical-границы слоёв приведены в документе [«Архитектура SDK»](../architecture.md).
|
|
4
4
|
|
|
5
5
|
## Главная идея
|
|
6
6
|
|
|
@@ -50,6 +50,52 @@ src/application
|
|
|
50
50
|
- filesystem paths;
|
|
51
51
|
- concrete infrastructure modules.
|
|
52
52
|
|
|
53
|
+
## Контракты и DTO
|
|
54
|
+
|
|
55
|
+
В текущем проекте есть несколько разных типов contracts, и их нельзя смешивать:
|
|
56
|
+
|
|
57
|
+
- proto-generated DTO из `src/generated/*.ts`;
|
|
58
|
+
- application DTO из `src/application/dto/**`;
|
|
59
|
+
- application report contracts из `src/application/reports/**`;
|
|
60
|
+
- CLI command option schemas из `src/bootstrap/commands/**` и общие SDK options из `src/bootstrap/args/**`.
|
|
61
|
+
|
|
62
|
+
## Сгенерированные DTO
|
|
63
|
+
|
|
64
|
+
Vendored T-Invest proto-файлы хранятся в плоской структуре `contracts/*.proto`. Генератор зеркально создаёт из этого layout файлы `src/generated/*.ts`. `contracts/upstream.json` указывает официальный upstream snapshot.
|
|
65
|
+
|
|
66
|
+
Это wire contracts внешнего API. Их нельзя редактировать вручную и нельзя использовать как место для project-specific правил.
|
|
67
|
+
|
|
68
|
+
Допустимо:
|
|
69
|
+
|
|
70
|
+
- импортировать generated types в infrastructure adapters;
|
|
71
|
+
- использовать generated service definitions при создании gRPC clients внутри bootstrap/infrastructure;
|
|
72
|
+
- использовать generated request/response DTO в package-owned public service interfaces SDK facade.
|
|
73
|
+
|
|
74
|
+
Нежелательно:
|
|
75
|
+
|
|
76
|
+
- делать generated DTO основой новых application reports;
|
|
77
|
+
- добавлять handwritten mapping или helpers в generated файлы;
|
|
78
|
+
- завязывать CLI output format на нестабильный generated JSON shape.
|
|
79
|
+
- экспортировать generated service clients как root public API.
|
|
80
|
+
|
|
81
|
+
Исключение — server-side generated `*ServiceDefinition` и `*ServiceImplementation`. Они входят в root public API, потому что пакет поддерживает nice-grpc server adapters у Consumers.
|
|
82
|
+
|
|
83
|
+
## DTO уровня application
|
|
84
|
+
|
|
85
|
+
`src/application/dto/t-invest-options.ts` описывает options SDK facade.
|
|
86
|
+
|
|
87
|
+
Это не CLI DTO и не gRPC DTO. Один и тот же contract может использоваться из bootstrap, tests и публичного SDK facade.
|
|
88
|
+
|
|
89
|
+
Правило:
|
|
90
|
+
|
|
91
|
+
```text
|
|
92
|
+
CLI/env parsing -> TInvestOptions -> SDK facade/infrastructure
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`application/dto` не должен читать env и не должен знать про CLI flags.
|
|
96
|
+
|
|
97
|
+
`src/application/dto/t-invest-services.ts` описывает публичные service interfaces SDK facade: `UsersService`, `OrdersService`, `MarketDataStreamService` и другие. Эти interfaces сохраняют upstream method names и generated request/response DTO, но не раскрывают `nice-grpc` `*ServiceClient`, `*ServiceDefinition`, `CallOptions` или `CallContext`.
|
|
98
|
+
|
|
53
99
|
## Отчёты
|
|
54
100
|
|
|
55
101
|
`application/reports` описывает, что команда сообщает наружу, но не решает, как это показать пользователю.
|
|
@@ -103,8 +149,62 @@ Error code классифицирует ошибку, но не делает о
|
|
|
103
149
|
- use-case - если команда начинает координировать сценарий, а не просто вызывает один SDK method;
|
|
104
150
|
- domain - если появляются provider-neutral правила или модели.
|
|
105
151
|
|
|
152
|
+
## Входные данные CLI
|
|
153
|
+
|
|
154
|
+
Raw `process.argv` остаётся на executable-границе `src/bootstrap/index.ts`. Затем `bootstrap/cli/runner.ts` передаёт argv в terminal app и command registry из `icore`:
|
|
155
|
+
|
|
156
|
+
```text
|
|
157
|
+
process.argv -> src/bootstrap/index.ts -> bootstrap/cli/runner.ts -> icore terminal app -> command registry -> typed command options -> command handler
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Runner использует двухфазный flow `prepare -> runPrepared`, чтобы вывести warnings после command resolution без повторного разбора argv. Policy из `bootstrap/cli/error.ts` обрабатывает ошибки всех terminal-фаз. `isUsageError()` из `icore` распознаёт framework usage errors и публичный `CliUsageError` от project validators; для них exit code равен `2`. Runtime и command-definition errors получают exit code `1`.
|
|
161
|
+
|
|
162
|
+
Command-specific primitive options описываются декларативными `icore` schemas в `src/bootstrap/commands/**`. Общие SDK options нормализуются в `src/bootstrap/args/**`. Эти модули не должны создавать SDK clients, вызывать API или форматировать reports.
|
|
163
|
+
|
|
164
|
+
После `icore` validation command handler работает с typed command options. Raw CLI option maps не должны передаваться ни в command-local parser helpers, ни в request builders. Project-specific `parse*` helper может преобразовывать отдельное уже типизированное значение, например RFC 3339 date-time или comma-separated список. Mapping typed options в generated request DTO должен жить в `create*Request` helper-е.
|
|
165
|
+
|
|
166
|
+
## Mapping
|
|
167
|
+
|
|
168
|
+
Текущий flow API-команды:
|
|
169
|
+
|
|
170
|
+
```text
|
|
171
|
+
process.argv
|
|
172
|
+
-> icore terminal app
|
|
173
|
+
-> icore schema parser/validator
|
|
174
|
+
-> typed command options
|
|
175
|
+
-> project API-specific validation
|
|
176
|
+
-> generated request DTO
|
|
177
|
+
-> generated SDK call
|
|
178
|
+
-> application report или command-local stream event contract
|
|
179
|
+
-> CLI output
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Где должен жить mapping:
|
|
183
|
+
|
|
184
|
+
| Mapping | Текущее место | Возможное целевое место |
|
|
185
|
+
| --- | --- | --- |
|
|
186
|
+
| typed command options -> `TInvestOptions` | `bootstrap/args` | без изменений |
|
|
187
|
+
| typed command options -> generated request DTO | command-local `cli.ts` или `request.mapper.ts`, `create*Request` | application use-case, если command перестает быть тонким adapter-ом |
|
|
188
|
+
| generated unary response -> application report | `bootstrap/commands/*/reporter.ts` | CLI adapter или application use-case, зависит от выбранной границы |
|
|
189
|
+
| stream event -> command-local event contract | `bootstrap/commands/stream-run/reporter.ts` | application report, если contract потребуется вне CLI |
|
|
190
|
+
| report/event contract -> command-specific output values | `bootstrap/commands/*/reporter.ts` | без изменений для компактного Inventory-style CLI |
|
|
191
|
+
| output values -> JSON/CSV/table | публичные `renderJson`, `renderCsv`, `renderCsvRow`, `renderTextTable` из `icore`, вызываемые reporter-ами | command-specific поля и структура остаются в reporter-е |
|
|
192
|
+
| string/stream -> stdout | `icore` `TerminalApp`/`Output.write`, собираемые в `bootstrap/cli/runner.ts` | штатный normal output wiring остается в runner-е |
|
|
193
|
+
| warning/error -> stderr | `icore` `Output.error`; project CLI/error policy владеет содержанием | без изменений |
|
|
194
|
+
|
|
195
|
+
## Типичные ошибки
|
|
196
|
+
|
|
197
|
+
- передавать raw CLI args глубже bootstrap boundary;
|
|
198
|
+
- смешивать raw CLI parsing и generated request DTO mapping в одной функции;
|
|
199
|
+
- форматировать пользовательский output внутри application report contract;
|
|
200
|
+
- класть JSON/CSV/table logic в stdout sink;
|
|
201
|
+
- считать generated DTO стабильным CLI output contract;
|
|
202
|
+
- создавать generic DTO только ради красивой структуры.
|
|
203
|
+
|
|
106
204
|
## Короткие правила
|
|
107
205
|
|
|
206
|
+
- DTO и reports - это boundary contracts, а не domain models.
|
|
207
|
+
- Application reports стабильны и transport-neutral.
|
|
108
208
|
- `application` описывает application-level контракт, а не формат пользовательского вывода.
|
|
109
209
|
- Provider/gRPC mapping не должен протекать в чистые application contracts.
|
|
110
210
|
- Bootstrap может вызывать application, но application не импортирует bootstrap.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Разделение форматирования и вывода в CLI
|
|
2
2
|
|
|
3
|
-
> Type: Design Note. Здесь
|
|
3
|
+
> Type: Design Note. Здесь описаны project adapters, направление зависимостей и граница между command-specific CLI formatting, общей механикой JSON/CSV/table из `icore` и доставкой готового результата через `Output`.
|
|
4
4
|
|
|
5
5
|
## Контекст
|
|
6
6
|
|
|
@@ -8,35 +8,29 @@ CLI-команды живут в `bootstrap`, но не вся логика во
|
|
|
8
8
|
|
|
9
9
|
`icore` предоставляет общую механику как внешняя зависимость. Это не слой проекта: application reports и output contract конкретной команды остаются в SDK.
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Актуальная карта слоёв находится в [архитектуре SDK](../architecture.md#карта-слоев). Адаптеры переводят внутренние contracts во внешний интерфейс и обратно; command-specific CLI adapters находятся рядом с командами в `bootstrap`.
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
renderCsv
|
|
35
|
-
renderCsvRow
|
|
36
|
-
renderTextTable
|
|
37
|
-
TerminalApp
|
|
38
|
-
Output
|
|
39
|
-
```
|
|
13
|
+
## Адаптеры проекта
|
|
14
|
+
|
|
15
|
+
`infrastructure/transport/grpc` - технический adapter к `nice-grpc`:
|
|
16
|
+
|
|
17
|
+
- channel;
|
|
18
|
+
- metadata;
|
|
19
|
+
- middleware;
|
|
20
|
+
- typed clients;
|
|
21
|
+
- mapping gRPC method path в transport-neutral `TInvestUnaryQuota`;
|
|
22
|
+
- mapping `nice-grpc` client failures в transport-neutral `SdkError`.
|
|
23
|
+
|
|
24
|
+
`unary-limit-resolver.ts` выбирает method rule или service fallback и разрешает quota bucket. Middleware передаёт Consumer-owned limiter-у полный `path`, `bucket`, `maxRequests`, `windowMs` и `AbortSignal`. Application port не разбирает gRPC path и не владеет transport lifecycle.
|
|
25
|
+
|
|
26
|
+
`infrastructure/interceptor` содержит технический process hook для известных warnings. Обычный вывод команд проходит через terminal app.
|
|
27
|
+
|
|
28
|
+
`infrastructure/report-values.ts` - принадлежащий проекту адаптер скалярных значений:
|
|
29
|
+
|
|
30
|
+
- преобразует повторяющиеся provider scalar DTO values в reusable report values;
|
|
31
|
+
- сохраняет `MoneyValue` в JSON как структурный `ReportMoney`;
|
|
32
|
+
- предоставляет text helper для table cells вида `"amount currency"`;
|
|
33
|
+
- не знает command names, report shapes, columns, generic renderers или output delivery.
|
|
40
34
|
|
|
41
35
|
## Основная граница
|
|
42
36
|
|
|
@@ -94,6 +88,8 @@ icore TerminalApp -> Output.write
|
|
|
94
88
|
stdout
|
|
95
89
|
```
|
|
96
90
|
|
|
91
|
+
Runner создаёт default `Output` или принимает injected `Output`, собирает lightweight terminal app для shortcuts и external errors и лениво загружает command registry.
|
|
92
|
+
|
|
97
93
|
Runner отдельно управляет публичными short aliases, help/version shortcuts и command warnings. Он направляет help/version через lightweight terminal app, warnings — через command terminal app, а normal command result передаёт в `runPrepared`. Оба экземпляра используют один `Output` и одну error policy.
|
|
98
94
|
|
|
99
95
|
Штатный terminal flow идёт через `Output` из `icore`. Только крайний аварийный fallback в executable entrypoint пишет через `console.error`.
|
|
@@ -199,6 +195,53 @@ Technical mechanics необоснованно дублируется в reporte
|
|
|
199
195
|
- повторяет расчет ширины таблицы;
|
|
200
196
|
- пишет normal result напрямую в `process.stdout`, хотя достаточно вернуть его terminal app.
|
|
201
197
|
|
|
198
|
+
## Направление зависимостей
|
|
199
|
+
|
|
200
|
+
Допустимо:
|
|
201
|
+
|
|
202
|
+
```text
|
|
203
|
+
bootstrap/commands/*/reporter.ts -> application/reports
|
|
204
|
+
bootstrap/commands/*/reporter.ts -> infrastructure/report-values.ts
|
|
205
|
+
bootstrap/commands/*/reporter.ts -> icore presentation primitives
|
|
206
|
+
bootstrap/cli/runner.ts -> icore TerminalApp/Output
|
|
207
|
+
infrastructure/report-values.ts -> application/reports
|
|
208
|
+
infrastructure/transport/grpc -> application services/contracts
|
|
209
|
+
infrastructure/unary resolver -> application TInvestUnaryQuota
|
|
210
|
+
infrastructure/grpc middleware -> application TInvestUnaryLimiter
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Недопустимо:
|
|
214
|
+
|
|
215
|
+
```text
|
|
216
|
+
application -> bootstrap/commands/*/reporter.ts
|
|
217
|
+
application -> icore CLI/presentation mechanics
|
|
218
|
+
infrastructure/report-values.ts -> command-specific report formatting
|
|
219
|
+
generic output facade -> выбор полей или JSON contract команды
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Прямой import `icore` из `bootstrap` не меняет направление project layers: bootstrap остаётся внешним composition/presentation слоем и связывает external mechanics с локальными contracts.
|
|
223
|
+
|
|
224
|
+
## История перехода
|
|
225
|
+
|
|
226
|
+
Текущая модель сложилась после переноса общей механики presentation/output в `icore`:
|
|
227
|
+
|
|
228
|
+
1. Project-owned generic renderers и stdout/stderr writers удалены.
|
|
229
|
+
2. Reporter-ы вызывают публичные `icore` render primitives напрямую, без локальных forwarding wrappers.
|
|
230
|
+
3. Bootstrap CLI собирает `TerminalApp` и `Output`, но сохраняет project-owned alias inventory, help/version shortcuts, warnings и error policy; command aliases передаются в canonical definitions и разрешаются самим `icore`.
|
|
231
|
+
4. `application/reports`, command-specific presentation и `infrastructure/report-values.ts` остались project-owned contracts.
|
|
232
|
+
|
|
233
|
+
Отдельный use-case слой понадобится, только если command перестанет быть простой обёрткой над одним SDK call.
|
|
234
|
+
|
|
235
|
+
## Короткое правило
|
|
236
|
+
|
|
237
|
+
Если код отвечает на вопрос "что и как показать для конкретной команды", это command reporter.
|
|
238
|
+
|
|
239
|
+
Если код отвечает на вопрос "как механически сериализовать выбранные значения", используйте подходящий public primitive `icore`.
|
|
240
|
+
|
|
241
|
+
Если код отвечает на вопрос "как доставить готовый результат", это `TerminalApp`/`Output`, собранные в CLI runner-е.
|
|
242
|
+
|
|
243
|
+
Если код отвечает на вопрос "какой сценарий выполнить", это application use-case.
|
|
244
|
+
|
|
202
245
|
## Итог
|
|
203
246
|
|
|
204
247
|
```text
|
|
@@ -1,126 +1,35 @@
|
|
|
1
1
|
# DTO и отчёты
|
|
2
2
|
|
|
3
|
-
> Type:
|
|
3
|
+
> Type: Navigation. Материал объединён с описанием application-слоя. Прежние разделы ведут к соответствующим частям общего документа.
|
|
4
4
|
|
|
5
5
|
## Кратко
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
- proto-generated DTO из `src/generated/*.ts`;
|
|
10
|
-
- application DTO из `src/application/dto/**`;
|
|
11
|
-
- application report contracts из `src/application/reports/**`;
|
|
12
|
-
- CLI command option schemas из `src/bootstrap/commands/**` и общие SDK options из `src/bootstrap/args/**`.
|
|
7
|
+
[Кратко](./application.md#контракты-и-dto).
|
|
13
8
|
|
|
14
9
|
## Сгенерированные DTO
|
|
15
10
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
Это wire contracts внешнего API. Их нельзя редактировать вручную и нельзя использовать как место для project-specific правил.
|
|
19
|
-
|
|
20
|
-
Допустимо:
|
|
21
|
-
|
|
22
|
-
- импортировать generated types в infrastructure adapters;
|
|
23
|
-
- использовать generated service definitions при создании gRPC clients внутри bootstrap/infrastructure;
|
|
24
|
-
- использовать generated request/response DTO в package-owned public service interfaces SDK facade.
|
|
25
|
-
|
|
26
|
-
Нежелательно:
|
|
27
|
-
|
|
28
|
-
- делать generated DTO основой новых application reports;
|
|
29
|
-
- добавлять handwritten mapping или helpers в generated файлы;
|
|
30
|
-
- завязывать CLI output format на нестабильный generated JSON shape.
|
|
31
|
-
- экспортировать generated service clients как root public API.
|
|
32
|
-
|
|
33
|
-
Исключение — server-side generated `*ServiceDefinition` и `*ServiceImplementation`. Они входят в root public API, потому что пакет поддерживает nice-grpc server adapters у Consumers.
|
|
11
|
+
[Сгенерированные DTO](./application.md#сгенерированные-dto).
|
|
34
12
|
|
|
35
13
|
## DTO уровня application
|
|
36
14
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
Это не CLI DTO и не gRPC DTO. Один и тот же contract может использоваться из bootstrap, tests и публичного SDK facade.
|
|
40
|
-
|
|
41
|
-
Правило:
|
|
42
|
-
|
|
43
|
-
```text
|
|
44
|
-
CLI/env parsing -> TInvestOptions -> SDK facade/infrastructure
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
`application/dto` не должен читать env и не должен знать про CLI flags.
|
|
48
|
-
|
|
49
|
-
`src/application/dto/t-invest-services.ts` описывает публичные service interfaces SDK facade: `UsersService`, `OrdersService`, `MarketDataStreamService` и другие. Эти interfaces сохраняют upstream method names и generated request/response DTO, но не раскрывают `nice-grpc` `*ServiceClient`, `*ServiceDefinition`, `CallOptions` или `CallContext`.
|
|
15
|
+
[DTO уровня application](./application.md#dto-уровня-application).
|
|
50
16
|
|
|
51
17
|
## Отчёты
|
|
52
18
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
Reports отвечают на вопрос:
|
|
56
|
-
|
|
57
|
-
```text
|
|
58
|
-
что команда сообщает наружу?
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
Они не отвечают на вопрос:
|
|
62
|
-
|
|
63
|
-
```text
|
|
64
|
-
как это вывести в JSON, CSV, table или stdout?
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
Форматирование должно жить во внешнем adapter/presentation слое.
|
|
19
|
+
[Отчёты](./application.md#отчёты).
|
|
68
20
|
|
|
69
21
|
## Входные данные CLI
|
|
70
22
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
```text
|
|
74
|
-
process.argv -> src/bootstrap/index.ts -> bootstrap/cli/runner.ts -> icore terminal app -> command registry -> typed command options -> command handler
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
Runner использует двухфазный flow `prepare -> runPrepared`, чтобы вывести warnings после command resolution без повторного разбора argv. Policy из `bootstrap/cli/error.ts` обрабатывает ошибки всех terminal-фаз. `isUsageError()` из `icore` распознаёт framework usage errors и публичный `CliUsageError` от project validators; для них exit code равен `2`. Runtime и command-definition errors получают exit code `1`.
|
|
78
|
-
|
|
79
|
-
Command-specific primitive options описываются декларативными `icore` schemas в `src/bootstrap/commands/**`. Общие SDK options нормализуются в `src/bootstrap/args/**`. Эти модули не должны создавать SDK clients, вызывать API или форматировать reports.
|
|
80
|
-
|
|
81
|
-
После `icore` validation command handler работает с typed command options. Raw CLI option maps не должны передаваться ни в command-local parser helpers, ни в request builders. Project-specific `parse*` helper может преобразовывать отдельное уже типизированное значение, например RFC 3339 date-time или comma-separated список. Mapping typed options в generated request DTO должен жить в `create*Request` helper-е.
|
|
23
|
+
[Входные данные CLI](./application.md#входные-данные-cli).
|
|
82
24
|
|
|
83
25
|
## Mapping
|
|
84
26
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
```text
|
|
88
|
-
process.argv
|
|
89
|
-
-> icore terminal app
|
|
90
|
-
-> icore schema parser/validator
|
|
91
|
-
-> typed command options
|
|
92
|
-
-> project API-specific validation
|
|
93
|
-
-> generated request DTO
|
|
94
|
-
-> generated SDK call
|
|
95
|
-
-> application report или command-local stream event contract
|
|
96
|
-
-> CLI output
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
Где должен жить mapping:
|
|
100
|
-
|
|
101
|
-
| Mapping | Текущее место | Возможное целевое место |
|
|
102
|
-
| --- | --- | --- |
|
|
103
|
-
| typed command options -> `TInvestOptions` | `bootstrap/args` | без изменений |
|
|
104
|
-
| typed command options -> generated request DTO | command-local `cli.ts` или `request.mapper.ts`, `create*Request` | application use-case, если command перестает быть тонким adapter-ом |
|
|
105
|
-
| generated unary response -> application report | `bootstrap/commands/*/reporter.ts` | CLI adapter или application use-case, зависит от выбранной границы |
|
|
106
|
-
| stream event -> command-local event contract | `bootstrap/commands/stream-run/reporter.ts` | application report, если contract потребуется вне CLI |
|
|
107
|
-
| report/event contract -> command-specific output values | `bootstrap/commands/*/reporter.ts` | без изменений для компактного Inventory-style CLI |
|
|
108
|
-
| output values -> JSON/CSV/table | публичные `renderJson`, `renderCsv`, `renderCsvRow`, `renderTextTable` из `icore`, вызываемые reporter-ами | command-specific поля и структура остаются в reporter-е |
|
|
109
|
-
| string/stream -> stdout | `icore` `TerminalApp`/`Output.write`, собираемые в `bootstrap/cli/runner.ts` | штатный normal output wiring остается в runner-е |
|
|
110
|
-
| warning/error -> stderr | `icore` `Output.error`; project CLI/error policy владеет содержанием | без изменений |
|
|
27
|
+
[Mapping](./application.md#mapping).
|
|
111
28
|
|
|
112
29
|
## Типичные ошибки
|
|
113
30
|
|
|
114
|
-
|
|
115
|
-
- смешивать raw CLI parsing и generated request DTO mapping в одной функции;
|
|
116
|
-
- форматировать пользовательский output внутри application report contract;
|
|
117
|
-
- класть JSON/CSV/table logic в stdout sink;
|
|
118
|
-
- считать generated DTO стабильным CLI output contract;
|
|
119
|
-
- создавать generic DTO только ради красивой структуры.
|
|
31
|
+
[Типичные ошибки](./application.md#типичные-ошибки).
|
|
120
32
|
|
|
121
33
|
## Резюме
|
|
122
34
|
|
|
123
|
-
|
|
124
|
-
- Generated contracts принадлежат proto workflow.
|
|
125
|
-
- Application reports стабильны и transport-neutral.
|
|
126
|
-
- CLI formatting должен быть отделен от записи в stdout.
|
|
35
|
+
[Резюме](./application.md#короткие-правила).
|