aiox-core 5.0.0 → 5.0.2

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 (91) hide show
  1. package/.aiox-core/data/entity-registry.yaml +5297 -1814
  2. package/.aiox-core/data/registry-update-log.jsonl +2 -0
  3. package/.aiox-core/development/templates/service-template/README.md.hbs +158 -158
  4. package/.aiox-core/development/templates/service-template/__tests__/index.test.ts.hbs +237 -237
  5. package/.aiox-core/development/templates/service-template/client.ts.hbs +403 -403
  6. package/.aiox-core/development/templates/service-template/errors.ts.hbs +182 -182
  7. package/.aiox-core/development/templates/service-template/index.ts.hbs +120 -120
  8. package/.aiox-core/development/templates/service-template/package.json.hbs +87 -87
  9. package/.aiox-core/development/templates/service-template/types.ts.hbs +145 -145
  10. package/.aiox-core/development/templates/squad-template/LICENSE +21 -21
  11. package/.aiox-core/infrastructure/scripts/tool-resolver.js +4 -4
  12. package/.aiox-core/infrastructure/templates/aiox-sync.yaml.template +182 -182
  13. package/.aiox-core/infrastructure/templates/coderabbit.yaml.template +279 -279
  14. package/.aiox-core/infrastructure/templates/github-workflows/ci.yml.template +169 -169
  15. package/.aiox-core/infrastructure/templates/github-workflows/pr-automation.yml.template +330 -330
  16. package/.aiox-core/infrastructure/templates/github-workflows/release.yml.template +196 -196
  17. package/.aiox-core/infrastructure/templates/gitignore/gitignore-aiox-base.tmpl +63 -63
  18. package/.aiox-core/infrastructure/templates/gitignore/gitignore-brownfield-merge.tmpl +18 -18
  19. package/.aiox-core/infrastructure/templates/gitignore/gitignore-node.tmpl +85 -85
  20. package/.aiox-core/infrastructure/templates/gitignore/gitignore-python.tmpl +145 -145
  21. package/.aiox-core/install-manifest.yaml +58 -58
  22. package/.aiox-core/local-config.yaml.template +71 -71
  23. package/.aiox-core/monitor/hooks/lib/__init__.py +1 -1
  24. package/.aiox-core/monitor/hooks/lib/enrich.py +58 -58
  25. package/.aiox-core/monitor/hooks/lib/send_event.py +47 -47
  26. package/.aiox-core/monitor/hooks/notification.py +29 -29
  27. package/.aiox-core/monitor/hooks/post_tool_use.py +45 -45
  28. package/.aiox-core/monitor/hooks/pre_compact.py +29 -29
  29. package/.aiox-core/monitor/hooks/pre_tool_use.py +40 -40
  30. package/.aiox-core/monitor/hooks/stop.py +29 -29
  31. package/.aiox-core/monitor/hooks/subagent_stop.py +29 -29
  32. package/.aiox-core/monitor/hooks/user_prompt_submit.py +38 -38
  33. package/.aiox-core/product/templates/adr.hbs +125 -125
  34. package/.aiox-core/product/templates/dbdr.hbs +241 -241
  35. package/.aiox-core/product/templates/engine/elicitation.js +2 -3
  36. package/.aiox-core/product/templates/epic.hbs +212 -212
  37. package/.aiox-core/product/templates/pmdr.hbs +186 -186
  38. package/.aiox-core/product/templates/prd-v2.0.hbs +216 -216
  39. package/.aiox-core/product/templates/prd.hbs +201 -201
  40. package/.aiox-core/product/templates/story.hbs +263 -263
  41. package/.aiox-core/product/templates/task.hbs +170 -170
  42. package/.aiox-core/product/templates/tmpl-comment-on-examples.sql +158 -158
  43. package/.aiox-core/product/templates/tmpl-migration-script.sql +91 -91
  44. package/.aiox-core/product/templates/tmpl-rls-granular-policies.sql +104 -104
  45. package/.aiox-core/product/templates/tmpl-rls-kiss-policy.sql +10 -10
  46. package/.aiox-core/product/templates/tmpl-rls-roles.sql +135 -135
  47. package/.aiox-core/product/templates/tmpl-rls-simple.sql +77 -77
  48. package/.aiox-core/product/templates/tmpl-rls-tenant.sql +152 -152
  49. package/.aiox-core/product/templates/tmpl-rollback-script.sql +77 -77
  50. package/.aiox-core/product/templates/tmpl-seed-data.sql +140 -140
  51. package/.aiox-core/product/templates/tmpl-smoke-test.sql +16 -16
  52. package/.aiox-core/product/templates/tmpl-staging-copy-merge.sql +139 -139
  53. package/.aiox-core/product/templates/tmpl-stored-proc.sql +140 -140
  54. package/.aiox-core/product/templates/tmpl-trigger.sql +152 -152
  55. package/.aiox-core/product/templates/tmpl-view-materialized.sql +133 -133
  56. package/.aiox-core/product/templates/tmpl-view.sql +177 -177
  57. package/.aiox-core/scripts/pm.sh +0 -0
  58. package/.claude/hooks/code-intel-pretool.cjs +107 -0
  59. package/.claude/hooks/enforce-architecture-first.py +196 -196
  60. package/.claude/hooks/mind-clone-governance.py +192 -192
  61. package/.claude/hooks/read-protection.py +151 -151
  62. package/.claude/hooks/slug-validation.py +176 -176
  63. package/.claude/hooks/sql-governance.py +182 -182
  64. package/.claude/hooks/write-path-validation.py +194 -194
  65. package/LICENSE +33 -33
  66. package/bin/aiox-graph.js +0 -0
  67. package/bin/aiox-minimal.js +0 -0
  68. package/bin/aiox.js +0 -0
  69. package/docs/guides/aios-workflows/README.md +247 -0
  70. package/docs/guides/aios-workflows/bob-orchestrator-workflow.md +1536 -0
  71. package/package.json +1 -1
  72. package/packages/aiox-install/bin/aiox-install.js +0 -0
  73. package/packages/aiox-install/bin/edmcp.js +0 -0
  74. package/packages/aiox-pro-cli/bin/aiox-pro.js +0 -0
  75. package/packages/installer/src/wizard/pro-setup.js +210 -123
  76. package/pro/README.md +66 -0
  77. package/pro/license/degradation.js +220 -0
  78. package/pro/license/errors.js +450 -0
  79. package/pro/license/feature-gate.js +354 -0
  80. package/pro/license/index.js +181 -0
  81. package/pro/license/license-api.js +679 -0
  82. package/pro/license/license-cache.js +523 -0
  83. package/pro/license/license-crypto.js +303 -0
  84. package/scripts/check-markdown-links.py +352 -352
  85. package/scripts/dashboard-parallel-dev.sh +0 -0
  86. package/scripts/dashboard-parallel-phase3.sh +0 -0
  87. package/scripts/dashboard-parallel-phase4.sh +0 -0
  88. package/scripts/glue/README.md +355 -0
  89. package/scripts/glue/compose-agent-prompt.cjs +362 -0
  90. package/scripts/install-monitor-hooks.sh +0 -0
  91. package/.aiox-core/lib/build.json +0 -1
@@ -1,403 +1,403 @@
1
- /**
2
- * HTTP client for {{pascalCase serviceName}} API integration.
3
- * Includes rate limiting, retry logic with exponential backoff, and request logging.
4
- * @module @aiox/{{kebabCase serviceName}}/client
5
- * @story {{storyId}}
6
- */
7
-
8
- {{#if isApiIntegration}}
9
- import type {
10
- {{pascalCase serviceName}}Config,
11
- {{pascalCase serviceName}}ApiResponse,
12
- {{pascalCase serviceName}}RequestOptions,
13
- {{pascalCase serviceName}}RateLimit,
14
- } from './types';
15
- import {
16
- {{pascalCase serviceName}}Error,
17
- {{pascalCase serviceName}}ErrorCode,
18
- {{pascalCase serviceName}}Errors,
19
- } from './errors';
20
-
21
- /**
22
- * Default configuration values.
23
- */
24
- const DEFAULTS = {
25
- baseUrl: '{{apiBaseUrl}}',
26
- timeout: 30000,
27
- maxRetries: 3,
28
- retryBaseDelay: 1000,
29
- retryMaxDelay: 30000,
30
- debug: false,
31
- };
32
-
33
- /**
34
- * HTTP client for {{pascalCase serviceName}} API.
35
- */
36
- export class {{pascalCase serviceName}}Client {
37
- private readonly config: Required<Pick<{{pascalCase serviceName}}Config, 'baseUrl' | 'timeout' | 'maxRetries' | 'debug'>> & {{pascalCase serviceName}}Config;
38
- private rateLimit: {{pascalCase serviceName}}RateLimit | null = null;
39
-
40
- constructor(config: {{pascalCase serviceName}}Config) {
41
- this.config = {
42
- ...config,
43
- baseUrl: config.baseUrl ?? DEFAULTS.baseUrl,
44
- timeout: config.timeout ?? DEFAULTS.timeout,
45
- maxRetries: config.maxRetries ?? DEFAULTS.maxRetries,
46
- debug: config.debug ?? DEFAULTS.debug,
47
- };
48
- }
49
-
50
- /**
51
- * Make an API request with automatic retry and rate limiting.
52
- */
53
- async request<T>(
54
- endpoint: string,
55
- options: {{pascalCase serviceName}}RequestOptions = {}
56
- ): Promise<{{pascalCase serviceName}}ApiResponse<T>> {
57
- const {
58
- method = 'GET',
59
- headers = {},
60
- body,
61
- params,
62
- timeout = this.config.timeout,
63
- noRetry = false,
64
- } = options;
65
-
66
- // Build URL with query parameters
67
- const url = this.buildUrl(endpoint, params);
68
-
69
- // Wait for rate limit if necessary
70
- await this.waitForRateLimit();
71
-
72
- const requestHeaders: Record<string, string> = {
73
- 'Content-Type': 'application/json',
74
- 'Accept': 'application/json',
75
- ...this.getAuthHeaders(),
76
- ...headers,
77
- };
78
-
79
- const requestInit: RequestInit = {
80
- method,
81
- headers: requestHeaders,
82
- body: body ? JSON.stringify(body) : undefined,
83
- };
84
-
85
- // Retry logic
86
- const maxAttempts = noRetry ? 1 : this.config.maxRetries + 1;
87
- let lastError: Error | null = null;
88
-
89
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
90
- try {
91
- this.debug(`Request attempt ${attempt}/${maxAttempts}: ${method} ${url}`);
92
-
93
- const response = await this.fetchWithTimeout(url, requestInit, timeout);
94
-
95
- // Update rate limit info from headers
96
- this.updateRateLimit(response.headers);
97
-
98
- // Handle rate limiting (429)
99
- if (response.status === 429) {
100
- const retryAfter = this.getRetryAfter(response.headers);
101
- if (attempt < maxAttempts) {
102
- this.debug(`Rate limited, waiting ${retryAfter}ms before retry`);
103
- await this.sleep(retryAfter);
104
- continue;
105
- }
106
- throw {{pascalCase serviceName}}Errors.rateLimitError(
107
- Math.ceil(retryAfter / 1000),
108
- this.rateLimit ?? { remaining: 0, reset: Date.now() + retryAfter }
109
- );
110
- }
111
-
112
- // Parse response
113
- const data = await this.parseResponse<T>(response);
114
-
115
- // Handle error responses
116
- if (!response.ok) {
117
- throw this.handleErrorResponse(response.status, data);
118
- }
119
-
120
- return {
121
- success: true,
122
- data: data as T,
123
- meta: {
124
- requestId: response.headers.get('x-request-id') ?? undefined,
125
- rateLimit: this.rateLimit ?? undefined,
126
- },
127
- };
128
- } catch (error) {
129
- lastError = error as Error;
130
-
131
- // Don't retry on certain errors
132
- if (
133
- error instanceof {{pascalCase serviceName}}Error &&
134
- [
135
- {{pascalCase serviceName}}ErrorCode.AUTHENTICATION_ERROR,
136
- {{pascalCase serviceName}}ErrorCode.AUTHORIZATION_ERROR,
137
- {{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR,
138
- ].includes(error.code)
139
- ) {
140
- throw error;
141
- }
142
-
143
- // Retry with exponential backoff
144
- if (attempt < maxAttempts) {
145
- const delay = this.calculateBackoff(attempt);
146
- this.debug(`Request failed, retrying in ${delay}ms: ${(error as Error).message}`);
147
- await this.sleep(delay);
148
- }
149
- }
150
- }
151
-
152
- // All retries exhausted
153
- throw lastError instanceof {{pascalCase serviceName}}Error
154
- ? lastError
155
- : {{pascalCase serviceName}}Errors.networkError(
156
- `Request failed after ${maxAttempts} attempts`,
157
- lastError ?? undefined
158
- );
159
- }
160
-
161
- /**
162
- * Convenience method for GET requests.
163
- */
164
- async get<T>(endpoint: string, params?: Record<string, string | number | boolean>): Promise<T> {
165
- const response = await this.request<T>(endpoint, { method: 'GET', params });
166
- return response.data as T;
167
- }
168
-
169
- /**
170
- * Convenience method for POST requests.
171
- */
172
- async post<T>(endpoint: string, body?: unknown): Promise<T> {
173
- const response = await this.request<T>(endpoint, { method: 'POST', body });
174
- return response.data as T;
175
- }
176
-
177
- /**
178
- * Convenience method for PUT requests.
179
- */
180
- async put<T>(endpoint: string, body?: unknown): Promise<T> {
181
- const response = await this.request<T>(endpoint, { method: 'PUT', body });
182
- return response.data as T;
183
- }
184
-
185
- /**
186
- * Convenience method for DELETE requests.
187
- */
188
- async delete<T>(endpoint: string): Promise<T> {
189
- const response = await this.request<T>(endpoint, { method: 'DELETE' });
190
- return response.data as T;
191
- }
192
-
193
- /**
194
- * Health check / ping endpoint.
195
- */
196
- async ping(): Promise<boolean> {
197
- try {
198
- await this.get('/ping');
199
- return true;
200
- } catch {
201
- return false;
202
- }
203
- }
204
-
205
- /**
206
- * Get current rate limit status.
207
- */
208
- getRateLimit(): {{pascalCase serviceName}}RateLimit | null {
209
- return this.rateLimit;
210
- }
211
-
212
- // ─────────────────────────────────────────────────────────────────────────────
213
- // Private Methods
214
- // ─────────────────────────────────────────────────────────────────────────────
215
-
216
- /**
217
- * Build full URL with query parameters.
218
- */
219
- private buildUrl(
220
- endpoint: string,
221
- params?: Record<string, string | number | boolean>
222
- ): string {
223
- const baseUrl = this.config.baseUrl.replace(/\/$/, '');
224
- const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
225
- const url = new URL(`${baseUrl}${path}`);
226
-
227
- if (params) {
228
- Object.entries(params).forEach(([key, value]) => {
229
- if (value !== undefined && value !== null) {
230
- url.searchParams.append(key, String(value));
231
- }
232
- });
233
- }
234
-
235
- return url.toString();
236
- }
237
-
238
- /**
239
- * Get authentication headers.
240
- */
241
- private getAuthHeaders(): Record<string, string> {
242
- const headers: Record<string, string> = {};
243
-
244
- {{#each envVars}}
245
- {{#if this.isAuthHeader}}
246
- if (this.config.{{camelCase this.name}}) {
247
- headers['{{this.headerName}}'] = {{#if this.headerPrefix}}`{{this.headerPrefix}} ${this.config.{{camelCase this.name}}}`{{else}}this.config.{{camelCase this.name}}{{/if}};
248
- }
249
- {{/if}}
250
- {{/each}}
251
-
252
- return headers;
253
- }
254
-
255
- /**
256
- * Fetch with timeout support.
257
- */
258
- private async fetchWithTimeout(
259
- url: string,
260
- init: RequestInit,
261
- timeout: number
262
- ): Promise<Response> {
263
- const controller = new AbortController();
264
- const timeoutId = setTimeout(() => controller.abort(), timeout);
265
-
266
- try {
267
- const response = await fetch(url, {
268
- ...init,
269
- signal: controller.signal,
270
- });
271
- return response;
272
- } catch (error) {
273
- if ((error as Error).name === 'AbortError') {
274
- throw {{pascalCase serviceName}}Errors.timeoutError(`Request timed out after ${timeout}ms`);
275
- }
276
- throw error;
277
- } finally {
278
- clearTimeout(timeoutId);
279
- }
280
- }
281
-
282
- /**
283
- * Parse response body.
284
- */
285
- private async parseResponse<T>(response: Response): Promise<T | null> {
286
- const contentType = response.headers.get('content-type');
287
-
288
- if (contentType?.includes('application/json')) {
289
- try {
290
- return await response.json();
291
- } catch {
292
- return null;
293
- }
294
- }
295
-
296
- return null;
297
- }
298
-
299
- /**
300
- * Handle error response.
301
- */
302
- private handleErrorResponse(status: number, data: unknown): {{pascalCase serviceName}}Error {
303
- const errorData = data as { error?: { message?: string; code?: string } } | null;
304
- const message = errorData?.error?.message ?? `Request failed with status ${status}`;
305
-
306
- switch (status) {
307
- case 401:
308
- return {{pascalCase serviceName}}Errors.authenticationError(message);
309
- case 403:
310
- return {{pascalCase serviceName}}Errors.authorizationError(message);
311
- default:
312
- return {{pascalCase serviceName}}Errors.apiError(status, message, errorData ?? undefined);
313
- }
314
- }
315
-
316
- /**
317
- * Update rate limit from response headers.
318
- */
319
- private updateRateLimit(headers: Headers): void {
320
- const limit = headers.get('x-ratelimit-limit');
321
- const remaining = headers.get('x-ratelimit-remaining');
322
- const reset = headers.get('x-ratelimit-reset');
323
-
324
- if (limit && remaining && reset) {
325
- const parsedLimit = parseInt(limit, 10);
326
- const parsedRemaining = parseInt(remaining, 10);
327
- const parsedReset = parseInt(reset, 10);
328
-
329
- if (isNaN(parsedLimit) || isNaN(parsedRemaining) || isNaN(parsedReset)) {
330
- this.debug('Invalid rate limit headers received');
331
- return;
332
- }
333
-
334
- this.rateLimit = {
335
- limit: parsedLimit,
336
- remaining: parsedRemaining,
337
- reset: parsedReset * 1000, // Convert to milliseconds
338
- };
339
- }
340
- }
341
-
342
- /**
343
- * Wait if rate limited.
344
- */
345
- private async waitForRateLimit(): Promise<void> {
346
- if (this.rateLimit && this.rateLimit.remaining <= 0) {
347
- const waitTime = Math.max(0, this.rateLimit.reset - Date.now());
348
- if (waitTime > 0) {
349
- this.debug(`Rate limit reached, waiting ${waitTime}ms`);
350
- await this.sleep(waitTime);
351
- }
352
- }
353
- }
354
-
355
- /**
356
- * Get retry-after delay from headers.
357
- */
358
- private getRetryAfter(headers: Headers): number {
359
- const retryAfter = headers.get('retry-after');
360
- if (retryAfter) {
361
- // Could be seconds or HTTP date
362
- const seconds = parseInt(retryAfter, 10);
363
- if (!isNaN(seconds)) {
364
- return seconds * 1000;
365
- }
366
- const date = new Date(retryAfter);
367
- if (!isNaN(date.getTime())) {
368
- return Math.max(0, date.getTime() - Date.now());
369
- }
370
- }
371
- return DEFAULTS.retryBaseDelay;
372
- }
373
-
374
- /**
375
- * Calculate exponential backoff delay.
376
- */
377
- private calculateBackoff(attempt: number): number {
378
- const delay = DEFAULTS.retryBaseDelay * Math.pow(2, attempt - 1);
379
- // Add jitter (±25%)
380
- const jitter = delay * 0.25 * (Math.random() * 2 - 1);
381
- return Math.min(delay + jitter, DEFAULTS.retryMaxDelay);
382
- }
383
-
384
- /**
385
- * Sleep for specified milliseconds.
386
- */
387
- private sleep(ms: number): Promise<void> {
388
- return new Promise((resolve) => setTimeout(resolve, ms));
389
- }
390
-
391
- /**
392
- * Debug logging.
393
- */
394
- private debug(message: string): void {
395
- if (this.config.debug) {
396
- console.debug(`[{{pascalCase serviceName}}Client] ${message}`);
397
- }
398
- }
399
- }
400
- {{else}}
401
- // This file is only generated for API integrations (isApiIntegration: true)
402
- export {};
403
- {{/if}}
1
+ /**
2
+ * HTTP client for {{pascalCase serviceName}} API integration.
3
+ * Includes rate limiting, retry logic with exponential backoff, and request logging.
4
+ * @module @aiox/{{kebabCase serviceName}}/client
5
+ * @story {{storyId}}
6
+ */
7
+
8
+ {{#if isApiIntegration}}
9
+ import type {
10
+ {{pascalCase serviceName}}Config,
11
+ {{pascalCase serviceName}}ApiResponse,
12
+ {{pascalCase serviceName}}RequestOptions,
13
+ {{pascalCase serviceName}}RateLimit,
14
+ } from './types';
15
+ import {
16
+ {{pascalCase serviceName}}Error,
17
+ {{pascalCase serviceName}}ErrorCode,
18
+ {{pascalCase serviceName}}Errors,
19
+ } from './errors';
20
+
21
+ /**
22
+ * Default configuration values.
23
+ */
24
+ const DEFAULTS = {
25
+ baseUrl: '{{apiBaseUrl}}',
26
+ timeout: 30000,
27
+ maxRetries: 3,
28
+ retryBaseDelay: 1000,
29
+ retryMaxDelay: 30000,
30
+ debug: false,
31
+ };
32
+
33
+ /**
34
+ * HTTP client for {{pascalCase serviceName}} API.
35
+ */
36
+ export class {{pascalCase serviceName}}Client {
37
+ private readonly config: Required<Pick<{{pascalCase serviceName}}Config, 'baseUrl' | 'timeout' | 'maxRetries' | 'debug'>> & {{pascalCase serviceName}}Config;
38
+ private rateLimit: {{pascalCase serviceName}}RateLimit | null = null;
39
+
40
+ constructor(config: {{pascalCase serviceName}}Config) {
41
+ this.config = {
42
+ ...config,
43
+ baseUrl: config.baseUrl ?? DEFAULTS.baseUrl,
44
+ timeout: config.timeout ?? DEFAULTS.timeout,
45
+ maxRetries: config.maxRetries ?? DEFAULTS.maxRetries,
46
+ debug: config.debug ?? DEFAULTS.debug,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Make an API request with automatic retry and rate limiting.
52
+ */
53
+ async request<T>(
54
+ endpoint: string,
55
+ options: {{pascalCase serviceName}}RequestOptions = {}
56
+ ): Promise<{{pascalCase serviceName}}ApiResponse<T>> {
57
+ const {
58
+ method = 'GET',
59
+ headers = {},
60
+ body,
61
+ params,
62
+ timeout = this.config.timeout,
63
+ noRetry = false,
64
+ } = options;
65
+
66
+ // Build URL with query parameters
67
+ const url = this.buildUrl(endpoint, params);
68
+
69
+ // Wait for rate limit if necessary
70
+ await this.waitForRateLimit();
71
+
72
+ const requestHeaders: Record<string, string> = {
73
+ 'Content-Type': 'application/json',
74
+ 'Accept': 'application/json',
75
+ ...this.getAuthHeaders(),
76
+ ...headers,
77
+ };
78
+
79
+ const requestInit: RequestInit = {
80
+ method,
81
+ headers: requestHeaders,
82
+ body: body ? JSON.stringify(body) : undefined,
83
+ };
84
+
85
+ // Retry logic
86
+ const maxAttempts = noRetry ? 1 : this.config.maxRetries + 1;
87
+ let lastError: Error | null = null;
88
+
89
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
90
+ try {
91
+ this.debug(`Request attempt ${attempt}/${maxAttempts}: ${method} ${url}`);
92
+
93
+ const response = await this.fetchWithTimeout(url, requestInit, timeout);
94
+
95
+ // Update rate limit info from headers
96
+ this.updateRateLimit(response.headers);
97
+
98
+ // Handle rate limiting (429)
99
+ if (response.status === 429) {
100
+ const retryAfter = this.getRetryAfter(response.headers);
101
+ if (attempt < maxAttempts) {
102
+ this.debug(`Rate limited, waiting ${retryAfter}ms before retry`);
103
+ await this.sleep(retryAfter);
104
+ continue;
105
+ }
106
+ throw {{pascalCase serviceName}}Errors.rateLimitError(
107
+ Math.ceil(retryAfter / 1000),
108
+ this.rateLimit ?? { remaining: 0, reset: Date.now() + retryAfter }
109
+ );
110
+ }
111
+
112
+ // Parse response
113
+ const data = await this.parseResponse<T>(response);
114
+
115
+ // Handle error responses
116
+ if (!response.ok) {
117
+ throw this.handleErrorResponse(response.status, data);
118
+ }
119
+
120
+ return {
121
+ success: true,
122
+ data: data as T,
123
+ meta: {
124
+ requestId: response.headers.get('x-request-id') ?? undefined,
125
+ rateLimit: this.rateLimit ?? undefined,
126
+ },
127
+ };
128
+ } catch (error) {
129
+ lastError = error as Error;
130
+
131
+ // Don't retry on certain errors
132
+ if (
133
+ error instanceof {{pascalCase serviceName}}Error &&
134
+ [
135
+ {{pascalCase serviceName}}ErrorCode.AUTHENTICATION_ERROR,
136
+ {{pascalCase serviceName}}ErrorCode.AUTHORIZATION_ERROR,
137
+ {{pascalCase serviceName}}ErrorCode.CONFIGURATION_ERROR,
138
+ ].includes(error.code)
139
+ ) {
140
+ throw error;
141
+ }
142
+
143
+ // Retry with exponential backoff
144
+ if (attempt < maxAttempts) {
145
+ const delay = this.calculateBackoff(attempt);
146
+ this.debug(`Request failed, retrying in ${delay}ms: ${(error as Error).message}`);
147
+ await this.sleep(delay);
148
+ }
149
+ }
150
+ }
151
+
152
+ // All retries exhausted
153
+ throw lastError instanceof {{pascalCase serviceName}}Error
154
+ ? lastError
155
+ : {{pascalCase serviceName}}Errors.networkError(
156
+ `Request failed after ${maxAttempts} attempts`,
157
+ lastError ?? undefined
158
+ );
159
+ }
160
+
161
+ /**
162
+ * Convenience method for GET requests.
163
+ */
164
+ async get<T>(endpoint: string, params?: Record<string, string | number | boolean>): Promise<T> {
165
+ const response = await this.request<T>(endpoint, { method: 'GET', params });
166
+ return response.data as T;
167
+ }
168
+
169
+ /**
170
+ * Convenience method for POST requests.
171
+ */
172
+ async post<T>(endpoint: string, body?: unknown): Promise<T> {
173
+ const response = await this.request<T>(endpoint, { method: 'POST', body });
174
+ return response.data as T;
175
+ }
176
+
177
+ /**
178
+ * Convenience method for PUT requests.
179
+ */
180
+ async put<T>(endpoint: string, body?: unknown): Promise<T> {
181
+ const response = await this.request<T>(endpoint, { method: 'PUT', body });
182
+ return response.data as T;
183
+ }
184
+
185
+ /**
186
+ * Convenience method for DELETE requests.
187
+ */
188
+ async delete<T>(endpoint: string): Promise<T> {
189
+ const response = await this.request<T>(endpoint, { method: 'DELETE' });
190
+ return response.data as T;
191
+ }
192
+
193
+ /**
194
+ * Health check / ping endpoint.
195
+ */
196
+ async ping(): Promise<boolean> {
197
+ try {
198
+ await this.get('/ping');
199
+ return true;
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Get current rate limit status.
207
+ */
208
+ getRateLimit(): {{pascalCase serviceName}}RateLimit | null {
209
+ return this.rateLimit;
210
+ }
211
+
212
+ // ─────────────────────────────────────────────────────────────────────────────
213
+ // Private Methods
214
+ // ─────────────────────────────────────────────────────────────────────────────
215
+
216
+ /**
217
+ * Build full URL with query parameters.
218
+ */
219
+ private buildUrl(
220
+ endpoint: string,
221
+ params?: Record<string, string | number | boolean>
222
+ ): string {
223
+ const baseUrl = this.config.baseUrl.replace(/\/$/, '');
224
+ const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
225
+ const url = new URL(`${baseUrl}${path}`);
226
+
227
+ if (params) {
228
+ Object.entries(params).forEach(([key, value]) => {
229
+ if (value !== undefined && value !== null) {
230
+ url.searchParams.append(key, String(value));
231
+ }
232
+ });
233
+ }
234
+
235
+ return url.toString();
236
+ }
237
+
238
+ /**
239
+ * Get authentication headers.
240
+ */
241
+ private getAuthHeaders(): Record<string, string> {
242
+ const headers: Record<string, string> = {};
243
+
244
+ {{#each envVars}}
245
+ {{#if this.isAuthHeader}}
246
+ if (this.config.{{camelCase this.name}}) {
247
+ headers['{{this.headerName}}'] = {{#if this.headerPrefix}}`{{this.headerPrefix}} ${this.config.{{camelCase this.name}}}`{{else}}this.config.{{camelCase this.name}}{{/if}};
248
+ }
249
+ {{/if}}
250
+ {{/each}}
251
+
252
+ return headers;
253
+ }
254
+
255
+ /**
256
+ * Fetch with timeout support.
257
+ */
258
+ private async fetchWithTimeout(
259
+ url: string,
260
+ init: RequestInit,
261
+ timeout: number
262
+ ): Promise<Response> {
263
+ const controller = new AbortController();
264
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
265
+
266
+ try {
267
+ const response = await fetch(url, {
268
+ ...init,
269
+ signal: controller.signal,
270
+ });
271
+ return response;
272
+ } catch (error) {
273
+ if ((error as Error).name === 'AbortError') {
274
+ throw {{pascalCase serviceName}}Errors.timeoutError(`Request timed out after ${timeout}ms`);
275
+ }
276
+ throw error;
277
+ } finally {
278
+ clearTimeout(timeoutId);
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Parse response body.
284
+ */
285
+ private async parseResponse<T>(response: Response): Promise<T | null> {
286
+ const contentType = response.headers.get('content-type');
287
+
288
+ if (contentType?.includes('application/json')) {
289
+ try {
290
+ return await response.json();
291
+ } catch {
292
+ return null;
293
+ }
294
+ }
295
+
296
+ return null;
297
+ }
298
+
299
+ /**
300
+ * Handle error response.
301
+ */
302
+ private handleErrorResponse(status: number, data: unknown): {{pascalCase serviceName}}Error {
303
+ const errorData = data as { error?: { message?: string; code?: string } } | null;
304
+ const message = errorData?.error?.message ?? `Request failed with status ${status}`;
305
+
306
+ switch (status) {
307
+ case 401:
308
+ return {{pascalCase serviceName}}Errors.authenticationError(message);
309
+ case 403:
310
+ return {{pascalCase serviceName}}Errors.authorizationError(message);
311
+ default:
312
+ return {{pascalCase serviceName}}Errors.apiError(status, message, errorData ?? undefined);
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Update rate limit from response headers.
318
+ */
319
+ private updateRateLimit(headers: Headers): void {
320
+ const limit = headers.get('x-ratelimit-limit');
321
+ const remaining = headers.get('x-ratelimit-remaining');
322
+ const reset = headers.get('x-ratelimit-reset');
323
+
324
+ if (limit && remaining && reset) {
325
+ const parsedLimit = parseInt(limit, 10);
326
+ const parsedRemaining = parseInt(remaining, 10);
327
+ const parsedReset = parseInt(reset, 10);
328
+
329
+ if (isNaN(parsedLimit) || isNaN(parsedRemaining) || isNaN(parsedReset)) {
330
+ this.debug('Invalid rate limit headers received');
331
+ return;
332
+ }
333
+
334
+ this.rateLimit = {
335
+ limit: parsedLimit,
336
+ remaining: parsedRemaining,
337
+ reset: parsedReset * 1000, // Convert to milliseconds
338
+ };
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Wait if rate limited.
344
+ */
345
+ private async waitForRateLimit(): Promise<void> {
346
+ if (this.rateLimit && this.rateLimit.remaining <= 0) {
347
+ const waitTime = Math.max(0, this.rateLimit.reset - Date.now());
348
+ if (waitTime > 0) {
349
+ this.debug(`Rate limit reached, waiting ${waitTime}ms`);
350
+ await this.sleep(waitTime);
351
+ }
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Get retry-after delay from headers.
357
+ */
358
+ private getRetryAfter(headers: Headers): number {
359
+ const retryAfter = headers.get('retry-after');
360
+ if (retryAfter) {
361
+ // Could be seconds or HTTP date
362
+ const seconds = parseInt(retryAfter, 10);
363
+ if (!isNaN(seconds)) {
364
+ return seconds * 1000;
365
+ }
366
+ const date = new Date(retryAfter);
367
+ if (!isNaN(date.getTime())) {
368
+ return Math.max(0, date.getTime() - Date.now());
369
+ }
370
+ }
371
+ return DEFAULTS.retryBaseDelay;
372
+ }
373
+
374
+ /**
375
+ * Calculate exponential backoff delay.
376
+ */
377
+ private calculateBackoff(attempt: number): number {
378
+ const delay = DEFAULTS.retryBaseDelay * Math.pow(2, attempt - 1);
379
+ // Add jitter (±25%)
380
+ const jitter = delay * 0.25 * (Math.random() * 2 - 1);
381
+ return Math.min(delay + jitter, DEFAULTS.retryMaxDelay);
382
+ }
383
+
384
+ /**
385
+ * Sleep for specified milliseconds.
386
+ */
387
+ private sleep(ms: number): Promise<void> {
388
+ return new Promise((resolve) => setTimeout(resolve, ms));
389
+ }
390
+
391
+ /**
392
+ * Debug logging.
393
+ */
394
+ private debug(message: string): void {
395
+ if (this.config.debug) {
396
+ console.debug(`[{{pascalCase serviceName}}Client] ${message}`);
397
+ }
398
+ }
399
+ }
400
+ {{else}}
401
+ // This file is only generated for API integrations (isApiIntegration: true)
402
+ export {};
403
+ {{/if}}