@radandevist/conventions 0.0.0-stage → 0.1.0
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/LICENSE +201 -0
- package/README.md +31 -2
- package/package.json +32 -5
- package/rules/architecture/design-patterns.md +298 -0
- package/rules/architecture/ports-and-adapters.md +169 -0
- package/rules/architecture/solid.md +110 -0
- package/rules/ci.md +91 -0
- package/rules/index.md +11 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @radandevist/conventions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Shared rules and the tooling that enforces them, for Radan's own projects (PublyApp, ShopKartOS,
|
|
4
|
+
radan-ui, and future personal projects).
|
|
5
|
+
|
|
6
|
+
The design is the reference document:
|
|
7
|
+
[docs/design/2026-11-21-conventions-design.md](docs/design/2026-11-21-conventions-design.md).
|
|
8
|
+
|
|
9
|
+
Rules:
|
|
10
|
+
|
|
11
|
+
- [Index of all rules](rules/index.md) — the single entry point projects link to.
|
|
12
|
+
- [CI rules](rules/ci.md) — fast, honest CI (two gates, budgets, how to make it fast).
|
|
13
|
+
- [Ports and adapters](rules/architecture/ports-and-adapters.md) — service → small ports (interface segregation) → `<Library><Function>Adapter`.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pnpm add -D @radandevist/conventions@<exact-version>
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Pin an exact version. The package currently ships the rule texts only (`rules/`). The ratchet CLI and the
|
|
22
|
+
catalog check come in 0.2.0.
|
|
23
|
+
|
|
24
|
+
## Releasing
|
|
25
|
+
|
|
26
|
+
Versions are released from CI with [changesets](https://github.com/changesets/changesets) and npm Trusted
|
|
27
|
+
Publishing (no token). 0.1.0 was published by hand once.
|
|
28
|
+
|
|
29
|
+
1. In a PR, run `pnpm changeset` and commit the file (never an empty changeset).
|
|
30
|
+
2. Merge the PR. The release workflow opens or updates a `chore: version packages` PR.
|
|
31
|
+
3. Close and reopen that PR so CI runs (PRs from the Actions bot do not trigger it), then merge it.
|
|
32
|
+
4. The workflow publishes to npm, tags `vX.Y.Z` and creates the GitHub release.
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@radandevist/conventions",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Shared rules and tools for Radan's personal projects.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/radandevist/conventions.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/radandevist/conventions#readme",
|
|
11
|
+
"bugs": "https://github.com/radandevist/conventions/issues",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22"
|
|
15
|
+
},
|
|
16
|
+
"packageManager": "pnpm@10.13.1",
|
|
17
|
+
"files": [
|
|
18
|
+
"rules",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"changeset": "changeset",
|
|
27
|
+
"version-packages": "changeset version",
|
|
28
|
+
"release": "changeset publish"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@changesets/cli": "^3.0.3"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# Design patterns
|
|
2
|
+
|
|
3
|
+
Rules for every personal project (PublyApp, ShopKartOS, radan-ui, future ones), in TypeScript and in
|
|
4
|
+
.NET. Never DigitalPrevention. Written for agents; each rule says why. Owner decision of 2026-11-25.
|
|
5
|
+
Examples marked "example from PublyApp" are illustrations, not a list to copy.
|
|
6
|
+
|
|
7
|
+
"The book" is *Design Patterns: Elements of Reusable Object-Oriented Software* (Gamma, Helm, Johnson,
|
|
8
|
+
Vlissides). Its two principles:
|
|
9
|
+
|
|
10
|
+
- **Program to an interface, not an implementation.** Callers depend on the contract they use, so the
|
|
11
|
+
implementation can change. "Interface" means a supertype or a small role type, not an interface per
|
|
12
|
+
class: do not add one where there is no second implementation and no test seam.
|
|
13
|
+
- **Prefer composition to inheritance.** Assemble behaviour from small objects instead of building a
|
|
14
|
+
deep class tree. Inheritance is still right for a genuine is-a with a fixed skeleton (see Template
|
|
15
|
+
Method), not for reusing a method.
|
|
16
|
+
|
|
17
|
+
The « I » and « D » seam of SOLID is [ports and adapters](ports-and-adapters.md), the detailed rule for
|
|
18
|
+
services, ports and adapters; this page names the shapes that sit on that seam.
|
|
19
|
+
|
|
20
|
+
**A pattern answers a problem; no problem, no pattern.** A pattern is a name for a shape the code
|
|
21
|
+
already needs, never a target. YAGNI: the cheapest pattern is the code you did not add. Scan the table
|
|
22
|
+
for the sign you actually see; open a card only when the sign is real. Two entries are not GoF patterns
|
|
23
|
+
(Simple Factory, Null Object) and are marked as such.
|
|
24
|
+
|
|
25
|
+
## Sign → pattern
|
|
26
|
+
|
|
27
|
+
| Sign in the code | Pattern |
|
|
28
|
+
| --------------------------------------------------------------------------------- | -------------------------------- |
|
|
29
|
+
| A vendor SDK/API type leaks into business code, or two classes call the same API | Adapter |
|
|
30
|
+
| A layer below the service must wrap an interface and compose (sink, cache, metrics) | Decorator |
|
|
31
|
+
| The same interface needs access control, lazy load, or a security gate | Proxy |
|
|
32
|
+
| Ordered checks, each may stop or pass, and the list changes per route | Chain of Responsibility |
|
|
33
|
+
| One event must reach listeners the publisher does not know | Observer |
|
|
34
|
+
| A `switch`/`if` on a kind chooses an algorithm, and new cases keep arriving | Strategy |
|
|
35
|
+
| The same skeleton, with steps that vary per case | Template Method |
|
|
36
|
+
| Callers must reach a multi-class subsystem through one entry point | Facade |
|
|
37
|
+
| A function or keyed method picks the concrete implementation at one boundary | Simple Factory (non-GoF; default) |
|
|
38
|
+
| A creator class lets subclasses decide which product one create step returns | Factory Method (GoF) |
|
|
39
|
+
| A request must be stored, queued, retried, or undone later | Command |
|
|
40
|
+
| An optional collaborator forces `if (x is not null)` around every call | Null Object (non-GoF) |
|
|
41
|
+
|
|
42
|
+
## Adapter
|
|
43
|
+
|
|
44
|
+
**Sign.** A vendor type (`Resend`, `HttpClient`, a browser global) appears in business code; two classes
|
|
45
|
+
call the same external API; tests cannot run without the vendor.
|
|
46
|
+
|
|
47
|
+
**Shape.** One port for our need; one adapter per library, translating only. Example: `ResendEmailAdapter`
|
|
48
|
+
implements `IEmailSender`; `EmailService` calls the port and never the vendor.
|
|
49
|
+
```csharp
|
|
50
|
+
public interface IEmailSender {
|
|
51
|
+
Task<EmailSendReceipt> SendAsync(EmailRequest request, string? idempotencyKey = null, CancellationToken ct = default);
|
|
52
|
+
}
|
|
53
|
+
public class ResendEmailAdapter : IEmailSender { /* Resend types stay here */ }
|
|
54
|
+
```
|
|
55
|
+
**When NOT.** A pure library used directly; one implementation with no swap and no fake; a forwarding adapter.
|
|
56
|
+
**Close cousins.** Decorator (adds behaviour); Proxy (access control); Facade (several subsystems).
|
|
57
|
+
|
|
58
|
+
## Strategy
|
|
59
|
+
|
|
60
|
+
**Sign.** A `switch`/`if` on a kind chooses what to do; every new case edits several files; the caller
|
|
61
|
+
knows every concrete implementation.
|
|
62
|
+
|
|
63
|
+
**Shape.** One small interface, one implementation per case, one registry that picks. Example from
|
|
64
|
+
PublyApp: `ISocialPublisher` implementations are indexed by `SocialAdapterRegistry`. The publish job
|
|
65
|
+
still injects `IPublishProvider` directly: that is a gap against [ports and adapters](ports-and-adapters.md),
|
|
66
|
+
not a shape that already follows it. The target is a `PublishService` the job calls; the service owns
|
|
67
|
+
the journal and transitions and calls the port.
|
|
68
|
+
```csharp
|
|
69
|
+
public interface ISocialPublisher {
|
|
70
|
+
IReadOnlySet<SocialProvider> Networks { get; }
|
|
71
|
+
Task<PublishResult> PublishAsync(PublishRequest request, CancellationToken ct);
|
|
72
|
+
Task<ReconcileResult> ReconcileAsync(ReconcileRequest request, CancellationToken ct);
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
**When NOT.** One fixed algorithm; two branches unlikely to grow; the choice is made once at startup. A
|
|
76
|
+
kind → data lookup is a table, not a class per kind.
|
|
77
|
+
**Close cousins.** State (self-transition); Factory (creates the strategy); Adapter (different interface).
|
|
78
|
+
|
|
79
|
+
## Facade (the service plays this role)
|
|
80
|
+
|
|
81
|
+
**Sign.** Callers must use several interfaces of one subsystem together; the same multi-step sequence
|
|
82
|
+
and its order repeat at every caller.
|
|
83
|
+
|
|
84
|
+
**Shape.** The book's Facade is a unified interface over a set of interfaces in a subsystem: one entry
|
|
85
|
+
point, the subsystem still does the work. In our code the **service** is that entry point, as defined by
|
|
86
|
+
[ports and adapters](ports-and-adapters.md). Example from PublyApp: `EmailService` owns render + send;
|
|
87
|
+
`Analytics` owns consent + mask + failure containment before the adapter. These are services, not a
|
|
88
|
+
separate "Facade" class: do not add a Facade on top of them, and do not call every service a Facade to
|
|
89
|
+
add.
|
|
90
|
+
```ts
|
|
91
|
+
export class Analytics {
|
|
92
|
+
readonly #adapter: IAnalytics;
|
|
93
|
+
readonly #hasConsent: AnalyticsConsent;
|
|
94
|
+
|
|
95
|
+
constructor(adapter: IAnalytics, hasConsent: AnalyticsConsent) {
|
|
96
|
+
this.#adapter = adapter;
|
|
97
|
+
this.#hasConsent = hasConsent;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async send(event: AnalyticsEvent): Promise<boolean> {
|
|
101
|
+
try {
|
|
102
|
+
if (!this.#hasConsent()) return false;
|
|
103
|
+
await this.#adapter.send(maskAnalyticsEvent(event));
|
|
104
|
+
return true;
|
|
105
|
+
} catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
**When NOT.** A pass-through with one method and one caller; the sequence is one call already; PublyApp
|
|
112
|
+
has no separate multi-subsystem Facade object, the service covers the role.
|
|
113
|
+
**Close cousins.** Adapter (one interface); Mediator (colleagues talk through a hub); Decorator (adds behaviour).
|
|
114
|
+
|
|
115
|
+
## Decorator
|
|
116
|
+
|
|
117
|
+
**Sign.** Behaviour must wrap an implementation and compose at a layer that is not already a service
|
|
118
|
+
rule — a sink in front of every durable sink, a cache, metrics — without editing the wrapped code; the
|
|
119
|
+
wrapper has the same interface and adds one concern.
|
|
120
|
+
|
|
121
|
+
**Shape.** Same interface, one wrapped field, delegate then change. Example: `SanitizingLogEventSink`
|
|
122
|
+
wraps another `ILogEventSink`; `SanitizingSinkConfigurationExtensions` puts it in front of every durable
|
|
123
|
+
sink. It is the process-wide redaction **backstop** at the Serilog sink layer, below the adapter, not the
|
|
124
|
+
template for wrapping a port.
|
|
125
|
+
```csharp
|
|
126
|
+
public sealed class SanitizingLogEventSink : ILogEventSink {
|
|
127
|
+
private readonly ILogEventSink _Wrapped;
|
|
128
|
+
public void Emit(LogEvent logEvent) => this._Wrapped.Emit(_Sanitize(logEvent));
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
**When NOT.** Redaction, consent, validation and retry are service rules, done once before the port
|
|
132
|
+
([ports and adapters](ports-and-adapters.md)); a `RedactingEmailSender` around a port leaks on one missed
|
|
133
|
+
wrapper. Not for one fixed wrapper either.
|
|
134
|
+
**Close cousins.** Proxy (controls access, not behaviour); Adapter (different interface); Chain (several handlers).
|
|
135
|
+
|
|
136
|
+
## Proxy
|
|
137
|
+
|
|
138
|
+
**Sign.** The same interface as the real object, but the surrogate controls access, loads lazily, logs, or
|
|
139
|
+
hides forbidden entries; the caller must not know.
|
|
140
|
+
|
|
141
|
+
**Shape.** Same interface, one inner object, one gate. Example from PublyApp:
|
|
142
|
+
`ReparsePointExclusionFileProvider` wraps `PhysicalFileProvider` and returns "not found" for symlinked
|
|
143
|
+
paths, so the static-file middleware cannot serve outside the uploads root.
|
|
144
|
+
```csharp
|
|
145
|
+
public IFileInfo GetFileInfo(string subpath) {
|
|
146
|
+
var info = this._Inner.GetFileInfo(subpath);
|
|
147
|
+
return !info.Exists || _HasReparsePointInPath(info.PhysicalPath, subpath, out _)
|
|
148
|
+
? new NotFoundFileInfo(info.Name) : info;
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
**When NOT.** You can fix the real object; the gate is business logic that belongs in a service; you are
|
|
152
|
+
adding behaviour rather than controlling access (that is Decorator).
|
|
153
|
+
**Close cousins.** Decorator (adds behaviour); Adapter (changes interface); Facade (hides a subsystem).
|
|
154
|
+
|
|
155
|
+
## Simple Factory (non-GoF; our default)
|
|
156
|
+
|
|
157
|
+
**Sign.** `new` picks a concrete implementation from config, env or a kind at one boundary; callers must
|
|
158
|
+
not import the concrete types; the same construction is duplicated in several files.
|
|
159
|
+
|
|
160
|
+
**Shape.** One function or static method returns the port; the choice lives there. There is no creator
|
|
161
|
+
hierarchy and no overridable step, so this is not GoF Factory Method. Example: `resolveAdapter` returns the
|
|
162
|
+
logger adapter for the environment; `CursorSortFieldHandlerFactory.Create` builds a cursor handler from
|
|
163
|
+
two selectors. Both are Simple Factory.
|
|
164
|
+
```ts
|
|
165
|
+
export const resolveAdapter = (env: LogEnv, server: boolean): ILogger => {
|
|
166
|
+
if (env.LOG_ADAPTER === 'winston') return winstonAdapter(server);
|
|
167
|
+
if (env.LOG_ADAPTER === 'json') return new StdoutJsonLoggerAdapter();
|
|
168
|
+
return autoAdapter(env, server);
|
|
169
|
+
};
|
|
170
|
+
```
|
|
171
|
+
**When NOT.** One concrete type; no choice; `new` at the composition edge is already clear. Do not add a
|
|
172
|
+
factory for a class that will never have a second implementation.
|
|
173
|
+
**Close cousins.** Factory Method (creator subclass hook); Abstract Factory (product family); Strategy (runtime choice).
|
|
174
|
+
|
|
175
|
+
## Factory Method (GoF)
|
|
176
|
+
|
|
177
|
+
**Sign.** A creator class defines the algorithm and one create step, and subclasses decide which product
|
|
178
|
+
that step returns; callers use the creator, never the constructor.
|
|
179
|
+
|
|
180
|
+
**Shape.** A concrete method owns the flow and calls a protected abstract create step. PublyApp has no
|
|
181
|
+
GoF Factory Method today: the two factories above are Simple Factory. Add this only when a creator
|
|
182
|
+
genuinely has subclasses that pick different products.
|
|
183
|
+
```ts
|
|
184
|
+
export abstract class ReportExporter {
|
|
185
|
+
export(report: string): string {
|
|
186
|
+
return this.createWriter().write(report);
|
|
187
|
+
}
|
|
188
|
+
protected abstract createWriter(): { write(report: string): string };
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
**When NOT.** One product; the choice is a keyed lookup (Simple Factory); no subclass will override the
|
|
192
|
+
step. Naming a switch function "Factory Method" makes an agent implement the wrong pattern.
|
|
193
|
+
**Close cousins.** Simple Factory (one function chooses); Abstract Factory (product family); Template Method (the skeleton).
|
|
194
|
+
|
|
195
|
+
## Template Method
|
|
196
|
+
|
|
197
|
+
**Sign.** The same skeleton repeats with one or two steps varying; subclasses would copy the transaction,
|
|
198
|
+
retry or logging around a different body.
|
|
199
|
+
|
|
200
|
+
**Shape.** A non-virtual public method owns the skeleton; protected abstract steps fill it. Example from
|
|
201
|
+
PublyApp: `EmailJobHandlerBase<TPayload>.HandleAsync` owns the transaction, idempotency and provider
|
|
202
|
+
contract; five handlers implement `PrepareAsync`, `ResolveTerminalIdentityAsync` and `Kind`.
|
|
203
|
+
```csharp
|
|
204
|
+
public abstract class EmailJobHandlerBase<TPayload> : IJobHandler {
|
|
205
|
+
public async Task<JobOutcome> HandleAsync(JobContext context, CancellationToken ct) {
|
|
206
|
+
var preparation = await this.PrepareAsync(context.DeserializePayload<TPayload>(), ct);
|
|
207
|
+
// ... freeze, send, log, commit
|
|
208
|
+
}
|
|
209
|
+
protected abstract Task<EmailJobPreparation> PrepareAsync(TPayload payload, CancellationToken ct);
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
**When NOT.** Steps vary in order or can be skipped; composition can do it; the hierarchy is already deep.
|
|
213
|
+
**Close cousins.** Strategy (whole algorithm); Factory Method (one step creates a product); Hook (optional step).
|
|
214
|
+
|
|
215
|
+
## Chain of Responsibility
|
|
216
|
+
|
|
217
|
+
**Sign.** Ordered checks where each may stop or pass; the set or order changes per route; auth and
|
|
218
|
+
validation repeat before every handler.
|
|
219
|
+
|
|
220
|
+
**Shape.** Each handler does its check, then calls `next`; it returns early to stop. Example from PublyApp:
|
|
221
|
+
`SessionAuthFilter`, `TenantPermissionFilter` and the other endpoint filters in `apps/api/Lib/Filters`
|
|
222
|
+
call `next(context)`.
|
|
223
|
+
```csharp
|
|
224
|
+
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) {
|
|
225
|
+
var token = context.HttpContext.RequestServices.GetRequiredService<IRequestAuthContext>().SessionToken;
|
|
226
|
+
if (string.IsNullOrEmpty(token)) return TypedProblems.Unauthorized("Session token is missing", ResponseKeys.Unauthorized);
|
|
227
|
+
return await next(context);
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
**When NOT.** Two fixed steps; every step must always run; the framework already provides the pipeline.
|
|
231
|
+
**Close cousins.** Decorator (one wrapper, always delegates); Middleware (HTTP-level chain); Strategy (one chosen).
|
|
232
|
+
|
|
233
|
+
## Observer
|
|
234
|
+
|
|
235
|
+
**Sign.** One event must reach listeners the publisher does not know; UI or tabs must stay in sync; the
|
|
236
|
+
publisher must not import the subscribers.
|
|
237
|
+
|
|
238
|
+
**Shape.** A publish/subscribe pair: one side posts, the other subscribes and unsubscribes. Example:
|
|
239
|
+
`postBroadcast` publishes on a `BroadcastChannel`; `useBroadcastSync` subscribes for a component's
|
|
240
|
+
lifetime (auth, theme, locale sync). The platform owns the subject; our code is the seam.
|
|
241
|
+
```ts
|
|
242
|
+
export const postBroadcast = <T>(channelName: string, data: T): void => {
|
|
243
|
+
const channel = new BroadcastChannel(channelName);
|
|
244
|
+
channel.postMessage({ tab: TAB_ID, data });
|
|
245
|
+
channel.close();
|
|
246
|
+
};
|
|
247
|
+
```
|
|
248
|
+
**When NOT.** One known callee (call it); strict ordering or a transaction is required; an event bus is
|
|
249
|
+
used to avoid a direct dependency that is actually fine.
|
|
250
|
+
**Close cousins.** Mediator (a hub knows the colleagues); Pub/Sub (a cross-process broker); Chain (one path).
|
|
251
|
+
|
|
252
|
+
## Command
|
|
253
|
+
|
|
254
|
+
**Sign.** A request must be stored, queued, retried, audited or undone later; the invoker must not know
|
|
255
|
+
the receiver; work runs in another process.
|
|
256
|
+
|
|
257
|
+
**Shape.** A payload object is the command, a definition describes its type, an executor runs it. Example:
|
|
258
|
+
the tenant-invitation payload is the command and `JobDefinition<TPayload>` its type descriptor (`JobType`,
|
|
259
|
+
priority, attempts, validation); `IJobHandler` executes it by `JobType`, the queue owns retries.
|
|
260
|
+
**When NOT.** A synchronous in-process call with no retry, store or audit; a method call is enough.
|
|
261
|
+
|
|
262
|
+
## Null Object (non-GoF)
|
|
263
|
+
|
|
264
|
+
**Sign.** `if (x is not null)` around every call; an optional collaborator is passed as `null`; tests
|
|
265
|
+
invent a fake that does nothing.
|
|
266
|
+
|
|
267
|
+
**Shape.** A real implementation that does nothing, so callers call unconditionally. Example from
|
|
268
|
+
PublyApp: `BlueskySocialAdapter` (call in `BlueskySocialAdapter.Client.cs`) calls its logger without a null check and falls back to
|
|
269
|
+
`NullLogger<BlueskySocialAdapter>.Instance` at construction.
|
|
270
|
+
```csharp
|
|
271
|
+
this._Logger.LogError("Bluesky createSession returned unparseable JSON …", status); // no null check
|
|
272
|
+
this._Logger = logger ?? NullLogger<BlueskySocialAdapter>.Instance; // composition edge
|
|
273
|
+
```
|
|
274
|
+
**When NOT.** Absence is meaningful and must be handled; the no-op would hide a missing dependency or a
|
|
275
|
+
failed wiring; the operation must report an error. A required dependency should fail fast, so do not make
|
|
276
|
+
optional constructor injection the norm.
|
|
277
|
+
**Close cousins.** Proxy (controls access); Special Case (meaningful default); Optional (type says "may be absent").
|
|
278
|
+
|
|
279
|
+
## The other GoF patterns
|
|
280
|
+
|
|
281
|
+
- **Abstract Factory** — a family of related products must vary together (a theme kit, a cloud SDK family); we have no such family today.
|
|
282
|
+
- **Builder** — one immutable object has many optional parts and telescoping constructors; object initializers cover PublyApp today, so no builder.
|
|
283
|
+
- **Prototype** — configured instances are cloned instead of rebuilt; matters for expensive parsed templates, not for our small records.
|
|
284
|
+
- **Bridge** — abstraction and implementation both vary independently (a report type × an export format); two dimensions are the sign, not one.
|
|
285
|
+
- **Composite** — a part-whole tree where leaf and branch share an operation (nested menus, comment threads, org units); PublyApp has no such tree yet.
|
|
286
|
+
- **Flyweight** — many fine-grained objects share immutable state (glyphs, map tiles); a cache with a proven memory problem, not a guess.
|
|
287
|
+
- **Interpreter** — a small grammar must be parsed and evaluated (filters, query languages); a parser library is usually the cheaper answer.
|
|
288
|
+
- **Iterator** — traverse a collection without exposing its internals; C# `IAsyncEnumerable` and TS iterators already are the pattern, use them.
|
|
289
|
+
- **Mediator** — many colleagues communicate in complex ways and a hub simplifies them; a service that already owns the flow is a facade, not a mediator.
|
|
290
|
+
- **Memento** — undo or a snapshot must restore prior state; matters for editors, not for append-only rows.
|
|
291
|
+
- **State** — behaviour changes with an explicit state and the transitions are the point; an enum field plus a `switch` is enough until per-state behaviour appears.
|
|
292
|
+
- **Visitor** — a stable object tree gains new operations; our Roslyn analyzers traverse `DescendantNodes` in `packages/lint-cs`; a visitor pays only when several operations share one traversal.
|
|
293
|
+
|
|
294
|
+
## Singleton
|
|
295
|
+
|
|
296
|
+
Use the DI container lifetime: `AddSingleton<T>()` in C#, or one module-level instance in TypeScript.
|
|
297
|
+
Never a class with a static `Instance`. Example: `AddSocialAdapter<TAdapter>` registers one adapter as a
|
|
298
|
+
singleton and forwards every port it implements to that same instance.
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# Ports and adapters
|
|
2
|
+
|
|
3
|
+
Rules for every personal project (PublyApp, ShopKartOS, radan-ui, future ones), in TypeScript and in
|
|
4
|
+
.NET. Never DigitalPrevention. Written for agents; each rule says why. Owner decisions of 2026-11-24.
|
|
5
|
+
The names below (logger, e-mail, Mastodon) are examples taken from PublyApp, not a list to copy.
|
|
6
|
+
|
|
7
|
+
## 0. Scope
|
|
8
|
+
|
|
9
|
+
The rule covers code with **side effects or input/output**: logs, e-mail, SMS, analytics, external HTTP
|
|
10
|
+
APIs, file or blob storage, browser storage, queues, the console. Pure libraries (validation such as
|
|
11
|
+
zod, date or string helpers, UI frameworks) are used directly. Why: a port is worth its cost only where
|
|
12
|
+
you need to swap the outside world, fake it in tests, or apply a shared rule (redaction, consent)
|
|
13
|
+
before it leaves the process.
|
|
14
|
+
|
|
15
|
+
## 1. Three layers: service → port → adapters
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
your code ──► Service (what the code calls; does the shared work ONCE)
|
|
19
|
+
│
|
|
20
|
+
▼
|
|
21
|
+
IPort (a small interface: one need)
|
|
22
|
+
│
|
|
23
|
+
▼
|
|
24
|
+
<Library><Function>Adapter (one per library or API; only the outside call)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- **The service does the shared work once**: level filtering, redaction of personal data, consent,
|
|
28
|
+
validation, retries. Why: written once, it cannot be forgotten by one adapter. If every adapter
|
|
29
|
+
implemented the full contract, each would repeat that work, and one missing call would leak data.
|
|
30
|
+
- **A port covers one need** (interface segregation, the « I » of SOLID): one method, or a few methods
|
|
31
|
+
that are always used together. `ILogger.write(entry)`, `IEmailSender.SendAsync(request)`,
|
|
32
|
+
`ISocialPublisher.PublishAsync(post)`. Why: a caller depends only on what it uses, an adapter stays
|
|
33
|
+
small, and no interface grows into a god class.
|
|
34
|
+
- **An adapter only translates** for its library or API. It holds no business rule, no `if` on the
|
|
35
|
+
environment, no filtering and no redaction. Why: the adapters stay swappable and small.
|
|
36
|
+
- **One adapter per library or external API; it may implement several ports.** Two classes that call
|
|
37
|
+
the same API are a defect. Example: connecting an account and publishing both talk to Mastodon, so
|
|
38
|
+
one `MastodonSocialAdapter` implements `ISocialConnector` and `ISocialPublisher`. A network that can
|
|
39
|
+
only publish implements only `ISocialPublisher`, never a method that throws "not supported". Why: the
|
|
40
|
+
API's URLs, errors and tokens must be known in one place.
|
|
41
|
+
- **Business code (controllers, jobs, components) calls the service only**, never a port or an
|
|
42
|
+
adapter. The port is known by the service, the wiring and tests; adapters are known by the wiring
|
|
43
|
+
(`index.ts`, DI registration, or a small registry that picks the adapter per account or network) and
|
|
44
|
+
by tests. Why: then changing or adding an adapter touches the wiring alone, never a caller. The
|
|
45
|
+
service exists even when its shared work is small (a journal entry, encrypting a token): it is the
|
|
46
|
+
one place that work will grow.
|
|
47
|
+
- **Tests use a memory adapter** (`MemoryLoggerAdapter`, `MemoryEmailAdapter`) and assert on what it
|
|
48
|
+
received, never by spying on `console` or a global. Why: a spy still passes when the code stops
|
|
49
|
+
writing, so it cannot prove "written, and without the secret".
|
|
50
|
+
|
|
51
|
+
## 2. Names
|
|
52
|
+
|
|
53
|
+
- **Service: named for its function**: `Logger`, `EmailService`, `Analytics`. Why: it is what callers
|
|
54
|
+
see; the plain name reads best at the call site.
|
|
55
|
+
- **Port: `I` + the role it plays**, as a noun (the service does not implement its own port: `Logger`
|
|
56
|
+
uses an `ILogger` adapter, it is not one): `ILogger`, `IEmailSender`, `ISmsSender`,
|
|
57
|
+
`ISocialPublisher`. In .NET, never reuse a framework name (`Microsoft.Extensions.Logging.ILogger`):
|
|
58
|
+
pick another role noun (`ILogWriter`). Why: the name says what an adapter must be, and a clash with a
|
|
59
|
+
framework type causes wrong imports.
|
|
60
|
+
- **Adapter: library (or API, or medium) + function + `Adapter`**: `WinstonLoggerAdapter`,
|
|
61
|
+
`StdoutJsonLoggerAdapter`, `MemoryLoggerAdapter`, `PostHogAnalyticsAdapter`, `ResendEmailAdapter`,
|
|
62
|
+
`MastodonSocialAdapter`, `LocalDiskFileStorageAdapter`. Long is fine. Why: the name alone says what
|
|
63
|
+
it wraps, which job, and that it is an adapter. Do not use `…Provider`, `…Sink`, `…Transport`,
|
|
64
|
+
`…Client` or `…Store` for an adapter.
|
|
65
|
+
- **An environment variable names what it chooses**: `LOG_ADAPTER=winston|json`, not `LOG_SINK` or
|
|
66
|
+
`LOG_FORMAT`. Why: an adapter has exactly one output format, so the variable picks the adapter.
|
|
67
|
+
|
|
68
|
+
## 3. Files
|
|
69
|
+
|
|
70
|
+
- **TypeScript: the service, port and adapter files are in kebab-case**, with the adapters in an
|
|
71
|
+
`adapters/` folder next to the service. Other folders keep the project's own casing (UI file naming
|
|
72
|
+
belongs to radan-ui). Why: the file name repeats the class name word for word, so an adapter is
|
|
73
|
+
found by its name, and kebab-case avoids case-only renames that break on case-insensitive disks.
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
lib/logger/
|
|
77
|
+
logger.types.ts ILogger, LogEntry, LogLevel, LogMeta
|
|
78
|
+
logger.ts class Logger (the service)
|
|
79
|
+
log-redaction.ts
|
|
80
|
+
log-level.ts
|
|
81
|
+
index.ts export const logger + adapter choice
|
|
82
|
+
adapters/
|
|
83
|
+
winston-logger-adapter.ts class WinstonLoggerAdapter implements ILogger
|
|
84
|
+
stdout-json-logger-adapter.ts class StdoutJsonLoggerAdapter implements ILogger
|
|
85
|
+
memory-logger-adapter.ts class MemoryLoggerAdapter implements ILogger
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- **C# has one file per type, named exactly like the type** in PascalCase: `ResendEmailAdapter.cs`,
|
|
89
|
+
`IEmailSender.cs`. Why: this is the .NET norm and what its tools expect; each language keeps its own.
|
|
90
|
+
|
|
91
|
+
## 4. Example
|
|
92
|
+
|
|
93
|
+
TypeScript (no constructor parameter properties, so it runs under Node type stripping):
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
export interface ILogger {
|
|
97
|
+
write(entry: LogEntry): void;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export class Logger {
|
|
101
|
+
readonly #adapter: ILogger;
|
|
102
|
+
readonly #minLevel: LogLevel;
|
|
103
|
+
|
|
104
|
+
constructor(adapter: ILogger, minLevel: LogLevel) {
|
|
105
|
+
this.#adapter = adapter;
|
|
106
|
+
this.#minLevel = minLevel;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
debug = this.#at('debug');
|
|
110
|
+
info = this.#at('info');
|
|
111
|
+
warn = this.#at('warn');
|
|
112
|
+
error = this.#at('error');
|
|
113
|
+
|
|
114
|
+
#at(level: LogLevel) {
|
|
115
|
+
return (message: string, meta?: LogMeta): void => {
|
|
116
|
+
if (rank(level) < rank(this.#minLevel)) return;
|
|
117
|
+
this.#adapter.write({ level, time: new Date(), message: redactText(message), meta: meta && redactMeta(meta) });
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export class WinstonLoggerAdapter implements ILogger {
|
|
123
|
+
// level 'debug': the service already filtered; the adapter must not filter again
|
|
124
|
+
readonly #winston = winston.createLogger({ level: 'debug', transports: [new winston.transports.Console()] });
|
|
125
|
+
|
|
126
|
+
write(entry: LogEntry): void {
|
|
127
|
+
this.#winston.log({ ...entry.meta, level: entry.level, message: entry.message, timestamp: entry.time.toISOString() });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
C#, one adapter implementing two small ports, used only through the services:
|
|
133
|
+
|
|
134
|
+
```csharp
|
|
135
|
+
public interface ISocialConnector {
|
|
136
|
+
Task<SocialAccount> ConnectAsync(ConnectRequest request, CancellationToken ct);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
public interface ISocialPublisher {
|
|
140
|
+
Task<PublishReceipt> PublishAsync(Post post, CancellationToken ct);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
public class MastodonSocialAdapter(HttpClient http) : ISocialConnector, ISocialPublisher {
|
|
144
|
+
public Task<SocialAccount> ConnectAsync(ConnectRequest request, CancellationToken ct) =>
|
|
145
|
+
throw new NotImplementedException(); // POST /oauth/token
|
|
146
|
+
public Task<PublishReceipt> PublishAsync(Post post, CancellationToken ct) =>
|
|
147
|
+
throw new NotImplementedException(); // POST /api/v1/statuses
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// wiring picks the adapter per network; the service does the shared work once
|
|
151
|
+
public class PublishService(ISocialAdapterRegistry adapters, IPublishAttemptJournal journal) {
|
|
152
|
+
public async Task<PublishReceipt> PublishAsync(Post post, CancellationToken ct) {
|
|
153
|
+
journal.Start(post);
|
|
154
|
+
try {
|
|
155
|
+
var receipt = await adapters.Publisher(post.Network).PublishAsync(post, ct);
|
|
156
|
+
journal.Succeed(post, receipt);
|
|
157
|
+
return receipt;
|
|
158
|
+
} catch (Exception ex) when (ex is not OperationCanceledException) {
|
|
159
|
+
journal.Fail(post, ex);
|
|
160
|
+
throw;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// business code: knows the service only
|
|
166
|
+
public class PublishNowEndpoint(PublishService publishing) {
|
|
167
|
+
public Task Handle(Post post, CancellationToken ct) => publishing.PublishAsync(post, ct);
|
|
168
|
+
}
|
|
169
|
+
```
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# SOLID
|
|
2
|
+
|
|
3
|
+
Rules for every personal project (PublyApp, ShopKartOS, radan-ui, future ones), in TypeScript and in
|
|
4
|
+
.NET. Never DigitalPrevention. Written for agents; each rule says why. Owner decision of 2026-11-25.
|
|
5
|
+
Examples marked "example from PublyApp" are illustrations, not a list to copy. The « I » and « D » are the
|
|
6
|
+
same seam as [ports and adapters](ports-and-adapters.md), which is the detailed rule.
|
|
7
|
+
|
|
8
|
+
## S — Single responsibility
|
|
9
|
+
|
|
10
|
+
**Rule.** One module, class or function changes for one reason: one actor or one job.
|
|
11
|
+
|
|
12
|
+
**Sign.** The name needs "And"; the file imports two unrelated domains; a test mocks a database to check
|
|
13
|
+
a string; two teams edit the same file for different features.
|
|
14
|
+
|
|
15
|
+
**Example from PublyApp.** `PublishValidationService` answers one question — is this content publishable
|
|
16
|
+
for these destinations? — and returns a `PublishContentFailure`. `PublishNowService` orchestrates the
|
|
17
|
+
write. Keep that boundary: validation stays pure, orchestration owns the transaction.
|
|
18
|
+
|
|
19
|
+
```csharp
|
|
20
|
+
public static PublishContentFailure? ValidateDestination(
|
|
21
|
+
EffectiveContent content,
|
|
22
|
+
SocialAccount account,
|
|
23
|
+
Func<SocialProvider, bool>? isProviderEnabled = null)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
**Why.** A class with two reasons is edited for one and broken for the other; its tests cannot say which
|
|
27
|
+
contract failed.
|
|
28
|
+
|
|
29
|
+
## O — Open/closed
|
|
30
|
+
|
|
31
|
+
**Rule.** Add a new case by adding code, not by editing working code: a new provider, kind or export is
|
|
32
|
+
a new file plus one registration, and the caller does not change.
|
|
33
|
+
|
|
34
|
+
**Sign.** Every new case edits the same `switch` in several files; a `default:` branch throws "unhandled"
|
|
35
|
+
and is touched on every release; a caller knows every concrete implementation.
|
|
36
|
+
|
|
37
|
+
**Example from PublyApp.** A network that can publish implements `ISocialPublisher`; `SocialAdapterRegistry`
|
|
38
|
+
builds the lookup once, and `RoutingPublishAdapter` routes by `request.Provider`. Adding a network does not
|
|
39
|
+
edit the job's routing (the display-label `switch` still needs a case: a known gap).
|
|
40
|
+
|
|
41
|
+
```csharp
|
|
42
|
+
public interface ISocialPublisher {
|
|
43
|
+
IReadOnlySet<SocialProvider> Networks { get; }
|
|
44
|
+
Task<PublishResult> PublishAsync(PublishRequest request, CancellationToken ct);
|
|
45
|
+
Task<ReconcileResult> ReconcileAsync(ReconcileRequest request, CancellationToken ct);
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**Why.** Each edit of a working branch can break a case nobody tested. Add the seam only where the set of
|
|
50
|
+
cases is genuinely open (providers, integrations); do not invent one for a value that never changes.
|
|
51
|
+
|
|
52
|
+
## L — Liskov substitution
|
|
53
|
+
|
|
54
|
+
**Rule.** An implementation of a type must be usable wherever that type is promised, without the caller
|
|
55
|
+
checking which implementation it got or catching a surprise refusal.
|
|
56
|
+
|
|
57
|
+
**Sign.** A method throws `NotSupportedException` / `NotImplementedException`; the caller does
|
|
58
|
+
`if (x is ConcreteA)`; an override narrows accepted input or skips a documented side effect.
|
|
59
|
+
|
|
60
|
+
**Example from PublyApp.** `ISocialPublisher` contains only what every publisher can honor. A network that
|
|
61
|
+
cannot publish does not implement the port; an unknown network fails at lookup (a wiring error), before
|
|
62
|
+
any publisher is returned. A publisher that cannot confirm an earlier write says so instead of throwing:
|
|
63
|
+
|
|
64
|
+
```csharp
|
|
65
|
+
public Task<ReconcileResult> ReconcileAsync(ReconcileRequest request, CancellationToken ct) {
|
|
66
|
+
return Task.FromResult<ReconcileResult>(new ReconcileResult.NeedsReview(
|
|
67
|
+
"Discord cannot confirm whether the message was posted; check the channel"));
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**Why.** A lying subtype turns a compile-time promise into a runtime branch in every caller, and the
|
|
72
|
+
failure lands far from the cause.
|
|
73
|
+
|
|
74
|
+
## I — Interface segregation
|
|
75
|
+
|
|
76
|
+
**Rule.** A caller depends on a small role interface with only what it uses; one need per port.
|
|
77
|
+
|
|
78
|
+
**Sign.** An interface has methods half its callers never call; a test fake implements twelve members and
|
|
79
|
+
throws on nine; a class implements a port and leaves the unused methods empty.
|
|
80
|
+
|
|
81
|
+
**Example from PublyApp.** `IEmailSender` has one method; `ISocialPublisher` has the three members this
|
|
82
|
+
seam needs. Callers inject the service, the service injects the port.
|
|
83
|
+
|
|
84
|
+
```csharp
|
|
85
|
+
public interface IEmailSender {
|
|
86
|
+
Task<EmailSendReceipt> SendAsync(
|
|
87
|
+
EmailRequest request, string? idempotencyKey = null, CancellationToken ct = default);
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Why.** A fat interface couples every caller to every change, and forces fakes that hide the one method
|
|
92
|
+
the test cares about. See [ports and adapters](ports-and-adapters.md) for the full seam.
|
|
93
|
+
|
|
94
|
+
## D — Dependency inversion
|
|
95
|
+
|
|
96
|
+
**Rule.** High-level policy depends on abstractions; only the wiring names concrete adapters and libraries.
|
|
97
|
+
|
|
98
|
+
**Sign.** A handler calls `new ResendEmailAdapter()`; a service imports the vendor SDK; an `if (isServer)`
|
|
99
|
+
or an environment check sits in business code; the test needs a live API key.
|
|
100
|
+
|
|
101
|
+
**Example from PublyApp.** `EmailService` holds `IEmailSender`; `ServiceRegistration` is the only production
|
|
102
|
+
place that names `ResendEmailAdapter`. Tests swap in `MemoryEmailAdapter` and assert on what it received.
|
|
103
|
+
|
|
104
|
+
```csharp
|
|
105
|
+
public EmailService(IEmailSender emailSender) { ... } // policy
|
|
106
|
+
builder.Services.AddSingleton<IEmailSender, ResendEmailAdapter>(); // wiring
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
**Why.** The policy stays testable and the vendor stays replaceable. This is the D of SOLID and the same
|
|
110
|
+
rule as [ports and adapters](ports-and-adapters.md): business code calls the service, never the adapter.
|
package/rules/ci.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# CI rules (fast, honest CI)
|
|
2
|
+
|
|
3
|
+
Rules for every personal project (PublyApp, ShopKartOS, radan-ui, future ones). Never DigitalPrevention.
|
|
4
|
+
Written for agents; each rule says why. Source: the CI work of 2026-11-21 → 23 (radandevist/conventions#2,
|
|
5
|
+
radandevist/shopkart-os#331, radandevist/radan-ui#88) and PublyApp's CI lessons.
|
|
6
|
+
|
|
7
|
+
**What is shared and what is not.** Shared tools from this package (`conventions quality`,
|
|
8
|
+
`conventions catalog`, see the [design](../docs/design/2026-11-21-conventions-design.md)) replace a
|
|
9
|
+
project's own copy of the same check. Everything else stays project-owned: workflow files, deploy and
|
|
10
|
+
selftest scripts, the PR size cap and which checks are required. The time budgets of §1 are shared: each
|
|
11
|
+
project owns how it meets them (workflow, steps, caches), not the numbers.
|
|
12
|
+
|
|
13
|
+
Measured results:
|
|
14
|
+
|
|
15
|
+
| Project | Before | After | What did it |
|
|
16
|
+
|---|---|---|---|
|
|
17
|
+
| ShopKartOS `pnpm verify` (local gate, no GitHub CI) | 3.9 min | ~37 s (45 s under load) | bounded parallel pool of independent steps; the browser layout check (115 s → ~32 s, the longest step) in a bounded browser pool; faster deploy selftest |
|
|
18
|
+
| radan-ui PR CI | 118 s p50 / 310 s p95 | 60–71 s over the first 3 runs (p95 not measured yet; target below not reached yet) | independent jobs instead of `needs:` chains; cancel superseded PR runs; slow native job split in a matrix; cached native install; heavy nav-stress only when its paths change |
|
|
19
|
+
|
|
20
|
+
## 1. Two gates, two budgets
|
|
21
|
+
|
|
22
|
+
- **PR gate**: the checks that run on every push of a pull request. **Target p50 under 1 minute;
|
|
23
|
+
ceiling: p95 under 5 minutes** (a p50 alone hides slow runs). Why: a slow gate gets skipped, and a
|
|
24
|
+
skipped gate is how main goes red.
|
|
25
|
+
- **Merge gate**: the checks that must be green on the **exact head SHA** before a merge. It is the PR
|
|
26
|
+
gate plus every heavy check whose inputs the change touches (see §3, affected-only). It may take
|
|
27
|
+
longer than the PR gate; its list is written down in each project.
|
|
28
|
+
- **Nightly**: heavy full runs (e.g. radan-ui's full nav-stress, ~10 min) also run on main every night.
|
|
29
|
+
A nightly run is **an alert, not a gate**: anything a change can break must be in the merge gate
|
|
30
|
+
through its path filter. A red nightly does not block green PRs; it opens a fix (or a revert of the
|
|
31
|
+
culprit) the same day, and a flaky nightly is a bug to fix like any flake.
|
|
32
|
+
|
|
33
|
+
## 2. Never buy speed with honesty
|
|
34
|
+
|
|
35
|
+
- **Measure before touching.** Record p50 and p95 over several real runs before any change; every CI PR
|
|
36
|
+
states its before/after p50/p95 and links the runs or the timing log. Why: guesses about where time
|
|
37
|
+
goes are usually wrong (ShopKartOS: the layout check was the longest step, not the unit tests).
|
|
38
|
+
- **No automatic retries, no widened timeouts, no `continue-on-error` on a real check.** They hide
|
|
39
|
+
flakes instead of fixing them. A flaky check is a bug to fix, or a written, project-owned exception.
|
|
40
|
+
- **Never drop a check to go faster.** Make it faster, or run it only when its inputs change (§3).
|
|
41
|
+
Same cases before and after.
|
|
42
|
+
- **The merge gate runs on the last commit.** Targeted runs are fine while working; a merge needs the
|
|
43
|
+
full merge gate green on the exact head SHA. Any rebase or new commit invalidates an earlier run
|
|
44
|
+
(ShopKartOS #344 broke main when this was skipped).
|
|
45
|
+
|
|
46
|
+
## 3. How to make it fast
|
|
47
|
+
|
|
48
|
+
- **Run independent steps in parallel, in a bounded pool** (`min(4, cores)` by default, overridable by
|
|
49
|
+
env). Steps that share a resource (database file, build output, port, browser profile) declare it and
|
|
50
|
+
take a read or write lock: **isolation groups**, never "hope they don't collide".
|
|
51
|
+
- **Stop at the first failure**: as soon as a step exits non-zero, start no new step; let the steps
|
|
52
|
+
already running finish (killing a writer can leave a half-written database or build output), then
|
|
53
|
+
report the failed and the not-run steps and where their logs are. Logs per step in a known folder; one header line per step (id, status, ms).
|
|
54
|
+
- **Independent CI jobs, not chains.** Drop `needs:` unless a job truly consumes another's output.
|
|
55
|
+
- **Cancel superseded runs on pull requests only.** Use one group per PR and a unique group per run
|
|
56
|
+
elsewhere, so a queued run on main is never cancelled:
|
|
57
|
+
```yaml
|
|
58
|
+
concurrency:
|
|
59
|
+
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
|
60
|
+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
|
61
|
+
```
|
|
62
|
+
- **Cache what costs, keyed exactly.** pnpm store; slow native installs keyed on lockfile + manifest +
|
|
63
|
+
runtime version, no loose restore keys. Keep a cache only if the measured restore beats the install.
|
|
64
|
+
- **Affected-only, with fall-back to full.** Heavy suites (browser stress, native builds) run when files
|
|
65
|
+
in their input paths change (path filters), and in full on main. When in doubt about what a change
|
|
66
|
+
affects, run everything.
|
|
67
|
+
- **A path-filtered job is never a required check by itself.** GitHub leaves a required check that did
|
|
68
|
+
not run as "Expected — waiting", and the PR cannot merge. A heavy check that belongs to the merge gate
|
|
69
|
+
goes behind an always-running, required **aggregator** job that passes when no path matched and runs
|
|
70
|
+
(or waits for) the suite otherwise. Leaving a path-filtered check out of the required list is allowed
|
|
71
|
+
only if something else required enforces it; otherwise it is not a gate, and the merger must wait for
|
|
72
|
+
it by hand (radan-ui today: only `check` is required, so a merger waits for `nav-stress` when it runs).
|
|
73
|
+
- **Split a slow job** into a matrix when its parts are independent; shard tests only with a coverage
|
|
74
|
+
guard that uses the test tool's own rule (never a hand-written list that can drop files).
|
|
75
|
+
- **Use the tool's own rules, never re-implement them** (lint rules, test selection, coverage).
|
|
76
|
+
- **Re-measure the runtime choice, don't assume it.** Example: Bun was trialled on ShopKartOS (2026-11-23,
|
|
77
|
+
Bun 1.4.5) for test/format/lint while keeping pnpm as package manager: not adopted (156 failing tests
|
|
78
|
+
on missing Vitest APIs, ~1 s total gain). Re-trial when its gaps close.
|
|
79
|
+
|
|
80
|
+
## 4. Where CI runs
|
|
81
|
+
|
|
82
|
+
- **No CI runner on the owner's PC**, and no paid runner without a quote the owner accepted.
|
|
83
|
+
- **A project without GitHub CI** (ShopKartOS today) uses its local full gate as the merge gate. The
|
|
84
|
+
agent that ran it states the tested SHA and the result in the PR (comment) before asking to merge;
|
|
85
|
+
the merger checks that SHA equals the PR head. This is an honor system until the project has CI.
|
|
86
|
+
|
|
87
|
+
## 5. Size and review
|
|
88
|
+
|
|
89
|
+
- CI changes ship as small PRs, one change each, with numbers, within the project's own PR size cap and
|
|
90
|
+
its exclusions (e.g. PublyApp: 600 changed lines; its own exclusion list — tests, generated files, lockfiles, migrations and snapshots — lives in its config).
|
|
91
|
+
- Reviews follow the project's merge gate: no merge while a CRITICAL, MAJOR or MEDIUM finding stands.
|
package/rules/index.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Rules index
|
|
2
|
+
|
|
3
|
+
Every shared rule for Radan's personal projects. Projects link this file from their `AGENTS.md`
|
|
4
|
+
through a versioned GitHub URL. Never DigitalPrevention.
|
|
5
|
+
|
|
6
|
+
- [CI](ci.md) — fast, honest CI: two gates, time budgets, how to make it fast.
|
|
7
|
+
- [Ports and adapters](architecture/ports-and-adapters.md) — service → small ports (interface segregation) →
|
|
8
|
+
`<Library><Function>Adapter`; file names; TypeScript and .NET.
|
|
9
|
+
- [SOLID](architecture/solid.md) — the five principles: the rule, the sign of a violation, why.
|
|
10
|
+
- [Design patterns](architecture/design-patterns.md) — problem → pattern: sign, shape, when not; all 23
|
|
11
|
+
Gang of Four patterns named.
|