@teamnovu/kit-shopware-api-client 0.0.2 → 0.0.4

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/dist/client.d.ts CHANGED
@@ -1,20 +1,20 @@
1
+ import { EventEmitter } from './eventEmitter';
1
2
  import { OperationOptions, OperationProp, ShopwareClientOptions } from './types';
2
- export declare class ShopwareApiError extends Error {
3
- readonly status: number;
4
- readonly response?: unknown | undefined;
5
- constructor(message: string, status: number, response?: unknown | undefined);
3
+ export interface ResponseType<TKey> {
4
+ __response: TKey;
6
5
  }
7
- export declare class ShopwareClient<Operations extends Record<string, {
8
- body?: unknown;
9
- response?: unknown;
10
- }>> {
6
+ export type BrandedResponse<Operations, OperationKey extends (keyof Operations) & string> = ResponseType<OperationKey> & OperationProp<Operations, OperationKey, 'response'>;
7
+ export declare class ShopwareClient<Operations> extends EventEmitter {
11
8
  private options;
12
9
  constructor(options: ShopwareClientOptions);
13
10
  setBaseURL(baseURL: string): void;
14
11
  setApiKey(apiKey: string): void;
15
12
  setLanguage(language: string | undefined): void;
13
+ setContextToken(contextToken: string | undefined): void;
16
14
  setIncludeSeoUrls(includeSeoUrls?: boolean): void;
15
+ setReflectContextToken(reflectContextToken?: boolean): void;
17
16
  private parseOperation;
18
17
  private interpolateUrl;
19
- query<OperationKey extends (keyof Operations) & string>(operation: OperationKey, options?: OperationOptions<Operations, OperationKey>): Promise<OperationProp<Operations, OperationKey, 'response'>>;
18
+ queryRaw<OperationKey extends (keyof Operations) & string>(operation: OperationKey, options?: OperationOptions<Operations, OperationKey>): Promise<Response>;
19
+ query<OperationKey extends (keyof Operations) & string>(operation: OperationKey, options?: OperationOptions<Operations, OperationKey>): Promise<BrandedResponse<Operations, OperationKey>>;
20
20
  }
@@ -0,0 +1,64 @@
1
+ import { z } from 'zod';
2
+ declare const shopwareErrorSchema: z.ZodObject<{
3
+ status: z.ZodString;
4
+ code: z.ZodString;
5
+ title: z.ZodOptional<z.ZodString>;
6
+ detail: z.ZodOptional<z.ZodString>;
7
+ meta: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
8
+ source: z.ZodOptional<z.ZodObject<{
9
+ pointer: z.ZodOptional<z.ZodString>;
10
+ }, "strip", z.ZodTypeAny, {
11
+ pointer?: string | undefined;
12
+ }, {
13
+ pointer?: string | undefined;
14
+ }>>;
15
+ trace: z.ZodOptional<z.ZodArray<z.ZodObject<{
16
+ file: z.ZodString;
17
+ line: z.ZodNumber;
18
+ function: z.ZodString;
19
+ }, "strip", z.ZodTypeAny, {
20
+ function: string;
21
+ file: string;
22
+ line: number;
23
+ }, {
24
+ function: string;
25
+ file: string;
26
+ line: number;
27
+ }>, "many">>;
28
+ }, "strip", z.ZodTypeAny, {
29
+ status: string;
30
+ code: string;
31
+ title?: string | undefined;
32
+ detail?: string | undefined;
33
+ meta?: Record<string, unknown> | undefined;
34
+ source?: {
35
+ pointer?: string | undefined;
36
+ } | undefined;
37
+ trace?: {
38
+ function: string;
39
+ file: string;
40
+ line: number;
41
+ }[] | undefined;
42
+ }, {
43
+ status: string;
44
+ code: string;
45
+ title?: string | undefined;
46
+ detail?: string | undefined;
47
+ meta?: Record<string, unknown> | undefined;
48
+ source?: {
49
+ pointer?: string | undefined;
50
+ } | undefined;
51
+ trace?: {
52
+ function: string;
53
+ file: string;
54
+ line: number;
55
+ }[] | undefined;
56
+ }>;
57
+ export type ShopwareError = z.infer<typeof shopwareErrorSchema>;
58
+ export declare class ShopwareApiError extends Error {
59
+ readonly status: number;
60
+ readonly response?: unknown | undefined;
61
+ errors: ShopwareError[];
62
+ constructor(message: string, status: number, response?: unknown | undefined);
63
+ }
64
+ export {};
@@ -0,0 +1,14 @@
1
+ export declare class EventEmitter implements EventTarget {
2
+ private listeners;
3
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
4
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
5
+ dispatchEvent(event: Event): boolean;
6
+ private normalizeOptions;
7
+ private optionsMatch;
8
+ on(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
9
+ off(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
10
+ once(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
11
+ emit(type: string, detail?: unknown): boolean;
12
+ getEventTypes(): string[];
13
+ removeAllListeners(type?: string): void;
14
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './client';
2
2
  export * from './types';
3
+ export { type ShopwareError, ShopwareApiError } from './error';
package/dist/index.mjs CHANGED
@@ -1,21 +1,144 @@
1
- var h = Object.defineProperty;
2
- var l = (s, e, t) => e in s ? h(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
3
- var n = (s, e, t) => l(s, typeof e != "symbol" ? e + "" : e, t);
4
- class o extends Error {
5
- constructor(e, t, r) {
6
- super(e), this.status = t, this.response = r, this.name = "ShopwareApiError";
1
+ var d = Object.defineProperty;
2
+ var g = (i, r, e) => r in i ? d(i, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[r] = e;
3
+ var u = (i, r, e) => g(i, typeof r != "symbol" ? r + "" : r, e);
4
+ import { z as o } from "zod";
5
+ const y = o.object({
6
+ status: o.string(),
7
+ code: o.string(),
8
+ title: o.string().optional(),
9
+ detail: o.string().optional(),
10
+ meta: o.record(o.unknown()).optional(),
11
+ source: o.object({
12
+ pointer: o.string().optional()
13
+ }).optional(),
14
+ trace: o.array(
15
+ o.object({
16
+ file: o.string(),
17
+ line: o.number(),
18
+ function: o.string()
19
+ })
20
+ ).optional()
21
+ }), w = o.object({
22
+ errors: o.array(y)
23
+ });
24
+ class p extends Error {
25
+ constructor(e, t, s) {
26
+ super(e);
27
+ u(this, "errors");
28
+ this.status = t, this.response = s, this.name = "ShopwareApiError";
29
+ const { success: n, data: a } = w.safeParse(s);
30
+ this.errors = n ? a.errors : [];
7
31
  }
8
32
  }
9
- const c = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i;
10
- class g {
33
+ class m {
34
+ constructor() {
35
+ u(this, "listeners", /* @__PURE__ */ new Map());
36
+ }
37
+ addEventListener(r, e, t) {
38
+ if (!e) return;
39
+ const s = this.normalizeOptions(t), n = {
40
+ listener: e,
41
+ options: s
42
+ };
43
+ if (s.signal) {
44
+ if (s.signal.aborted) return;
45
+ n.signal = s.signal, s.signal.addEventListener("abort", () => {
46
+ this.removeEventListener(r, e, t);
47
+ }, { once: !0 });
48
+ }
49
+ this.listeners.has(r) || this.listeners.set(r, []), this.listeners.get(r).push(n);
50
+ }
51
+ removeEventListener(r, e, t) {
52
+ if (!e) return;
53
+ const s = this.listeners.get(r);
54
+ if (!s) return;
55
+ const n = this.normalizeOptions(t), a = s.findIndex((h) => h.listener === e && this.optionsMatch(h.options, n));
56
+ a !== -1 && (s.splice(a, 1), s.length === 0 && this.listeners.delete(r));
57
+ }
58
+ dispatchEvent(r) {
59
+ var s;
60
+ const e = this.listeners.get(r.type);
61
+ if (!e || e.length === 0) return !0;
62
+ const t = [...e];
63
+ for (const n of t)
64
+ if (!((s = n.signal) != null && s.aborted)) {
65
+ try {
66
+ typeof n.listener == "function" ? n.listener.call(this, r) : n.listener.handleEvent(r);
67
+ } catch (a) {
68
+ console.error("Error in event listener:", a);
69
+ }
70
+ if (n.options.once && this.removeEventListener(r.type, n.listener, n.options), r.cancelBubble) break;
71
+ }
72
+ return !r.defaultPrevented;
73
+ }
74
+ normalizeOptions(r) {
75
+ return typeof r == "boolean" ? { capture: r } : {
76
+ capture: !1,
77
+ once: !1,
78
+ passive: !1,
79
+ ...r
80
+ };
81
+ }
82
+ optionsMatch(r, e) {
83
+ return r.capture === e.capture;
84
+ }
85
+ // Utility methods for easier usage
86
+ on(r, e, t) {
87
+ this.addEventListener(r, e, t);
88
+ }
89
+ off(r, e, t) {
90
+ this.removeEventListener(r, e, t);
91
+ }
92
+ once(r, e, t) {
93
+ const s = typeof t == "boolean" ? {
94
+ capture: t,
95
+ once: !0
96
+ } : {
97
+ ...t,
98
+ once: !0
99
+ };
100
+ this.addEventListener(r, e, s);
101
+ }
102
+ emit(r, e) {
103
+ const t = new CustomEvent(r, { detail: e });
104
+ return this.dispatchEvent(t);
105
+ }
106
+ getEventTypes() {
107
+ return Array.from(this.listeners.keys());
108
+ }
109
+ removeAllListeners(r) {
110
+ r ? this.listeners.delete(r) : this.listeners.clear();
111
+ }
112
+ }
113
+ const f = (i) => i == null || typeof i == "number" && isNaN(i) || typeof i == "function";
114
+ function b(i) {
115
+ const r = new URLSearchParams(), e = (t, s) => {
116
+ f(s) || (typeof s == "object" && r.append(t, JSON.stringify(s)), r.append(t, String(s)));
117
+ };
118
+ for (const [t, s] of Object.entries(i))
119
+ if (!f(s))
120
+ if (typeof s == "string")
121
+ r.append(t, String(s));
122
+ else if (Array.isArray(s))
123
+ for (const n of s)
124
+ e(`${t}[]`, n);
125
+ else
126
+ e(t, s);
127
+ return r;
128
+ }
129
+ const E = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i;
130
+ class v extends m {
11
131
  constructor(e) {
12
- n(this, "options", {
132
+ super();
133
+ u(this, "options", {
13
134
  baseURL: "",
14
135
  apiKey: "",
15
136
  language: "",
16
- includeSeoUrls: !1
137
+ contextToken: "",
138
+ includeSeoUrls: !1,
139
+ reflectContextToken: !0
17
140
  });
18
- this.setBaseURL(e.baseURL), this.setApiKey(e.apiKey), this.setLanguage(e.language), this.setIncludeSeoUrls(e.includeSeoUrls), this.options = e;
141
+ this.setBaseURL(e.baseURL ?? this.options.baseURL), this.setApiKey(e.apiKey ?? this.options.apiKey), this.setLanguage(e.language ?? this.options.language), this.setContextToken(e.contextToken ?? this.options.contextToken), this.setIncludeSeoUrls(e.includeSeoUrls ?? this.options.includeSeoUrls), this.setReflectContextToken(e.reflectContextToken ?? this.options.reflectContextToken);
19
142
  }
20
143
  setBaseURL(e) {
21
144
  if (typeof e != "string")
@@ -32,11 +155,19 @@ class g {
32
155
  throw new Error("Invalid language: If provided, it must be a string.");
33
156
  this.options.language = e;
34
157
  }
158
+ setContextToken(e) {
159
+ if (e && typeof e != "string")
160
+ throw new Error("Invalid contextToken: If provided, it must be a string.");
161
+ this.options.contextToken = e, this.emit("contextToken", e);
162
+ }
35
163
  setIncludeSeoUrls(e = !0) {
36
164
  this.options.includeSeoUrls = e;
37
165
  }
166
+ setReflectContextToken(e = !0) {
167
+ this.options.reflectContextToken = e;
168
+ }
38
169
  parseOperation(e) {
39
- const t = c.exec(e);
170
+ const t = E.exec(e);
40
171
  if (!(t != null && t.groups))
41
172
  throw new Error("Invalid operation format");
42
173
  return {
@@ -46,44 +177,54 @@ class g {
46
177
  };
47
178
  }
48
179
  interpolateUrl(e, t) {
49
- return e.replace(/{([^}]+?)}/g, (r, a) => {
50
- if (!(a in t))
51
- throw new Error(`Missing required URL parameter: ${a}`);
52
- return t[a];
180
+ return e.replace(/{([^}]+?)}/g, (s, n) => {
181
+ if (!(n in t))
182
+ throw new Error(`Missing required URL parameter: ${n}`);
183
+ return t[n];
53
184
  });
54
185
  }
55
- async query(e, t) {
186
+ async queryRaw(e, t) {
56
187
  try {
57
- const { method: r, url: a } = this.parseOperation(e), u = this.interpolateUrl(a, (t == null ? void 0 : t.params) ?? {}), i = await fetch(`${this.options.baseURL}/store-api${u}`, {
188
+ const { method: s, url: n } = this.parseOperation(e), a = this.interpolateUrl(n, (t == null ? void 0 : t.params) ?? {}), h = t != null && t.query ? `?${b(t.query)}` : "", c = await fetch(`${this.options.baseURL}/store-api${a}${h}`, {
58
189
  ...t,
59
- method: r,
190
+ method: s,
60
191
  headers: {
61
192
  "Content-Type": "application/json",
62
193
  "sw-access-key": this.options.apiKey,
194
+ ...this.options.contextToken && { "sw-context-token": this.options.contextToken },
63
195
  ...this.options.includeSeoUrls && { "sw-include-seo-urls": "true" },
64
196
  ...this.options.language && { "sw-language-id": this.options.language },
65
197
  ...t == null ? void 0 : t.headers
66
198
  },
67
199
  body: t != null && t.body ? JSON.stringify(t.body) : void 0
68
200
  });
69
- if (!i.ok)
70
- throw new o(
71
- `Shopware API request failed: ${i.statusText}`,
72
- i.status,
73
- await i.json().catch(() => {
201
+ if (!c.ok) {
202
+ const l = new p(
203
+ `Shopware API request failed: ${c.statusText}`,
204
+ c.status,
205
+ await c.json().catch(() => {
74
206
  })
75
207
  );
76
- return await i.json();
77
- } catch (r) {
78
- throw r instanceof o ? r : new o(
208
+ throw this.emit("error", l), l;
209
+ }
210
+ if (this.options.reflectContextToken) {
211
+ const l = c.headers.get("sw-context-token");
212
+ l && this.setContextToken(l);
213
+ }
214
+ return c;
215
+ } catch (s) {
216
+ throw s instanceof p ? s : new p(
79
217
  "Failed to communicate with Shopware API",
80
218
  500,
81
- r instanceof Error ? r.message : void 0
219
+ s instanceof Error ? s.message : void 0
82
220
  );
83
221
  }
84
222
  }
223
+ async query(e, t) {
224
+ return (await this.queryRaw(e, t)).json();
225
+ }
85
226
  }
86
227
  export {
87
- o as ShopwareApiError,
88
- g as ShopwareClient
228
+ p as ShopwareApiError,
229
+ v as ShopwareClient
89
230
  };
@@ -0,0 +1 @@
1
+ export declare function createQueryParams(params: Record<string, unknown>): URLSearchParams;
package/dist/types.d.ts CHANGED
@@ -16,11 +16,25 @@ export type OperationOptions<Operations, K extends OperationKey<Operations>> = O
16
16
  params?: void;
17
17
  } : {
18
18
  params: T;
19
- }) : never);
19
+ }) : never) & {
20
+ query?: Record<string, unknown>;
21
+ };
20
22
  export interface ShopwareClientOptions {
21
23
  baseURL: string;
22
24
  apiKey: string;
23
25
  includeSeoUrls?: boolean;
24
26
  language?: string;
27
+ /**
28
+ * If true, the context token will be reflected in the response headers.
29
+ * @default true
30
+ */
31
+ reflectContextToken?: boolean;
32
+ /**
33
+ * If provided, it will be used as the context token.
34
+ * If reflectContextToken is true, this token will be used only until the first response
35
+ * sends a new context token.
36
+ * @default undefined
37
+ */
38
+ contextToken?: string;
25
39
  }
26
40
  export {};
package/docs/index.md ADDED
@@ -0,0 +1,161 @@
1
+ # Shopware API Client
2
+
3
+ A TypeScript client for the Shopware Store API with full type safety and event-driven context management.
4
+
5
+ Install with `npm i @teamnovu/kit-shopware-api-client`
6
+
7
+ ## Features
8
+
9
+ - ✅ **Type-safe API calls** - Full TypeScript support with operation-based type inference
10
+ - ✅ **Automatic context token management** - Handles authentication tokens automatically
11
+ - ✅ **Event-driven architecture** - Subscribe to context token changes
12
+ - ✅ **URL parameter interpolation** - Dynamic URL path parameters with type safety
13
+ - ✅ **Query parameter support** - Type-safe query string generation
14
+ - ✅ **SEO URLs support** - Optional SEO-friendly URL responses
15
+ - ✅ **Error handling** - Custom error types with response details
16
+
17
+ ## Basic Usage
18
+
19
+ ```typescript
20
+ import { ShopwareClient } from '@teamnovu/kit-shopware-api-client'
21
+
22
+ // Initialize the client
23
+ const client = new ShopwareClient({
24
+ baseURL: 'https://your-shopware-store.com',
25
+ apiKey: 'your-api-key',
26
+ includeSeoUrls: true,
27
+ language: 'language-id' // optional
28
+ })
29
+
30
+ // Make API calls using operation strings
31
+ const products = await client.query('readProductListing post /product-listing', {
32
+ body: {
33
+ // request body
34
+ }
35
+ })
36
+
37
+ // With URL parameters
38
+ const product = await client.query('readProduct post /product/{productId}', {
39
+ params: {
40
+ productId: 'product-uuid'
41
+ }
42
+ })
43
+
44
+ // With query parameters
45
+ const categories = await client.query('readCategoryList post /category', {
46
+ query: {
47
+ limit: 10,
48
+ page: 1
49
+ }
50
+ })
51
+ ```
52
+
53
+ ## Client Configuration
54
+
55
+ ### ShopwareClientOptions
56
+
57
+ | Option | Type | Required | Default | Description |
58
+ |--------|------|----------|---------|-------------|
59
+ | `baseURL` | `string` | ✅ | - | The base URL of your Shopware store |
60
+ | `apiKey` | `string` | ✅ | - | Your Shopware Store API access key |
61
+ | `language` | `string` | ❌ | `undefined` | Language ID for localized responses |
62
+ | `contextToken` | `string` | ❌ | `undefined` | Initial context token for authenticated requests |
63
+ | `includeSeoUrls` | `boolean` | ❌ | `false` | Include SEO-friendly URLs in responses |
64
+ | `reflectContextToken` | `boolean` | ❌ | `true` | Automatically update context token from responses |
65
+
66
+ ## Operation Format
67
+
68
+ Operations follow the pattern: `{operationName} {httpMethod} {urlPath}`
69
+
70
+ Examples:
71
+ - `'readProductListing post /product-listing'`
72
+ - `'readProduct post /product/{productId}'`
73
+ - `'addLineItem patch /checkout/cart/line-item'`
74
+
75
+ ## Context Token Management
76
+
77
+ The client automatically manages context tokens for session handling:
78
+
79
+ ```typescript
80
+ // Listen for context token changes
81
+ client.on('contextToken', (token) => {
82
+ console.log('New context token:', token)
83
+ // Store token for future requests
84
+ })
85
+
86
+ // Manually set context token
87
+ client.setContextToken('your-context-token')
88
+ ```
89
+
90
+ ## Error Handling
91
+
92
+ The client throws `ShopwareApiError` for API failures:
93
+
94
+ ```typescript
95
+ import { ShopwareApiError } from '@teamnovu/kit-shopware-api-client'
96
+
97
+ try {
98
+ const result = await client.query('someOperation post /some-endpoint')
99
+ } catch (error) {
100
+ if (error instanceof ShopwareApiError) {
101
+ console.error('API Error:', error.message)
102
+ console.error('Status:', error.status)
103
+ console.error('Response:', error.response)
104
+ }
105
+ }
106
+ ```
107
+
108
+ ## Advanced Usage
109
+
110
+ ### Raw Response Access
111
+
112
+ Use `queryRaw()` to access the raw fetch Response:
113
+
114
+ ```typescript
115
+ const response = await client.queryRaw('readProduct post /product/{productId}', {
116
+ params: { productId: 'uuid' }
117
+ })
118
+
119
+ const data = await response.json()
120
+ const headers = response.headers
121
+ ```
122
+
123
+ ### Dynamic Configuration
124
+
125
+ Update client configuration at runtime:
126
+
127
+ ```typescript
128
+ client.setBaseURL('https://new-store.com')
129
+ client.setApiKey('new-api-key')
130
+ client.setLanguage('new-language-id')
131
+ client.setIncludeSeoUrls(true)
132
+ client.setReflectContextToken(false)
133
+ ```
134
+
135
+ ## Type Safety
136
+
137
+ The client provides full TypeScript support when used with generated operation types:
138
+
139
+ ```typescript
140
+ type MyOperations = {
141
+ 'readProduct post /product/{productId}': {
142
+ body?: { includes?: Record<string, any> }
143
+ response: ProductDetailResponse
144
+ }
145
+ 'readProductListing post /product-listing': {
146
+ body: ProductListingCriteria
147
+ response: ProductListingResponse
148
+ }
149
+ }
150
+
151
+ const client = new ShopwareClient<MyOperations>({
152
+ baseURL: 'https://store.com',
153
+ apiKey: 'key'
154
+ })
155
+
156
+ // Now fully type-safe!
157
+ const product = await client.query('readProduct post /product/{productId}', {
158
+ params: { productId: 'uuid' } // TypeScript enforces this
159
+ })
160
+ // product is typed as ProductDetailResponse
161
+ ```
package/docs/info.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "name": "🛒 Shopware API Client"
3
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnovu/kit-shopware-api-client",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "A client for the Shopware API",
5
5
  "main": "dist/index.mjs",
6
6
  "module": "dist/index.mjs",
@@ -21,7 +21,9 @@
21
21
  "keywords": [],
22
22
  "author": "Elias Bernhaut",
23
23
  "homepage": "https://kit.novu.ch/packages/shopware-api-client/",
24
- "dependencies": {},
24
+ "dependencies": {
25
+ "zod": "^3.25.67"
26
+ },
25
27
  "scripts": {
26
28
  "build": "vite build",
27
29
  "watch": "NODE_ENV=development vite build --watch",
package/src/client.ts CHANGED
@@ -1,39 +1,43 @@
1
+ import { ShopwareApiError } from './error'
2
+ import { EventEmitter } from './eventEmitter'
3
+ import { createQueryParams } from './query'
1
4
  import type {
2
5
  OperationOptions,
3
6
  OperationProp,
4
7
  ShopwareClientOptions,
5
8
  } from './types'
6
9
 
7
- export class ShopwareApiError extends Error {
8
- constructor(
9
- message: string,
10
- public readonly status: number,
11
- public readonly response?: unknown,
12
- ) {
13
- super(message)
14
- this.name = 'ShopwareApiError'
15
- }
10
+ const operationRegex = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i
11
+
12
+ // This **Must** stay an interface and the response **must** be branded.
13
+ // This is to ensure that the response type is not already resolved when the
14
+ // library is built so we can still use module augmentation to override operations.
15
+ export interface ResponseType<TKey> {
16
+ __response: TKey
16
17
  }
17
18
 
18
- const operationRegex = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i
19
+ export type BrandedResponse<Operations, OperationKey extends (keyof Operations) & string> =
20
+ ResponseType<OperationKey> & OperationProp<Operations, OperationKey, 'response'>
19
21
 
20
- export class ShopwareClient<Operations extends Record<string, {
21
- body?: unknown
22
- response?: unknown
23
- }>> {
22
+ export class ShopwareClient<Operations> extends EventEmitter {
24
23
  private options: ShopwareClientOptions = {
25
24
  baseURL: '',
26
25
  apiKey: '',
27
26
  language: '',
27
+ contextToken: '',
28
28
  includeSeoUrls: false,
29
+ reflectContextToken: true,
29
30
  }
30
31
 
31
32
  constructor(options: ShopwareClientOptions) {
32
- this.setBaseURL(options.baseURL)
33
- this.setApiKey(options.apiKey)
34
- this.setLanguage(options.language)
35
- this.setIncludeSeoUrls(options.includeSeoUrls)
36
- this.options = options
33
+ super()
34
+
35
+ this.setBaseURL(options.baseURL ?? this.options.baseURL)
36
+ this.setApiKey(options.apiKey ?? this.options.apiKey)
37
+ this.setLanguage(options.language ?? this.options.language)
38
+ this.setContextToken(options.contextToken ?? this.options.contextToken)
39
+ this.setIncludeSeoUrls(options.includeSeoUrls ?? this.options.includeSeoUrls)
40
+ this.setReflectContextToken(options.reflectContextToken ?? this.options.reflectContextToken)
37
41
  }
38
42
 
39
43
  public setBaseURL(baseURL: string) {
@@ -60,10 +64,23 @@ export class ShopwareClient<Operations extends Record<string, {
60
64
  this.options.language = language
61
65
  }
62
66
 
67
+ public setContextToken(contextToken: string | undefined) {
68
+ if (contextToken && typeof contextToken !== 'string') {
69
+ throw new Error('Invalid contextToken: If provided, it must be a string.')
70
+ }
71
+
72
+ this.options.contextToken = contextToken
73
+ this.emit('contextToken', contextToken)
74
+ }
75
+
63
76
  public setIncludeSeoUrls(includeSeoUrls: boolean = true) {
64
77
  this.options.includeSeoUrls = includeSeoUrls
65
78
  }
66
79
 
80
+ public setReflectContextToken(reflectContextToken: boolean = true) {
81
+ this.options.reflectContextToken = reflectContextToken
82
+ }
83
+
67
84
  private parseOperation(operation: keyof Operations & string): {
68
85
  name: string
69
86
  method: string
@@ -89,21 +106,24 @@ export class ShopwareClient<Operations extends Record<string, {
89
106
  })
90
107
  }
91
108
 
92
- async query<OperationKey extends (keyof Operations) & string>(
109
+ async queryRaw<OperationKey extends (keyof Operations) & string>(
93
110
  operation: OperationKey,
94
111
  options?: OperationOptions<Operations, OperationKey>,
95
- ): Promise<OperationProp<Operations, OperationKey, 'response'>> {
112
+ ): Promise<Response> {
96
113
  try {
97
114
  const { method, url } = this.parseOperation(operation)
98
115
 
99
116
  const interpolatedUrl = this.interpolateUrl(url, options?.params ?? {})
100
117
 
101
- const response = await fetch(`${this.options.baseURL}/store-api${interpolatedUrl}`, {
118
+ const query = options?.query ? `?${createQueryParams(options.query)}` : ''
119
+
120
+ const response = await fetch(`${this.options.baseURL}/store-api${interpolatedUrl}${query}`, {
102
121
  ...options,
103
122
  method,
104
123
  headers: {
105
124
  'Content-Type': 'application/json',
106
125
  'sw-access-key': this.options.apiKey,
126
+ ...(this.options.contextToken && { 'sw-context-token': this.options.contextToken }),
107
127
  ...(this.options.includeSeoUrls && { 'sw-include-seo-urls': 'true' }),
108
128
  ...(this.options.language && { 'sw-language-id': this.options.language }),
109
129
  ...options?.headers,
@@ -112,15 +132,25 @@ export class ShopwareClient<Operations extends Record<string, {
112
132
  })
113
133
 
114
134
  if (!response.ok) {
115
- throw new ShopwareApiError(
135
+ const error = new ShopwareApiError(
116
136
  `Shopware API request failed: ${response.statusText}`,
117
137
  response.status,
118
138
  await response.json().catch(() => undefined),
119
139
  )
140
+
141
+ this.emit('error', error)
142
+
143
+ throw error
120
144
  }
121
145
 
122
- const data = await response.json()
123
- return data
146
+ if (this.options.reflectContextToken) {
147
+ const contextToken = response.headers.get('sw-context-token')
148
+ if (contextToken) {
149
+ this.setContextToken(contextToken)
150
+ }
151
+ }
152
+
153
+ return response
124
154
  } catch (error) {
125
155
  if (error instanceof ShopwareApiError) {
126
156
  throw error
@@ -133,4 +163,13 @@ export class ShopwareClient<Operations extends Record<string, {
133
163
  )
134
164
  }
135
165
  }
166
+
167
+ async query<OperationKey extends (keyof Operations) & string>(
168
+ operation: OperationKey,
169
+ options?: OperationOptions<Operations, OperationKey>,
170
+ ): Promise<BrandedResponse<Operations, OperationKey>> {
171
+ const response = await this.queryRaw(operation, options)
172
+
173
+ return response.json()
174
+ }
136
175
  }
package/src/error.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod'
2
+
3
+ const shopwareErrorSchema = z.object({
4
+ status: z.string(),
5
+ code: z.string(),
6
+ title: z.string().optional(),
7
+ detail: z.string().optional(),
8
+ meta: z.record(z.unknown()).optional(),
9
+ source: z.object({
10
+ pointer: z.string().optional(),
11
+ }).optional(),
12
+ trace: z.array(
13
+ z.object({
14
+ file: z.string(),
15
+ line: z.number(),
16
+ function: z.string(),
17
+ }),
18
+ ).optional(),
19
+ })
20
+
21
+ const shopwareErrorResponseSchema = z.object({
22
+ errors: z.array(shopwareErrorSchema),
23
+ })
24
+
25
+ export type ShopwareError = z.infer<typeof shopwareErrorSchema>
26
+
27
+ export class ShopwareApiError extends Error {
28
+ errors: ShopwareError[]
29
+
30
+ constructor(
31
+ message: string,
32
+ public readonly status: number,
33
+ public readonly response?: unknown,
34
+ ) {
35
+ super(message)
36
+ this.name = 'ShopwareApiError'
37
+
38
+ const { success, data } = shopwareErrorResponseSchema.safeParse(response)
39
+
40
+ this.errors = success ? data.errors : []
41
+ }
42
+ }
@@ -0,0 +1,162 @@
1
+ interface EventListenerEntry {
2
+ listener: EventListenerOrEventListenerObject
3
+ options: AddEventListenerOptions
4
+ signal?: AbortSignal
5
+ }
6
+
7
+ export class EventEmitter implements EventTarget {
8
+ private listeners = new Map<string, EventListenerEntry[]>()
9
+
10
+ addEventListener(
11
+ type: string,
12
+ listener: EventListenerOrEventListenerObject | null,
13
+ options?: boolean | AddEventListenerOptions,
14
+ ): void {
15
+ if (!listener) return
16
+
17
+ const listenerOptions = this.normalizeOptions(options)
18
+ const entry: EventListenerEntry = {
19
+ listener,
20
+ options: listenerOptions,
21
+ }
22
+
23
+ if (listenerOptions.signal) {
24
+ if (listenerOptions.signal.aborted) return
25
+
26
+ entry.signal = listenerOptions.signal
27
+ listenerOptions.signal.addEventListener('abort', () => {
28
+ this.removeEventListener(type, listener, options)
29
+ }, { once: true })
30
+ }
31
+
32
+ if (!this.listeners.has(type)) {
33
+ this.listeners.set(type, [])
34
+ }
35
+
36
+ this.listeners.get(type)!.push(entry)
37
+ }
38
+
39
+ removeEventListener(
40
+ type: string,
41
+ listener: EventListenerOrEventListenerObject | null,
42
+ options?: boolean | EventListenerOptions,
43
+ ): void {
44
+ if (!listener) return
45
+
46
+ const entries = this.listeners.get(type)
47
+ if (!entries) return
48
+
49
+ const listenerOptions = this.normalizeOptions(options)
50
+ const index = entries.findIndex(entry =>
51
+ entry.listener === listener
52
+ && this.optionsMatch(entry.options, listenerOptions))
53
+
54
+ if (index !== -1) {
55
+ entries.splice(index, 1)
56
+ if (entries.length === 0) {
57
+ this.listeners.delete(type)
58
+ }
59
+ }
60
+ }
61
+
62
+ dispatchEvent(event: Event): boolean {
63
+ const entries = this.listeners.get(event.type)
64
+ if (!entries || entries.length === 0) return true
65
+
66
+ const entriesCopy = [...entries]
67
+
68
+ for (const entry of entriesCopy) {
69
+ if (entry.signal?.aborted) continue
70
+
71
+ try {
72
+ if (typeof entry.listener === 'function') {
73
+ entry.listener.call(this, event)
74
+ } else {
75
+ entry.listener.handleEvent(event)
76
+ }
77
+ } catch (error) {
78
+ // In a real implementation, you might want to handle errors differently
79
+ console.error('Error in event listener:', error)
80
+ }
81
+
82
+ // Remove if 'once' option was set
83
+ if (entry.options.once) {
84
+ this.removeEventListener(event.type, entry.listener, entry.options)
85
+ }
86
+
87
+ // Stop if event propagation was stopped
88
+ if (event.cancelBubble) break
89
+ }
90
+
91
+ return !event.defaultPrevented
92
+ }
93
+
94
+ private normalizeOptions(
95
+ options?: boolean | AddEventListenerOptions | EventListenerOptions,
96
+ ): AddEventListenerOptions {
97
+ if (typeof options === 'boolean') {
98
+ return { capture: options }
99
+ }
100
+ return {
101
+ capture: false,
102
+ once: false,
103
+ passive: false,
104
+ ...options,
105
+ }
106
+ }
107
+
108
+ private optionsMatch(a: AddEventListenerOptions, b: AddEventListenerOptions): boolean {
109
+ return a.capture === b.capture
110
+ }
111
+
112
+ // Utility methods for easier usage
113
+ on(
114
+ type: string,
115
+ listener: EventListenerOrEventListenerObject,
116
+ options?: boolean | AddEventListenerOptions,
117
+ ): void {
118
+ this.addEventListener(type, listener, options)
119
+ }
120
+
121
+ off(
122
+ type: string,
123
+ listener: EventListenerOrEventListenerObject,
124
+ options?: boolean | EventListenerOptions,
125
+ ): void {
126
+ this.removeEventListener(type, listener, options)
127
+ }
128
+
129
+ once(
130
+ type: string,
131
+ listener: EventListenerOrEventListenerObject,
132
+ options?: boolean | AddEventListenerOptions,
133
+ ): void {
134
+ const onceOptions = typeof options === 'boolean'
135
+ ? {
136
+ capture: options,
137
+ once: true,
138
+ }
139
+ : {
140
+ ...options,
141
+ once: true,
142
+ }
143
+ this.addEventListener(type, listener, onceOptions)
144
+ }
145
+
146
+ emit(type: string, detail?: unknown): boolean {
147
+ const event = new CustomEvent(type, { detail })
148
+ return this.dispatchEvent(event)
149
+ }
150
+
151
+ getEventTypes(): string[] {
152
+ return Array.from(this.listeners.keys())
153
+ }
154
+
155
+ removeAllListeners(type?: string): void {
156
+ if (type) {
157
+ this.listeners.delete(type)
158
+ } else {
159
+ this.listeners.clear()
160
+ }
161
+ }
162
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './client'
2
2
  export * from './types'
3
+ export { type ShopwareError, ShopwareApiError } from './error'
package/src/query.ts ADDED
@@ -0,0 +1,39 @@
1
+ const isIgnored = (value: unknown) =>
2
+ value === undefined
3
+ || value === null
4
+ || (typeof value === 'number' && isNaN(value as number))
5
+ || typeof value === 'function'
6
+
7
+ export function createQueryParams(params: Record<string, unknown>) {
8
+ const queryParams = new URLSearchParams()
9
+
10
+ const appendNested = (key: string, value: unknown) => {
11
+ if (isIgnored(value)) {
12
+ return
13
+ }
14
+
15
+ if (typeof value === 'object') {
16
+ queryParams.append(key, JSON.stringify(value))
17
+ }
18
+
19
+ queryParams.append(key, String(value))
20
+ }
21
+
22
+ for (const [key, value] of Object.entries(params)) {
23
+ if (isIgnored(value)) {
24
+ continue
25
+ }
26
+
27
+ if (typeof value === 'string') {
28
+ queryParams.append(key, String(value))
29
+ } else if (Array.isArray(value)) {
30
+ for (const item of value) {
31
+ appendNested(`${key}[]`, item)
32
+ }
33
+ } else {
34
+ appendNested(key, value)
35
+ }
36
+ }
37
+
38
+ return queryParams
39
+ }
package/src/types.ts CHANGED
@@ -15,7 +15,9 @@ export type OperationProp<
15
15
  Operations,
16
16
  OperationKey extends keyof Operations,
17
17
  Prop extends string,
18
- > = Operation<Operations, OperationKey> extends { [K in Prop]?: unknown } ? Operation<Operations, OperationKey>[Prop] : never
18
+ > = Operation<Operations, OperationKey> extends { [K in Prop]?: unknown }
19
+ ? Operation<Operations, OperationKey>[Prop]
20
+ : never
19
21
 
20
22
  export type InferParameters<T extends string> = UrlParamsRecord<ExtractUrlFromOperation<T>>
21
23
 
@@ -31,10 +33,27 @@ export type OperationOptions<
31
33
  (UrlParamsRecord<ExtractUrlFromOperation<K>> extends infer T
32
34
  ? (keyof T extends never ? { params?: void } : { params: T })
33
35
  : never)
36
+ & {
37
+ query?: Record<string, unknown>
38
+ }
34
39
 
35
40
  export interface ShopwareClientOptions {
36
41
  baseURL: string
37
42
  apiKey: string
38
43
  includeSeoUrls?: boolean
39
44
  language?: string
45
+
46
+ /**
47
+ * If true, the context token will be reflected in the response headers.
48
+ * @default true
49
+ */
50
+ reflectContextToken?: boolean
51
+
52
+ /**
53
+ * If provided, it will be used as the context token.
54
+ * If reflectContextToken is true, this token will be used only until the first response
55
+ * sends a new context token.
56
+ * @default undefined
57
+ */
58
+ contextToken?: string
40
59
  }
package/eslint.config.mjs DELETED
@@ -1,84 +0,0 @@
1
- import js from '@eslint/js'
2
- import pluginStylistic from '@stylistic/eslint-plugin'
3
- import tseslint from 'typescript-eslint'
4
-
5
- export default tseslint.config(
6
- js.configs.recommended,
7
- tseslint.configs.recommended,
8
- pluginStylistic.configs['recommended'],
9
- {
10
- rules: {
11
- // stylistic
12
- // ********************
13
- '@stylistic/newline-per-chained-call': [
14
- 'error',
15
- { ignoreChainWithDepth: 2 },
16
- ],
17
- '@stylistic/nonblock-statement-body-position': 'error',
18
- '@stylistic/one-var-declaration-per-line': 'error',
19
- '@stylistic/operator-linebreak': [
20
- 'error',
21
- 'before',
22
- { overrides: { '=': 'none' } },
23
- ],
24
- '@stylistic/function-paren-newline': ['error', 'multiline-arguments'],
25
- '@stylistic/dot-location': ['error', 'property'],
26
- '@stylistic/no-mixed-operators': ['error', { allowSamePrecedence: true }],
27
- '@stylistic/brace-style': ['error', '1tbs', { allowSingleLine: true }],
28
- '@stylistic/array-bracket-newline': ['error', { multiline: true }],
29
- '@stylistic/array-element-newline': [
30
- 'error',
31
- {
32
- multiline: true,
33
- consistent: true,
34
- },
35
- ],
36
- '@stylistic/max-len': [
37
- 'warn',
38
- {
39
- code: 150,
40
- tabWidth: 2,
41
- },
42
- ],
43
- '@stylistic/object-curly-newline': [
44
- 'error',
45
- {
46
- multiline: true,
47
- consistent: true,
48
- },
49
- ],
50
- '@stylistic/object-property-newline': [
51
- 'error',
52
- { allowAllPropertiesOnSameLine: false },
53
- ],
54
-
55
- // common
56
- // ********************
57
- 'no-console': ['error', { allow: ['warn', 'error'] }],
58
- 'prefer-destructuring': [
59
- 'error',
60
- {
61
- array: false,
62
- object: true,
63
- },
64
- ],
65
- 'no-unused-vars': 'off',
66
- 'eqeqeq': ['error', 'smart'],
67
- 'no-undef': 'off', // done by typescript
68
- '@typescript-eslint/consistent-type-imports': 'error',
69
- '@typescript-eslint/no-explicit-any': 'warn',
70
- '@typescript-eslint/no-unused-vars': [
71
- 'error',
72
- {
73
- args: 'all',
74
- argsIgnorePattern: '^_',
75
- caughtErrors: 'all',
76
- caughtErrorsIgnorePattern: '^_',
77
- destructuredArrayIgnorePattern: '^_',
78
- varsIgnorePattern: '^_',
79
- ignoreRestSiblings: true,
80
- },
81
- ],
82
- },
83
- },
84
- )