@effect/ai-typesafe 0.0.1 → 4.0.0-rc.117

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.
Files changed (111) hide show
  1. package/AGENTS.md +410 -0
  2. package/CLAUDE.md +410 -0
  3. package/LICENSE +21 -0
  4. package/README.md +3 -41
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +110 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  69. package/ai-docs/src/60_child-process/index.md +3 -0
  70. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  71. package/ai-docs/src/70_cli/index.md +5 -0
  72. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  73. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  74. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  75. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  76. package/ai-docs/src/71_ai/index.md +5 -0
  77. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  78. package/ai-docs/src/80_cluster/index.md +4 -0
  79. package/ai-docs/src/index.md +10 -0
  80. package/ai-docs/tsconfig.json +24 -0
  81. package/dist/TypeSafeClient.d.ts +71 -0
  82. package/dist/TypeSafeClient.d.ts.map +1 -0
  83. package/dist/TypeSafeClient.js +74 -0
  84. package/dist/TypeSafeClient.js.map +1 -0
  85. package/dist/TypeSafeConfig.d.ts +68 -0
  86. package/dist/TypeSafeConfig.d.ts.map +1 -0
  87. package/dist/TypeSafeConfig.js +36 -0
  88. package/dist/TypeSafeConfig.js.map +1 -0
  89. package/dist/TypeSafeDecisionModel.d.ts +44 -0
  90. package/dist/TypeSafeDecisionModel.d.ts.map +1 -0
  91. package/dist/TypeSafeDecisionModel.js +118 -0
  92. package/dist/TypeSafeDecisionModel.js.map +1 -0
  93. package/dist/TypeSafeSchema.d.ts +188 -0
  94. package/dist/TypeSafeSchema.d.ts.map +1 -0
  95. package/dist/TypeSafeSchema.js +130 -0
  96. package/dist/TypeSafeSchema.js.map +1 -0
  97. package/dist/index.d.ts +20 -0
  98. package/dist/index.d.ts.map +1 -0
  99. package/dist/index.js +21 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/internal/errors.d.ts +7 -0
  102. package/dist/internal/errors.d.ts.map +1 -0
  103. package/dist/internal/errors.js +120 -0
  104. package/dist/internal/errors.js.map +1 -0
  105. package/package.json +58 -7
  106. package/src/TypeSafeClient.ts +143 -0
  107. package/src/TypeSafeConfig.ts +85 -0
  108. package/src/TypeSafeDecisionModel.ts +106 -0
  109. package/src/TypeSafeSchema.ts +134 -0
  110. package/src/index.ts +25 -0
  111. package/src/internal/errors.ts +113 -0
package/CLAUDE.md ADDED
@@ -0,0 +1,410 @@
1
+ # Effect library documentation
2
+
3
+ This documentation covers the Effect library and its related packages.
4
+
5
+ When you need to find information about Effect, use this documentation and the
6
+ Effect source code available in your environment. Avoid unrelated copies of
7
+ Effect or external documentation, as they may be outdated or incorrect.
8
+
9
+ **Note**: The examples in this documentation contain comments for illustration
10
+ purposes. In practice, you would not include these comments in your code.
11
+
12
+ ## Writing `Effect` code
13
+
14
+ Prefer `Effect.gen` for inline Effect code. For reusable functions, prefer
15
+ `Effect.fn("name")` when tracing is useful and `Effect.fnUntraced` when it is not,
16
+ particularly in library implementations and hot paths. Avoid functions that only
17
+ wrap and return `Effect.gen`. Attach additional behaviour with combinators; this
18
+ style is more readable and easier to maintain than using combinators alone.
19
+
20
+ ### Using Effect.gen
21
+
22
+ Use `Effect.gen` to write code in an imperative style similar to async await.
23
+ You can use `yield*` to access the result of an effect.
24
+
25
+ ```ts
26
+ import { Effect, Schema } from "effect"
27
+
28
+ Effect.gen(function*() {
29
+ yield* Effect.log("Starting the file processing...")
30
+ yield* Effect.log("Reading file...")
31
+
32
+ // Always return when raising an error, to ensure typescript understands that
33
+ // the function will not continue executing.
34
+ return yield* new FileProcessingError({ message: "Failed to read the file" })
35
+ }).pipe(
36
+ // Add additional functionality with .pipe
37
+ Effect.catch((error) => Effect.logError(`An error occurred: ${error}`)),
38
+ Effect.withSpan("fileProcessing", {
39
+ attributes: {
40
+ method: "Effect.gen"
41
+ }
42
+ })
43
+ )
44
+
45
+ // Use Schema.TaggedError to define a custom error
46
+ export class FileProcessingError extends Schema.TaggedError<FileProcessingError>()("FileProcessingError", {
47
+ message: Schema.String
48
+ }) {}
49
+ ```
50
+
51
+ ### Using Effect.fn and Effect.fnUntraced
52
+
53
+ When writing reusable functions that return an Effect, use `Effect.fn` or
54
+ `Effect.fnUntraced` to use the generator syntax.
55
+
56
+ Use `Effect.fn("name")` when the function should create a tracing span. Prefer
57
+ `Effect.fnUntraced` when tracing is not needed, particularly for library
58
+ implementations and hot paths.
59
+
60
+ **Avoid creating functions that only wrap and return an `Effect.gen`**.
61
+
62
+ ```ts
63
+ import { Effect, Schema } from "effect"
64
+
65
+ // Pass a string to Effect.fn, which will improve stack traces and also
66
+ // attach a tracing span (using Effect.withSpan behind the scenes).
67
+ //
68
+ // The name string should match the function name.
69
+ //
70
+ export const effectFunction = Effect.fn("effectFunction")(
71
+ // You can use `Effect.fn.Return` to specify the return type of the function.
72
+ // It accepts the same type parameters as `Effect.Effect`.
73
+ function*(n: number): Effect.fn.Return<string, SomeError> {
74
+ yield* Effect.logInfo("Received number:", n)
75
+
76
+ // Always return when raising an error, to ensure typescript understands that
77
+ // the function will not continue executing.
78
+ return yield* new SomeError({ message: "Failed to read the file" })
79
+ },
80
+ // Add additional functionality by passing in additional arguments.
81
+ // **Do not** use .pipe with Effect.fn
82
+ Effect.catch((error) => Effect.logError(`An error occurred: ${error}`)),
83
+ Effect.annotateLogs({
84
+ method: "effectFunction"
85
+ })
86
+ )
87
+
88
+ // Effect.fnUntraced avoids tracing and stack-frame capture while still reusing
89
+ // the generator body. This is preferred for library functions that do not
90
+ // represent a useful tracing boundary.
91
+ export const validateBatchSize = Effect.fnUntraced(function*(size: number): Effect.fn.Return<number, SomeError> {
92
+ if (!Number.isInteger(size) || size <= 0) {
93
+ return yield* new SomeError({ message: "Batch size must be a positive integer" })
94
+ }
95
+ return size
96
+ })
97
+
98
+ // Use Schema.TaggedError to define a custom error
99
+ export class SomeError extends Schema.TaggedError<SomeError>()("SomeError", {
100
+ message: Schema.String
101
+ }) {}
102
+ ```
103
+
104
+ ### More examples
105
+
106
+ - **[Creating effects from common sources](./ai-docs/src/01_effect/01_basics/10_creating-effects.ts)**:
107
+ Learn how to create effects from various sources, including plain values,
108
+ synchronous code, Promise APIs, optional values, and callback-based APIs.
109
+
110
+ ## Defining schemas and domain models
111
+
112
+ All validation and domain modeling in Effect is done with `Schema`.
113
+
114
+ **AVOID using predicates or manual parsing**, instead use `Schema` to parse untrusted data and validate it.
115
+
116
+ For a comprehensive guide, see [SCHEMA.md](https://github.com/Effect-TS/effect/blob/main/packages/effect/SCHEMA.md). Make sure to read the guide in chunks, as it is a large document.
117
+
118
+ - **[Schema basics](./ai-docs/src/01_effect/02_schema/10_schema-basics.ts)**:
119
+ Define `Schema.Class`s, decode unknown input into typed values, and
120
+ encode typed values back into their external representation.
121
+
122
+ ## Writing Effect services
123
+
124
+ Effect services are the most common way to structure Effect code. Prefer using
125
+ services to encapsulate behaviour over other approaches, as it ensures that your
126
+ code is modular, testable, and maintainable.
127
+
128
+ ### Context.Service
129
+
130
+ The default way to define a service is to extend `Context.Service`,
131
+ passing in the service interface as a type parameter.
132
+
133
+ ```ts
134
+ // file: src/db/Database.ts
135
+ import { Context, Effect, Layer, Schema } from "effect"
136
+
137
+ // Pass in the service class name as the first type parameter, and the service
138
+ // interface as the second type parameter.
139
+ export class Database extends Context.Service<Database, {
140
+ query(sql: string): Effect.Effect<Array<unknown>, DatabaseError>
141
+ }>()(
142
+ // The string identifier for the service, which should include the package
143
+ // name and the subdirectory path to the service file.
144
+ "myapp/db/Database"
145
+ ) {
146
+ // Attach a static layer to the service, which will be used to provide an
147
+ // implementation of the service.
148
+ static readonly layer = Layer.effect(
149
+ Database,
150
+ Effect.gen(function*() {
151
+ // Define the service methods using Effect.fn
152
+ const query = Effect.fn("Database.query")(function*(sql: string) {
153
+ yield* Effect.log("Executing SQL query:", sql)
154
+ return [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }]
155
+ })
156
+
157
+ // Return an instance of the service using Database.of, passing in an
158
+ // object that implements the service interface.
159
+ return Database.of({
160
+ query
161
+ })
162
+ })
163
+ )
164
+ }
165
+
166
+ export class DatabaseError extends Schema.TaggedError<DatabaseError>()("DatabaseError", {
167
+ cause: Schema.Defect()
168
+ }) {}
169
+
170
+ // If you ever need to access the service type, use `Database["Service"]`
171
+ export type DatabaseService = Database["Service"]
172
+ ```
173
+
174
+ ### More examples
175
+
176
+ - **[Context.Reference](./ai-docs/src/01_effect/03_services/10_reference.ts)**: For defining configuration values, feature flags, or any other service that has a default value.
177
+ - **[Composing services with the Layer module](./ai-docs/src/01_effect/03_services/20_layer-composition.ts)**:
178
+ Build focused service layers, then compose them with `Layer.provide` and
179
+ `Layer.provideMerge` based on what services you want to expose.
180
+ - **[Creating Layers from configuration and/or Effects](./ai-docs/src/01_effect/03_services/20_layer-unwrap.ts)**: Build a layer dynamically from an Effect / Config with `Layer.unwrap`.
181
+
182
+ ## Error handling
183
+
184
+ ### Error handling basics
185
+
186
+ Defining custom errors and handling them with Effect.catch and Effect.catchTag.
187
+
188
+ ```ts
189
+ import { Effect, Schema } from "effect"
190
+
191
+ // Define custom errors using Schema.TaggedError
192
+ export class ParseError extends Schema.TaggedError<ParseError>()("ParseError", {
193
+ input: Schema.String,
194
+ message: Schema.String
195
+ }) {}
196
+
197
+ export class ReservedPortError extends Schema.TaggedError<ReservedPortError>()("ReservedPortError", {
198
+ port: Schema.Int
199
+ }) {}
200
+
201
+ declare const loadPort: (input: string) => Effect.Effect<number, ParseError | ReservedPortError>
202
+
203
+ export const recovered = loadPort("80").pipe(
204
+ // Catch multiple errors with Effect.catchTag, and return a default port number.
205
+ Effect.catchTag(["ParseError", "ReservedPortError"], (_) => Effect.succeed(3000))
206
+ )
207
+
208
+ export const withFinalFallback = loadPort("invalid").pipe(
209
+ // Catch a specific error with Effect.catchTag
210
+ Effect.catchTag("ReservedPortError", (_) => Effect.succeed(3000)),
211
+ // Catch all errors with Effect.catch
212
+ Effect.catch((_) => Effect.succeed(3000))
213
+ )
214
+ ```
215
+
216
+ ### More examples
217
+
218
+ - **[Catch multiple errors with Effect.catchTags](./ai-docs/src/01_effect/04_errors/10_catch-tags.ts)**: Use `Effect.catchTags` to handle several tagged errors in one place.
219
+ - **[Creating and handling errors with reasons](./ai-docs/src/01_effect/04_errors/20_reason-errors.ts)**:
220
+ Define a tagged error with a tagged `reason` field, then recover with
221
+ `Effect.catchReason`, `Effect.catchReasons`, or by unwrapping the reason into
222
+ the error channel with `Effect.unwrapReason`.
223
+
224
+ ## Managing resources and `Scope`s
225
+
226
+ Learn how to safely manage resources in Effect using `Scope`s and finalizers.
227
+
228
+ - **[Acquiring resources with Effect.acquireRelease](./ai-docs/src/01_effect/05_resources/10_acquire-release.ts)**:
229
+ Define a service that uses `Effect.acquireRelease` to manage the lifecycle of
230
+ a resource, ensuring that it is properly cleaned up when the service is no
231
+ longer needed.
232
+ - **[Creating Layers that run background tasks](./ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts)**: Use Layer.effectDiscard to encapsulate background tasks without a service interface.
233
+ - **[Dynamic resources with LayerMap](./ai-docs/src/01_effect/05_resources/30_layer-map.ts)**:
234
+ Use `LayerMap.Service` to dynamically build and manage resources that are
235
+ keyed by some identifier, such as a tenant ID.
236
+
237
+ ## Running Effect programs
238
+
239
+ - **[Running effects with NodeRuntime and BunRuntime](./ai-docs/src/01_effect/06_running/10_run-main.ts)**: Use `NodeRuntime.runMain` to run an Effect program as your process entrypoint.
240
+ - **[Using Layer.launch as the application entry point](./ai-docs/src/01_effect/06_running/20_layer-launch.ts)**: Use `Layer.launch` to run a long-running Effect program as your process entrypoint.
241
+
242
+ ## Broadcasting messages with PubSub
243
+
244
+ Use `PubSub` when you need one producer to fan out messages to many consumers.
245
+
246
+ - **[Broadcasting domain events with PubSub](./ai-docs/src/01_effect/07_pubsub/10_pubsub.ts)**: Build an in-process event bus with `PubSub` and expose it as a service.
247
+
248
+ ## Working with Streams
249
+
250
+ Effect Streams represent effectful, pull-based sequences of values over time.
251
+ They let you model finite or infinite data sources.
252
+
253
+ - **[Creating streams from common data sources](./ai-docs/src/03_stream/10_creating-streams.ts)**:
254
+ Learn how to create streams from various data sources. Includes:
255
+
256
+ - `Stream.fromIterable` for arrays and other iterables
257
+ - `Stream.fromEffectSchedule` for polling effects
258
+ - `Stream.paginate` for paginated APIs
259
+ - `Stream.fromAsyncIterable` for async iterables
260
+ - `Stream.fromEventListener` for DOM events
261
+ - `Stream.callback` for any callback-based API
262
+ - `NodeStream.fromReadable` for Node.js readable streams
263
+ - **[Consuming and transforming streams](./ai-docs/src/03_stream/20_consuming-streams.ts)**: How to transform and consume streams using operators like `map`, `flatMap`, `filter`, `mapEffect`, and various `run*` methods.
264
+ - **[Decoding and encoding streams](./ai-docs/src/03_stream/30_encoding.ts)**:
265
+ Use `Stream.pipeThroughChannel` with the `Ndjson` and `SchemaBinary` modules to
266
+ decode and encode streams of structured data.
267
+
268
+ ## Integrating Effect into existing applications
269
+
270
+ `ManagedRuntime` bridges Effect programs with non-Effect code. Build one runtime
271
+ from your application Layer, then use it anywhere you need imperative execution,
272
+ like web handlers, framework hooks, worker queues, or legacy callback APIs.
273
+
274
+ - **[Using ManagedRuntime with Hono](./ai-docs/src/04_integration/10_managed-runtime.ts)**: Use `ManagedRuntime` to run Effect programs from external frameworks while keeping your domain logic in services and Layers.
275
+
276
+ ## Batching external requests
277
+
278
+ Learn how to batch multiple requests into fewer external calls.
279
+
280
+ - **[Batching requests with RequestResolver](./ai-docs/src/05_batching/10_request-resolver.ts)**: Define request types with `Request.Class`, resolve them in batches with `RequestResolver`.
281
+
282
+ ## Working with Schedules
283
+
284
+ Schedules define recurring patterns for retries, repeats and polling.
285
+
286
+ - **[Working with the Schedule module](./ai-docs/src/06_schedule/10_schedules.ts)**: Build schedules, compose them, and use them with `Effect.retry` and `Effect.repeat`.
287
+
288
+ ## Working with DateTime
289
+
290
+ When working with dates and time, use the `DateTime` module instead of `Date` and `Date.now`.
291
+
292
+ Use it when your Effect programs need testable current time, safe parsing, stable ISO formatting, time-zone conversion, or calendar arithmetic.
293
+
294
+ - **[Creating and formatting DateTime values](./ai-docs/src/07_datetime/10_creating-and-formatting.ts)**:
295
+ Parse incoming date values safely, use Clock-powered current time, and format
296
+ instants for API payloads or user-facing labels.
297
+ - **[Working with time zones](./ai-docs/src/07_datetime/20_time-zones.ts)**:
298
+ Attach IANA zones to instants, render zoned ISO strings, and provide a
299
+ CurrentTimeZone service for code that should use the workspace/user zone.
300
+
301
+ ## Observability
302
+
303
+ Effect has built-in support for structured logging, distributed tracing, and
304
+ metrics. For exporting telemetry, use the lightweight Otlp modules from
305
+ `effect/unstable/observability` in new projects, or use
306
+ `@effect/opentelemetry` NodeSdk when integrating with an existing OpenTelemetry
307
+ setup.
308
+
309
+ - **[Customizing logging](./ai-docs/src/08_observability/10_logging.ts)**: Configure loggers & log-level filtering for production applications.
310
+ - **[Setting up tracing with Otlp modules](./ai-docs/src/08_observability/20_otlp-tracing.ts)**: Configure Otlp tracing + log export with a reusable observability layer.
311
+
312
+ ## Testing Effect programs
313
+
314
+ - **[Writing Effect tests with @effect/vitest](./ai-docs/src/09_testing/10_effect-tests.ts)**: Using `it.effect` for Effect-based tests.
315
+ - **[Testing services with shared layers](./ai-docs/src/09_testing/20_layer-tests.ts)**: How to test Effect services that depend on other services.
316
+
317
+ ## Runtime type guards
318
+
319
+ The `Predicate` module contains small, reusable runtime checks.
320
+
321
+ **NEVER** write your own helper functions like `isRecord` or `isString`, instead
322
+ use the helpers from the `Predicate` module.
323
+
324
+ Predicates can be composed with apis such as `Predicate.and`,
325
+ `Predicate.or`, `Predicate.not`, and `Predicate.compose`.
326
+
327
+ ### Using the Predicate module
328
+
329
+
330
+
331
+ ```ts
332
+ import { Predicate } from "effect"
333
+
334
+ const thing: unknown = {
335
+ a: 1
336
+ }
337
+
338
+ if (Predicate.isObject(thing)) {
339
+ if (Predicate.isNumber(thing.a)) {
340
+ console.log("number", thing.a)
341
+ }
342
+ }
343
+ ```
344
+
345
+ ## Working with SQL databases
346
+
347
+ Use the `effect/unstable/sql` modules together with a driver package such as
348
+ `@effect/sql-sqlite-node` to access SQL databases. Define domain models with
349
+ `Model.Class` to derive schemas for the database and JSON boundaries, run
350
+ migrations, and write type-safe queries.
351
+
352
+ - **[Getting started with SQL](./ai-docs/src/40_sql/10_basics.ts)**:
353
+ Define a schema-backed domain model, run migrations against a SQLite
354
+ database, and expose a derived repository through a service.
355
+
356
+ ## Effect HttpClient
357
+
358
+ Build http clients with the `HttpClient` module.
359
+
360
+ - **[Getting started with HttpClient](./ai-docs/src/50_http-client/10_basics.ts)**: Define a service that uses the HttpClient module to fetch data from an external API
361
+
362
+ ## Building HttpApi servers
363
+
364
+ `HttpApi` gives you schema-first, type-safe HTTP APIs with runtime validation, typed clients, and OpenAPI docs from one definition.
365
+
366
+ - **[Getting started with HttpApi](./ai-docs/src/51_http-server/10_basics.ts)**:
367
+ Define a schema-first API, implement handlers, secure endpoints with
368
+ middleware, serve it over HTTP, and call it using a generated typed client.
369
+ - **[Testing HttpApi implementations](./ai-docs/src/51_http-server/20_testing.ts)**:
370
+ Test handlers through an in-memory typed client with `HttpApiTest`, without
371
+ starting an HTTP server or touching a real database.
372
+
373
+ ## Working with child processes
374
+
375
+ Use the `effect/unstable/process` modules to define child processes and run them with `ChildProcessSpawner`.
376
+
377
+ - **[Working with child processes](./ai-docs/src/60_child-process/10_working-with-child-processes.ts)**: This example shows how to collect process output, compose pipelines, and stream long-running command output.
378
+
379
+ ## Building CLI applications
380
+
381
+ Use the "effect/unstable/cli" modules to build CLI applications. These modules
382
+ provide utilities for parsing command-line arguments, handling user input, and
383
+ managing the flow of a CLI application.
384
+
385
+ - **[Getting started with Effect CLI modules](./ai-docs/src/70_cli/10_basics.ts)**:
386
+ Build a command-line app with typed arguments and flags, then wire subcommand
387
+ handlers into a single executable command.
388
+
389
+ ## Working with AI modules
390
+
391
+ Effect's AI modules provide a provider-agnostic interface for language models.
392
+ You can generate text, decode structured objects with `Schema` and stream partial
393
+ responses.
394
+
395
+ - **[Using LanguageModel for text, objects, and streams](./ai-docs/src/71_ai/10_language-model.ts)**:
396
+ Configure a provider once, then use `LanguageModel` for plain text
397
+ generation, schema-validated object generation, and streaming responses.
398
+ - **[Defining and using AI tools](./ai-docs/src/71_ai/20_tools.ts)**:
399
+ Define tools with schemas, group them into toolkits, implement handlers,
400
+ and pass them to `LanguageModel.generateText`.
401
+ - **[Stateful chat sessions](./ai-docs/src/71_ai/30_chat.ts)**:
402
+ The AI `Chat` module maintains conversation history automatically. Build
403
+ AI agents or chat assistants.
404
+
405
+ ## Building distributed applications with cluster
406
+
407
+ The cluster modules let you model stateful services as entities and distribute
408
+ them across multiple machines.
409
+
410
+ - **[Defining cluster entities](./ai-docs/src/80_cluster/10_entities.ts)**: Define distributed entity RPCs and run them in a cluster.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Effectful Technologies Inc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,7 @@
1
1
  # @effect/ai-typesafe
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ TypeSafe System One provider for Effect's `DecisionModel`. Supports classification, ordered ratings, and probabilities through Effect `HttpClient`.
4
4
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
5
+ Use `TypeSafeClient.layerConfig()` to read `TYPESAFE_API_KEY`, then provide `TypeSafeDecisionModel.model("jev-latest")` to a decision workflow. Versioned model identifiers such as `jev-1.13.0` are also supported.
6
6
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
-
9
- ## Purpose
10
-
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@effect/ai-typesafe`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
7
+ The client does not retry automatically. Rate-limit errors include the provider's retry delay when available. Provider distributions are preserved, not normalized; they must satisfy the core `DecisionModel` validation, including its current `1e-6` sum tolerance. TypeSafe's rounding behavior has not been verified against the live API.
@@ -0,0 +1,44 @@
1
+ # AI docs
2
+
3
+ `LLMS.md` is generated from `ai-docs/src`.
4
+
5
+ ## Add content
6
+
7
+ 1. Add or update markdown in `ai-docs/src/**/index.md` for section intro text.
8
+ 2. Add examples as `.ts` files in the same folder.
9
+ 3. Run `pnpm ai-docgen` to regenerate `LLMS.md`.
10
+
11
+ ## Source file conventions
12
+
13
+ - Use numeric filename prefixes to control ordering (`10_`, `20_`, etc). Avoid starting with `0` unless explicity requested to do so.
14
+ - Use a top JSDoc block with `@title` and optional description to control rendered title/description.
15
+ - `fixtures` directories are ignored and not included in the generated
16
+ documentation. Use them for any supporting code or data needed for examples.
17
+
18
+ ## Example guidelines
19
+
20
+ Before writing an example, look at the existing examples in `ai-docs/src` to
21
+ learn the style and conventions used in this project. Also read the current
22
+ `LLMS.md` to understand the content and style of the documentation.
23
+
24
+ **All code examples should be well commented** explaining the how and why of the
25
+ code, not just what the code is doing. The goal is to teach users how to use the
26
+ API.
27
+
28
+ **Code must represent real world usage and best practices.**
29
+ Do not include toy examples that are not representative of how the API should be
30
+ used in practice.
31
+
32
+ - **Prefer using the service style** of structuring code, as this represents real
33
+ world usage and best practices.
34
+ - Use the `fixtures` directory to illustrate / suggest best practices for
35
+ project structure, file organization, and code organization.
36
+
37
+ Pull requests with only ai documentation changes **DO NOT** need a changeset.
38
+
39
+ ## Regeneration
40
+
41
+ - One-shot: `pnpm ai-docgen`
42
+ - Watch mode: `pnpm ai-docgen:watch`
43
+
44
+ `pnpm ai-docgen` regenerates `LLMS.md` files from content in `ai-docs/src`.
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "ai-docs",
3
+ "private": true,
4
+ "type": "module",
5
+ "version": "0.0.0",
6
+ "dependencies": {
7
+ "@effect/ai-anthropic": "workspace:*",
8
+ "@effect/ai-openai": "workspace:*",
9
+ "@effect/ai-openai-compat": "workspace:*",
10
+ "@effect/ai-openrouter": "workspace:*",
11
+ "@effect/atom-react": "workspace:*",
12
+ "@effect/atom-solid": "workspace:*",
13
+ "@effect/atom-vue": "workspace:*",
14
+ "@effect/opentelemetry": "workspace:*",
15
+ "@effect/platform-bun": "workspace:*",
16
+ "@effect/platform-node": "workspace:*",
17
+ "@effect/sql-clickhouse": "workspace:*",
18
+ "@effect/sql-d1": "workspace:*",
19
+ "@effect/sql-libsql": "workspace:*",
20
+ "@effect/sql-mssql": "workspace:*",
21
+ "@effect/sql-mysql2": "workspace:*",
22
+ "@effect/sql-pg": "workspace:*",
23
+ "@effect/sql-sqlite-bun": "workspace:*",
24
+ "@effect/sql-sqlite-do": "workspace:*",
25
+ "@effect/sql-sqlite-node": "workspace:*",
26
+ "@effect/sql-sqlite-react-native": "workspace:*",
27
+ "@effect/sql-sqlite-wasm": "workspace:*",
28
+ "@effect/vitest": "workspace:*",
29
+ "effect": "workspace:*",
30
+ "hono": "^4.13.8",
31
+ "nodemailer": "^10.0.10"
32
+ },
33
+ "devDependencies": {
34
+ "@types/nodemailer": "^8.0.2"
35
+ }
36
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @title Using Effect.gen
3
+ *
4
+ * Use `Effect.gen` to write code in an imperative style similar to async await.
5
+ * You can use `yield*` to access the result of an effect.
6
+ */
7
+
8
+ import { Effect, Schema } from "effect"
9
+
10
+ Effect.gen(function*() {
11
+ yield* Effect.log("Starting the file processing...")
12
+ yield* Effect.log("Reading file...")
13
+
14
+ // Always return when raising an error, to ensure typescript understands that
15
+ // the function will not continue executing.
16
+ return yield* new FileProcessingError({ message: "Failed to read the file" })
17
+ }).pipe(
18
+ // Add additional functionality with .pipe
19
+ Effect.catch((error) => Effect.logError(`An error occurred: ${error}`)),
20
+ Effect.withSpan("fileProcessing", {
21
+ attributes: {
22
+ method: "Effect.gen"
23
+ }
24
+ })
25
+ )
26
+
27
+ // Use Schema.TaggedError to define a custom error
28
+ export class FileProcessingError extends Schema.TaggedError<FileProcessingError>()("FileProcessingError", {
29
+ message: Schema.String
30
+ }) {}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @title Using Effect.fn and Effect.fnUntraced
3
+ *
4
+ * When writing reusable functions that return an Effect, use `Effect.fn` or
5
+ * `Effect.fnUntraced` to use the generator syntax.
6
+ *
7
+ * Use `Effect.fn("name")` when the function should create a tracing span. Prefer
8
+ * `Effect.fnUntraced` when tracing is not needed, particularly for library
9
+ * implementations and hot paths.
10
+ *
11
+ * **Avoid creating functions that only wrap and return an `Effect.gen`**.
12
+ */
13
+
14
+ import { Effect, Schema } from "effect"
15
+
16
+ // Pass a string to Effect.fn, which will improve stack traces and also
17
+ // attach a tracing span (using Effect.withSpan behind the scenes).
18
+ //
19
+ // The name string should match the function name.
20
+ //
21
+ export const effectFunction = Effect.fn("effectFunction")(
22
+ // You can use `Effect.fn.Return` to specify the return type of the function.
23
+ // It accepts the same type parameters as `Effect.Effect`.
24
+ function*(n: number): Effect.fn.Return<string, SomeError> {
25
+ yield* Effect.logInfo("Received number:", n)
26
+
27
+ // Always return when raising an error, to ensure typescript understands that
28
+ // the function will not continue executing.
29
+ return yield* new SomeError({ message: "Failed to read the file" })
30
+ },
31
+ // Add additional functionality by passing in additional arguments.
32
+ // **Do not** use .pipe with Effect.fn
33
+ Effect.catch((error) => Effect.logError(`An error occurred: ${error}`)),
34
+ Effect.annotateLogs({
35
+ method: "effectFunction"
36
+ })
37
+ )
38
+
39
+ // Effect.fnUntraced avoids tracing and stack-frame capture while still reusing
40
+ // the generator body. This is preferred for library functions that do not
41
+ // represent a useful tracing boundary.
42
+ export const validateBatchSize = Effect.fnUntraced(function*(size: number): Effect.fn.Return<number, SomeError> {
43
+ if (!Number.isInteger(size) || size <= 0) {
44
+ return yield* new SomeError({ message: "Batch size must be a positive integer" })
45
+ }
46
+ return size
47
+ })
48
+
49
+ // Use Schema.TaggedError to define a custom error
50
+ export class SomeError extends Schema.TaggedError<SomeError>()("SomeError", {
51
+ message: Schema.String
52
+ }) {}