@atomic-solutions/wordpress-api-client 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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -0
  3. package/dist/calculatePagination-WUlN3OdM.d.cts +19 -0
  4. package/dist/calculatePagination-WUlN3OdM.d.ts +19 -0
  5. package/dist/client/index.cjs +1143 -0
  6. package/dist/client/index.cjs.map +1 -0
  7. package/dist/client/index.d.cts +10 -0
  8. package/dist/client/index.d.ts +10 -0
  9. package/dist/client/index.js +1137 -0
  10. package/dist/client/index.js.map +1 -0
  11. package/dist/http/index.cjs +674 -0
  12. package/dist/http/index.cjs.map +1 -0
  13. package/dist/http/index.d.cts +12 -0
  14. package/dist/http/index.d.ts +12 -0
  15. package/dist/http/index.js +667 -0
  16. package/dist/http/index.js.map +1 -0
  17. package/dist/index.cjs +1251 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +51 -0
  20. package/dist/index.d.ts +51 -0
  21. package/dist/index.js +1205 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/schemas/index.cjs +414 -0
  24. package/dist/schemas/index.cjs.map +1 -0
  25. package/dist/schemas/index.d.cts +1339 -0
  26. package/dist/schemas/index.d.ts +1339 -0
  27. package/dist/schemas/index.js +376 -0
  28. package/dist/schemas/index.js.map +1 -0
  29. package/dist/testing/index.cjs +1435 -0
  30. package/dist/testing/index.cjs.map +1 -0
  31. package/dist/testing/index.d.cts +50 -0
  32. package/dist/testing/index.d.ts +50 -0
  33. package/dist/testing/index.js +1426 -0
  34. package/dist/testing/index.js.map +1 -0
  35. package/dist/types-8pbwmNdu.d.ts +154 -0
  36. package/dist/types-BTo088EY.d.cts +154 -0
  37. package/dist/user.schema-eeUHQ4sI.d.cts +10614 -0
  38. package/dist/user.schema-eeUHQ4sI.d.ts +10614 -0
  39. package/dist/utils/index.cjs +47 -0
  40. package/dist/utils/index.cjs.map +1 -0
  41. package/dist/utils/index.d.cts +10 -0
  42. package/dist/utils/index.d.ts +10 -0
  43. package/dist/utils/index.js +44 -0
  44. package/dist/utils/index.js.map +1 -0
  45. package/package.json +103 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2026 Atomic Solutions
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 ADDED
@@ -0,0 +1,295 @@
1
+ # @atomic-solutions/wordpress-utils
2
+
3
+ Type-safe WordPress REST API client (platform-agnostic)
4
+
5
+ > **⚛️ React users:** This is a platform-agnostic client. If you're using React or React Native, use [`@atomic-solutions/react-wordpress`](../react-wordpress/) instead for React Query hooks and context providers.
6
+
7
+ ## Features
8
+
9
+ - 🔒 **Type-safe**: Full TypeScript support with Zod schema validation
10
+ - 🌐 **Platform-agnostic**: Works in Node.js, browsers, React, React Native
11
+ - 🔐 **JWT Authentication**: Support for JWT Authentication plugin
12
+ - 📄 **Pagination**: Automatic handling of WordPress pagination headers
13
+ - 🎯 **Error Handling**: Built-in error classes with optional error reporter injection
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pnpm add @atomic-solutions/wordpress-utils
19
+ ```
20
+
21
+ **For React/React Native projects, install react-wordpress instead:**
22
+
23
+ ```bash
24
+ pnpm add @atomic-solutions/react-wordpress
25
+ ```
26
+
27
+ ### Peer Dependencies
28
+
29
+ ```bash
30
+ pnpm add axios zod
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ > **React users:** See [`@atomic-solutions/react-wordpress`](../react-wordpress/) for React Query hooks and provider.
36
+
37
+ ### Basic Usage (Platform-agnostic)
38
+
39
+ ```typescript
40
+ import { createClient } from '@atomic-solutions/wordpress-utils';
41
+
42
+ // Create a client
43
+ const client = createClient({
44
+ baseURL: 'https://example.com/wp-json',
45
+ jwtToken: {
46
+ get: () => AsyncStorage.getItem('wp_jwt_token'),
47
+ },
48
+ });
49
+
50
+ // Use the API directly
51
+ const posts = await client.posts.list({ per_page: 10 });
52
+ const post = await client.posts.get(123);
53
+ const categories = await client.categories.list();
54
+ ```
55
+
56
+ ## API Reference
57
+
58
+ ### Client Configuration
59
+
60
+ ```typescript
61
+ interface WordPressConfig {
62
+ baseURL: string; // WordPress wp-json URL
63
+ jwtToken?: JwtTokenAdapter; // Optional JWT token provider
64
+ queryKeyPrefix?: string[]; // Query key prefix (default: ['wordpress'])
65
+ timeout?: number; // Request timeout (default: 30000)
66
+ headers?: Record<string, string>; // Custom headers
67
+ errorReporter?: ErrorReporter; // Optional error reporter for tracking (default: console.error)
68
+ onRequest?: (config) => config; // Request interceptor
69
+ onResponse?: (response) => response; // Response interceptor
70
+ onError?: (error) => void; // Error handler
71
+ }
72
+ ```
73
+
74
+ ### Client API Methods
75
+
76
+ The client provides direct access to all WordPress REST API endpoints:
77
+
78
+ ```typescript
79
+
80
+ // Posts
81
+ const posts = await client.posts.list({ per_page: 10 });
82
+ const post = await client.posts.get(123);
83
+ const postBySlug = await client.posts.getBySlug('hello-world');
84
+
85
+ // Categories
86
+ const categories = await client.categories.list();
87
+ const category = await client.categories.get(5);
88
+
89
+ // Media
90
+ const media = await client.media.get(456);
91
+
92
+ // Users (requires authentication)
93
+ const currentUser = await client.users.me();
94
+
95
+ // Auth
96
+ const token = await client.auth.login({ username: 'user', password: 'pass' });
97
+ const isValid = await client.auth.validateToken();
98
+ ```
99
+
100
+ ## Error Handling
101
+
102
+ ```typescript
103
+ import { WordPressError } from '@atomic-solutions/wordpress-utils';
104
+
105
+ try {
106
+ await client.posts.get(999);
107
+ } catch (error) {
108
+ if (error instanceof WordPressError) {
109
+ console.log(error.userMessage); // User-friendly message
110
+ console.log(error.wpCode); // WordPress error code
111
+ console.log(error.retryable); // Whether to retry
112
+ console.log(error.isAuthError); // Authentication error?
113
+ console.log(error.isNotFoundError); // 404 error?
114
+ }
115
+ }
116
+ ```
117
+
118
+ ### Error Reporter Integration
119
+
120
+ You can integrate with error tracking services like Sentry:
121
+
122
+ ```typescript
123
+ import * as Sentry from '@sentry/react-native';
124
+ import { createClient } from '@atomic-solutions/wordpress-utils';
125
+
126
+ const client = createClient({
127
+ baseURL: 'https://example.com/wp-json',
128
+ errorReporter: {
129
+ report: (error) => Sentry.captureException(error),
130
+ },
131
+ });
132
+ ```
133
+
134
+ ## Integration Testing
135
+
136
+ The package provides testing utilities for consumer projects to verify WordPress API connectivity in CI/CD pipelines.
137
+
138
+ ### Quick Health Check
139
+
140
+ ```typescript
141
+ import { createClient } from '@atomic-solutions/wordpress-utils';
142
+ import { runHealthCheck, assertHealthy } from '@atomic-solutions/wordpress-utils/testing';
143
+
144
+ test('WordPress API is healthy', async () => {
145
+ const client = createClient({ baseURL: process.env.WP_API_URL! });
146
+ const report = await runHealthCheck(client);
147
+
148
+ assertHealthy(report); // Throws if any check fails
149
+ expect(report.overall).toBe(true);
150
+ }, 30000);
151
+ ```
152
+
153
+ ### Health Checker Factory
154
+
155
+ ```typescript
156
+ import { createHealthChecker } from '@atomic-solutions/wordpress-utils/testing';
157
+
158
+ const checkHealth = createHealthChecker({
159
+ baseURL: process.env.WP_API_URL!,
160
+ });
161
+
162
+ test('WordPress API responds', async () => {
163
+ const report = await checkHealth();
164
+ expect(report.summary.failed).toBe(0);
165
+ });
166
+ ```
167
+
168
+ ### Full Test Suite
169
+
170
+ For comprehensive integration testing, use the pre-built test suite:
171
+
172
+ ```typescript
173
+ // wordpress-api.integration.test.ts
174
+ import { createWordPressTestSuite } from '@atomic-solutions/wordpress-utils/testing';
175
+
176
+ createWordPressTestSuite({
177
+ config: {
178
+ baseURL: process.env.WP_API_URL || 'https://example.com/wp-json',
179
+ },
180
+ timeout: 30000,
181
+ skipMedia: false, // Set true if site has no media
182
+ skipAuth: true, // Set false if testing JWT auth
183
+ });
184
+ ```
185
+
186
+ This runs tests for:
187
+ - Health check (connectivity, schema validation)
188
+ - Posts API (list, single, slug lookup, pagination)
189
+ - Categories API (list, single)
190
+ - Media API (featured images)
191
+ - Auth API (JWT validation, if enabled)
192
+
193
+ ### Health Check Report
194
+
195
+ ```typescript
196
+ interface HealthCheckReport {
197
+ baseURL: string;
198
+ timestamp: string;
199
+ overall: boolean; // true if all checks passed
200
+ results: HealthCheckResult[];
201
+ summary: {
202
+ passed: number;
203
+ failed: number;
204
+ total: number;
205
+ };
206
+ }
207
+ ```
208
+
209
+ ## Tree-shaking Support
210
+
211
+ Import only what you need for optimal bundle size:
212
+
213
+ ```typescript
214
+ // Import just the client
215
+ import { createClient } from '@atomic-solutions/wordpress-utils/client';
216
+
217
+ // Import just schemas
218
+ import { PostSchema, CategorySchema } from '@atomic-solutions/wordpress-utils/schemas';
219
+
220
+ // Import just HTTP utilities
221
+ import { calculatePagination } from '@atomic-solutions/wordpress-utils/http';
222
+
223
+ // Import just query keys utility
224
+ import { createQueryKeys } from '@atomic-solutions/wordpress-utils/utils';
225
+ ```
226
+
227
+ ## Migration from v1.x
228
+
229
+ If you were using React hooks from v1.x, follow these steps:
230
+
231
+ ### 1. Install react-wordpress
232
+
233
+ ```bash
234
+ pnpm add @atomic-solutions/react-wordpress
235
+ ```
236
+
237
+ ### 2. Update Imports
238
+
239
+ ```typescript
240
+ // Before (v1.x)
241
+ import { usePosts, WordPressProvider } from '@atomic-solutions/wordpress-utils';
242
+
243
+ // After (v2.x)
244
+ import { usePosts, WordPressProvider } from '@atomic-solutions/react-wordpress';
245
+ ```
246
+
247
+ ### 3. Update Dependencies
248
+
249
+ ```json
250
+ {
251
+ "dependencies": {
252
+ "@atomic-solutions/wordpress-utils": "^2.0.0",
253
+ "@atomic-solutions/react-wordpress": "^1.1.0"
254
+ }
255
+ }
256
+ ```
257
+
258
+ **That's it!** The API is identical - only the package name changed.
259
+
260
+ ### What Changed in v2.0.0
261
+
262
+ - ❌ **Removed**: React hooks (usePosts, useCategories, etc.) - now in `react-wordpress`
263
+ - ❌ **Removed**: WordPressProvider and WordPressContext - now in `react-wordpress`
264
+ - ❌ **Removed**: React and React Query peer dependencies
265
+ - ✅ **Added**: `/schemas` export path for tree-shaking
266
+ - ✅ **Added**: `/utils` export path for query keys utility
267
+ - ✅ **Improved**: Test coverage (112+ tests)
268
+
269
+ ### If You're NOT Using React
270
+
271
+ No breaking changes! Just update the version:
272
+
273
+ ```json
274
+ {
275
+ "dependencies": {
276
+ "@atomic-solutions/wordpress-utils": "^2.0.0"
277
+ }
278
+ }
279
+ ```
280
+
281
+ ## Architecture
282
+
283
+ ```
284
+ schemas (Zod schemas)
285
+
286
+ wordpress-utils (platform-agnostic API client)
287
+
288
+ react-wordpress (React Query hooks + provider)
289
+
290
+ React / React Native apps
291
+ ```
292
+
293
+ ## License
294
+
295
+ MIT
@@ -0,0 +1,19 @@
1
+ interface Pagination {
2
+ page: number;
3
+ perPage: number;
4
+ total: number;
5
+ totalPages: number;
6
+ hasNextPage: boolean;
7
+ hasPrevPage: boolean;
8
+ nextPage: number | null;
9
+ prevPage: number | null;
10
+ }
11
+ interface CalculatePaginationInput {
12
+ page: number;
13
+ perPage: number;
14
+ total: number;
15
+ totalPages: number;
16
+ }
17
+ declare const calculatePagination: (input: CalculatePaginationInput) => Pagination;
18
+
19
+ export { type Pagination as P, calculatePagination as c };
@@ -0,0 +1,19 @@
1
+ interface Pagination {
2
+ page: number;
3
+ perPage: number;
4
+ total: number;
5
+ totalPages: number;
6
+ hasNextPage: boolean;
7
+ hasPrevPage: boolean;
8
+ nextPage: number | null;
9
+ prevPage: number | null;
10
+ }
11
+ interface CalculatePaginationInput {
12
+ page: number;
13
+ perPage: number;
14
+ total: number;
15
+ totalPages: number;
16
+ }
17
+ declare const calculatePagination: (input: CalculatePaginationInput) => Pagination;
18
+
19
+ export { type Pagination as P, calculatePagination as c };