@vyriy/request 0.2.0 → 0.3.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/AGENTS.md ADDED
@@ -0,0 +1,65 @@
1
+ # Vyriy Package Agent Guide
2
+
3
+ This package belongs to the Vyriy toolkit. Keep changes calm, explicit, reusable, and easy to reason about.
4
+
5
+ ## Architecture
6
+
7
+ - Prefer simple modules over clever frameworks or hidden conventions.
8
+ - Keep package boundaries explicit and avoid project-specific coupling.
9
+ - Extract only proven reusable behavior.
10
+ - Keep public APIs small, typed, documented, and stable.
11
+ - Prefer SSR-friendly and SSG-friendly code paths.
12
+ - Keep integrations replaceable and avoid hard coupling to a CMS or runtime host.
13
+ - Prefer AWS serverless-compatible assumptions when infrastructure concerns appear.
14
+
15
+ ## File Shape
16
+
17
+ - Prefer one exported runtime method, component, or helper per production file when it stays readable.
18
+ - Prefer one matching test file per production file, for example `feature.ts` and `feature.test.ts`.
19
+ - Use focused folders when behavior naturally splits into several related files.
20
+ - Keep `index.ts` as a public re-export surface only. Do not place implementation logic in it.
21
+ - Use `.js` relative import and export specifiers in TypeScript source where package style requires it.
22
+ - Add `types.ts` when public shared types are part of the package contract.
23
+ - Keep constants near the code that owns them unless they are shared or clarify repeated behavior.
24
+
25
+ ## Public Surface
26
+
27
+ - Every new public export should be re-exported from `index.ts`.
28
+ - Add or update `index.test.ts` when the public export surface changes.
29
+ - Add JSDoc for public exports when behavior, parameters, return values, or usage expectations need explanation.
30
+ - Do not hand-maintain source package `exports` maps unless the package has a real custom publishing need.
31
+
32
+ ## Tests
33
+
34
+ - Tests use Jest and `@jest/globals`.
35
+ - Cover public behavior and meaningful edge cases.
36
+ - Prefer behavior-focused tests over private implementation lock-in.
37
+ - When mocking modules, install mocks before loading the module under test.
38
+ - Use focused validation when changing package behavior:
39
+
40
+ ```bash
41
+ yarn jest packages/<package> --runInBand --coverage=false
42
+ ```
43
+
44
+ ## Documentation
45
+
46
+ - Keep `README.md` concise and usage-oriented.
47
+ - Start package READMEs with `# @vyriy/<package>`.
48
+ - Document real public exports, supported options, and examples that actually work.
49
+ - Keep `doc.mdx` as the Storybook/docs wrapper for the README when the package participates in docs.
50
+ - For component packages, include Storybook coverage for supported states and common usage.
51
+
52
+ ## Components
53
+
54
+ - Prefer lightweight React 19+ components with TypeScript.
55
+ - Keep components SSR-friendly and avoid browser globals during render.
56
+ - Prefer composable props and Bootstrap-compatible ergonomics where practical.
57
+ - Put each public component in its own file with a matching test.
58
+ - Add Storybook stories when a component has visual states, variants, or interaction states.
59
+
60
+ ## Change Discipline
61
+
62
+ - Keep changes scoped to the requested behavior.
63
+ - Avoid unrelated refactors and metadata churn.
64
+ - Sync implementation, tests, README, `doc.mdx`, and public re-exports together.
65
+ - Prefer the option that is simpler to explain, easier to evolve, and calmer to maintain.
package/README.md CHANGED
@@ -22,23 +22,108 @@ yarn add @vyriy/request
22
22
 
23
23
  ## Usage
24
24
 
25
+ Read JSON:
26
+
25
27
  ```ts
26
- import { request } from '@vyriy/request';
28
+ import { request, requestStream } from '@vyriy/request';
27
29
 
28
30
  const profile = await request<{ id: string; name: string }>('/api/profile');
31
+ ```
32
+
33
+ Read text with custom retry and timeout behavior:
29
34
 
35
+ ```ts
30
36
  const html = await request<string>('https://example.com', null, {
31
37
  retries: 1,
32
38
  timeout: 5000,
33
39
  });
34
40
  ```
35
41
 
42
+ Send JSON with `POST`:
43
+
44
+ ```ts
45
+ type CreatedProfile = {
46
+ id: string;
47
+ };
48
+
49
+ const created = await request<CreatedProfile>('/api/profile', {
50
+ method: 'POST',
51
+ headers: {
52
+ 'content-type': 'application/json',
53
+ },
54
+ body: JSON.stringify({
55
+ name: 'Ada',
56
+ }),
57
+ });
58
+ ```
59
+
60
+ Send authenticated requests:
61
+
62
+ ```ts
63
+ const projects = await request<Array<{ id: string; name: string }>>('/api/projects', {
64
+ headers: {
65
+ authorization: `Bearer ${token}`,
66
+ accept: 'application/json',
67
+ },
68
+ });
69
+ ```
70
+
71
+ Send form data:
72
+
73
+ ```ts
74
+ const form = new FormData();
75
+ form.append('title', 'Draft');
76
+ form.append('file', file);
77
+
78
+ await request('/api/upload', {
79
+ method: 'POST',
80
+ body: form,
81
+ });
82
+ ```
83
+
84
+ Use an external abort signal:
85
+
86
+ ```ts
87
+ const controller = new AbortController();
88
+
89
+ const pending = request('/api/search', {
90
+ signal: controller.signal,
91
+ });
92
+
93
+ controller.abort();
94
+
95
+ await pending;
96
+ ```
97
+
98
+ Consume streaming chunks:
99
+
100
+ ```ts
101
+ const decoder = new TextDecoder();
102
+
103
+ await requestStream('/api/events', null, {
104
+ onChunk: (chunk) => {
105
+ console.info(decoder.decode(chunk));
106
+ },
107
+ });
108
+ ```
109
+
110
+ Get the raw streaming response:
111
+
112
+ ```ts
113
+ const response = await requestStream('/api/download');
114
+ const body = response.body;
115
+ ```
116
+
36
117
  ## API
37
118
 
38
119
  - `request(input, init?, options?)` performs a `fetch` call and returns parsed JSON or text.
120
+ - `requestStream(input, init?, options?)` performs a `fetch` call and returns the successful `Response`.
121
+ - `requestStream(..., { onChunk })` consumes `response.body` and calls `onChunk` for each `Uint8Array` chunk in order.
39
122
  - `init` may be `null` when you want to skip request init and pass `options` as the third argument.
40
123
  - `options.timeout` sets the per-attempt timeout in milliseconds.
41
124
  - `options.retries` controls how many retry attempts are allowed after the initial request.
42
125
  - `options.retryDelay` sets the base delay in milliseconds between retry attempts.
43
126
  - `options.retryMethods` overrides which HTTP methods are allowed to retry.
44
127
  - `options.retryStatuses` overrides which HTTP status codes are considered retryable.
128
+
129
+ For streaming requests, retries happen only before chunk consumption starts. This avoids delivering duplicate chunks to `onChunk`.
package/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './request.js';
2
+ export * from './stream.js';
2
3
  export type * from './types.js';
package/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export * from './request.js';
2
+ export * from './stream.js';
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@vyriy/request",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Shared request utility for Vyriy projects",
5
5
  "type": "module",
6
6
  "main": "./index.js",
7
+ "agents": "./AGENTS.md",
7
8
  "license": "MIT",
8
9
  "repository": {
9
10
  "type": "git",
@@ -77,6 +78,16 @@
77
78
  "import": "./retry.js",
78
79
  "default": "./retry.js"
79
80
  },
81
+ "./stream": {
82
+ "types": "./stream.d.ts",
83
+ "import": "./stream.js",
84
+ "default": "./stream.js"
85
+ },
86
+ "./stream.js": {
87
+ "types": "./stream.d.ts",
88
+ "import": "./stream.js",
89
+ "default": "./stream.js"
90
+ },
80
91
  "./timeout": {
81
92
  "types": "./timeout.d.ts",
82
93
  "import": "./timeout.js",
package/stream.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { RequestStream } from './types.js';
2
+ export declare const requestStream: RequestStream;
package/stream.js ADDED
@@ -0,0 +1,56 @@
1
+ import { DEFAULT_RETRY_METHODS, DEFAULT_RETRY_STATUSES } from './constants.js';
2
+ import { TimeoutError } from './error.js';
3
+ import { assertSuccessfulResponse } from './response.js';
4
+ import { isRetryableError, isRetryableMethod, wait } from './retry.js';
5
+ import { withTimeoutSignal } from './timeout.js';
6
+ export const requestStream = async (input, init = {}, options = {}) => {
7
+ const normalizedInit = init ?? {};
8
+ const { onChunk, retries = 2, retryDelay = 300, retryMethods = DEFAULT_RETRY_METHODS, retryStatuses = DEFAULT_RETRY_STATUSES, timeout = 25000, } = options;
9
+ const method = normalizedInit.method?.toUpperCase() ?? 'GET';
10
+ const run = async (attempt = 0) => {
11
+ const { cleanup, signal, timeoutSignal } = withTimeoutSignal(timeout, normalizedInit.signal);
12
+ let chunkConsumptionStarted = false;
13
+ try {
14
+ const response = await fetch(input, { ...normalizedInit, signal });
15
+ assertSuccessfulResponse(response);
16
+ if (!onChunk) {
17
+ cleanup();
18
+ return response;
19
+ }
20
+ const reader = response.body?.getReader();
21
+ if (!reader) {
22
+ cleanup();
23
+ return response;
24
+ }
25
+ try {
26
+ while (true) {
27
+ const { done, value } = await reader.read();
28
+ if (done) {
29
+ break;
30
+ }
31
+ chunkConsumptionStarted = true;
32
+ await onChunk(value, { attempt, response });
33
+ }
34
+ }
35
+ finally {
36
+ reader.releaseLock();
37
+ }
38
+ cleanup();
39
+ return response;
40
+ }
41
+ catch (error) {
42
+ const canRetry = !chunkConsumptionStarted &&
43
+ attempt < retries &&
44
+ isRetryableMethod(method, retryMethods) &&
45
+ isRetryableError(error, normalizedInit.signal, retryStatuses);
46
+ if (!canRetry) {
47
+ cleanup();
48
+ throw timeoutSignal.aborted && timeoutSignal.reason instanceof TimeoutError ? timeoutSignal.reason : error;
49
+ }
50
+ await wait(retryDelay * (attempt + 1));
51
+ cleanup();
52
+ return run(attempt + 1);
53
+ }
54
+ };
55
+ return run();
56
+ };
package/types.d.ts CHANGED
@@ -5,4 +5,13 @@ export type Options = {
5
5
  retryMethods?: string[];
6
6
  retryStatuses?: number[];
7
7
  };
8
+ export type StreamChunkHandlerParams = {
9
+ attempt: number;
10
+ response: Response;
11
+ };
12
+ export type StreamChunkHandler = (chunk: Uint8Array, params: StreamChunkHandlerParams) => Promise<void> | void;
13
+ export type StreamOptions = Options & {
14
+ onChunk?: StreamChunkHandler;
15
+ };
8
16
  export type Request = <R = Record<string, unknown>>(input: RequestInfo | URL, init?: RequestInit | null, options?: Options) => Promise<R>;
17
+ export type RequestStream = (input: RequestInfo | URL, init?: RequestInit | null, options?: StreamOptions) => Promise<Response>;