@nxisai/nxis 2.1.1

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.
@@ -0,0 +1,423 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ /**
6
+ * A non-fatal warning indicating no structured data was found for a page.
7
+ *
8
+ * @remarks
9
+ * Thrown when the proxy returns a 200 response with an empty `data` object.
10
+ * Callers can catch this specifically to distinguish "no data" from actual errors.
11
+ */
12
+ class NxisWarning extends Error {
13
+ constructor(msg) {
14
+ super(msg);
15
+ // Set the prototype explicitly.
16
+ Object.setPrototypeOf(this, NxisWarning.prototype);
17
+ }
18
+ }
19
+ /**
20
+ * gRPC-compatible error codes used by the Nxis AI Proxy.
21
+ *
22
+ * @remarks
23
+ * These codes map directly to gRPC status codes and are included in
24
+ * structured error responses from the proxy. Use {@link errorCodeToHttp}
25
+ * to convert to the corresponding HTTP status code.
26
+ */
27
+ exports.ErrorCode = void 0;
28
+ (function (ErrorCode) {
29
+ /** The request completed successfully. */
30
+ ErrorCode[ErrorCode["OK"] = 0] = "OK";
31
+ /** The request contained an invalid argument (e.g. malformed URI). */
32
+ ErrorCode[ErrorCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
33
+ /** The requested resource was not found. */
34
+ ErrorCode[ErrorCode["NOT_FOUND"] = 5] = "NOT_FOUND";
35
+ /** The caller does not have permission to access the requested resource. */
36
+ ErrorCode[ErrorCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
37
+ /** The caller has exceeded their rate limit or quota. */
38
+ ErrorCode[ErrorCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
39
+ /** An internal server error occurred. */
40
+ ErrorCode[ErrorCode["INTERNAL"] = 13] = "INTERNAL";
41
+ /** The request lacks valid authentication credentials. */
42
+ ErrorCode[ErrorCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
43
+ })(exports.ErrorCode || (exports.ErrorCode = {}));
44
+ /**
45
+ * Maps each {@link ErrorCode} to its conventional HTTP status code.
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const httpStatus = errorCodeToHttp[ErrorCode.NOT_FOUND]; // 404
50
+ * ```
51
+ */
52
+ const errorCodeToHttp = {
53
+ [exports.ErrorCode.OK]: 200,
54
+ [exports.ErrorCode.INVALID_ARGUMENT]: 400,
55
+ [exports.ErrorCode.NOT_FOUND]: 404,
56
+ [exports.ErrorCode.PERMISSION_DENIED]: 403,
57
+ [exports.ErrorCode.RESOURCE_EXHAUSTED]: 429,
58
+ [exports.ErrorCode.INTERNAL]: 500,
59
+ [exports.ErrorCode.UNAUTHENTICATED]: 401,
60
+ };
61
+ /**
62
+ * An error thrown when the Nxis AI Proxy returns a non-200 response.
63
+ *
64
+ * @remarks
65
+ * `ProxyError` carries both the gRPC {@link ErrorCode} and the HTTP status
66
+ * code so callers can decide how to surface or retry the failure.
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * try {
71
+ * const data = await getStructuredData({ token, uri });
72
+ * } catch (err) {
73
+ * if (err instanceof ProxyError && err.isRetryable) {
74
+ * // back off and retry
75
+ * }
76
+ * }
77
+ * ```
78
+ */
79
+ class ProxyError extends Error {
80
+ /**
81
+ * @param code - The gRPC-style {@link ErrorCode}.
82
+ * @param httpStatus - The HTTP status code from the proxy response.
83
+ * @param message - A human-readable description of the error.
84
+ */
85
+ constructor(code, httpStatus, message) {
86
+ super(message);
87
+ this.code = code;
88
+ this.httpStatus = httpStatus;
89
+ this.name = "ProxyError";
90
+ Object.setPrototypeOf(this, ProxyError.prototype);
91
+ }
92
+ /**
93
+ * Whether this error represents a transient failure that may succeed on retry.
94
+ *
95
+ * @remarks
96
+ * Returns `true` for {@link ErrorCode.RESOURCE_EXHAUSTED} (rate limiting)
97
+ * and {@link ErrorCode.INTERNAL} (server errors).
98
+ */
99
+ get isRetryable() {
100
+ return this.code === exports.ErrorCode.RESOURCE_EXHAUSTED || this.code === exports.ErrorCode.INTERNAL;
101
+ }
102
+ /**
103
+ * Whether this error indicates an authentication or authorization failure.
104
+ *
105
+ * @remarks
106
+ * Returns `true` for {@link ErrorCode.UNAUTHENTICATED} (missing/invalid token)
107
+ * and {@link ErrorCode.PERMISSION_DENIED} (valid token, insufficient access).
108
+ */
109
+ get isAuthError() {
110
+ return this.code === exports.ErrorCode.UNAUTHENTICATED || this.code === exports.ErrorCode.PERMISSION_DENIED;
111
+ }
112
+ /**
113
+ * Creates a `ProxyError` from an HTTP status code and a parsed
114
+ * {@link NxisErrorResponse} body.
115
+ *
116
+ * @param status - The HTTP status code of the response.
117
+ * @param body - The parsed error response body from the proxy.
118
+ * @returns A new `ProxyError` instance.
119
+ */
120
+ static fromResponse(status, body) {
121
+ return new ProxyError(body.code, status, body.message);
122
+ }
123
+ }
124
+
125
+ /** Default token endpoint URL. */
126
+ const DEFAULT_TOKEN_URL = 'https://authorization.nxis.ai/v1/oauth/token';
127
+ /** Refresh the token when it has this many seconds or fewer remaining. */
128
+ const REFRESH_BUFFER_SECONDS = 60;
129
+ /**
130
+ * Manages OAuth 2.0 access tokens using the client credentials grant.
131
+ *
132
+ * @remarks
133
+ * Tokens are cached in memory and automatically refreshed before expiration.
134
+ * Concurrent calls during a refresh all await the same in-flight request,
135
+ * preventing redundant token fetches.
136
+ *
137
+ * @example
138
+ * ```typescript
139
+ * const manager = new OAuthTokenManager({
140
+ * clientId: process.env.NXIS_CLIENT_ID!,
141
+ * clientSecret: process.env.NXIS_CLIENT_SECRET!,
142
+ * });
143
+ *
144
+ * const token = await manager.getAccessToken();
145
+ * // Use token in Authorization: Bearer <token> header
146
+ * ```
147
+ */
148
+ class OAuthTokenManager {
149
+ constructor(config) {
150
+ var _a, _b, _c;
151
+ /** The currently cached access token, or `null` if none. */
152
+ this.cachedToken = null;
153
+ /** Unix timestamp (ms) at which the cached token expires. */
154
+ this.expiresAt = 0;
155
+ /** In-flight token request for concurrency deduplication. */
156
+ this.pendingRequest = null;
157
+ this.clientId = config.clientId;
158
+ this.clientSecret = config.clientSecret;
159
+ this.tokenUrl = (_b = (_a = config.tokenUrl) !== null && _a !== void 0 ? _a : process.env.NXIS_TOKEN_URL) !== null && _b !== void 0 ? _b : DEFAULT_TOKEN_URL;
160
+ this.scope = (_c = config.scope) !== null && _c !== void 0 ? _c : 'jsonld:read';
161
+ }
162
+ /**
163
+ * Returns a valid access token, fetching or refreshing as needed.
164
+ *
165
+ * @remarks
166
+ * If the cached token has more than {@link REFRESH_BUFFER_SECONDS} seconds
167
+ * remaining, it is returned immediately. Otherwise a new token is requested
168
+ * from the OAuth endpoint.
169
+ *
170
+ * @returns A valid OAuth Bearer access token.
171
+ *
172
+ * @throws {@link ProxyError}
173
+ * Thrown if the token endpoint returns an error response.
174
+ */
175
+ async getAccessToken() {
176
+ if (this.cachedToken && Date.now() < this.expiresAt) {
177
+ return this.cachedToken;
178
+ }
179
+ // Deduplicate concurrent refresh requests
180
+ if (this.pendingRequest) {
181
+ return this.pendingRequest;
182
+ }
183
+ this.pendingRequest = this.fetchToken();
184
+ try {
185
+ const token = await this.pendingRequest;
186
+ return token;
187
+ }
188
+ finally {
189
+ this.pendingRequest = null;
190
+ }
191
+ }
192
+ /**
193
+ * Fetches a new access token from the OAuth endpoint.
194
+ *
195
+ * @internal
196
+ */
197
+ async fetchToken() {
198
+ var _a, _b, _c;
199
+ const body = new URLSearchParams({
200
+ grant_type: 'client_credentials',
201
+ client_id: this.clientId,
202
+ client_secret: this.clientSecret,
203
+ scope: this.scope,
204
+ });
205
+ const response = await fetch(this.tokenUrl, {
206
+ method: 'POST',
207
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
208
+ body: body.toString(),
209
+ });
210
+ if (!response.ok) {
211
+ const statusToCode = {
212
+ 400: exports.ErrorCode.INVALID_ARGUMENT,
213
+ 401: exports.ErrorCode.UNAUTHENTICATED,
214
+ 403: exports.ErrorCode.PERMISSION_DENIED,
215
+ 429: exports.ErrorCode.RESOURCE_EXHAUSTED,
216
+ };
217
+ const code = (_a = statusToCode[response.status]) !== null && _a !== void 0 ? _a : exports.ErrorCode.INTERNAL;
218
+ let message;
219
+ try {
220
+ const errorBody = await response.json();
221
+ message = (_c = (_b = errorBody.message) !== null && _b !== void 0 ? _b : errorBody.error_description) !== null && _c !== void 0 ? _c : `Token request failed with status ${response.status}`;
222
+ }
223
+ catch (_d) {
224
+ message = `Token request failed with status ${response.status}`;
225
+ }
226
+ throw new ProxyError(code, response.status, message);
227
+ }
228
+ const data = await response.json();
229
+ this.cachedToken = data.access_token;
230
+ // Subtract buffer so we refresh before actual expiry
231
+ this.expiresAt = Date.now() + (data.expires_in - REFRESH_BUFFER_SECONDS) * 1000;
232
+ return this.cachedToken;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Attempts to parse the response body as a {@link NxisErrorResponse}.
238
+ *
239
+ * @param response - The `fetch` Response object to parse.
240
+ * @returns The parsed error body, or `null` if the body is not valid JSON.
241
+ *
242
+ * @internal
243
+ */
244
+ async function parseErrorBody(response) {
245
+ try {
246
+ return await response.json();
247
+ }
248
+ catch (_a) {
249
+ return null;
250
+ }
251
+ }
252
+ /**
253
+ * Processes an HTTP response from the Nxis API and returns the structured
254
+ * data payload, or throws an appropriate error.
255
+ *
256
+ * @remarks
257
+ * - On a `200` response with data, returns the {@link StructuredDataResponse}.
258
+ * - On a `200` response with an empty `data` object, throws {@link NxisWarning}.
259
+ * - On error responses, attempts to parse a structured {@link NxisErrorResponse}
260
+ * and throws a {@link ProxyError}. Falls back to generic status-based errors
261
+ * if the body cannot be parsed.
262
+ *
263
+ * @param response - The raw `fetch` Response from the proxy.
264
+ * @param pageUrl - The page URL for use in error messages. Defaults to `"unknown"`.
265
+ * @returns The parsed structured data response.
266
+ *
267
+ * @throws {@link NxisWarning}
268
+ * Thrown when the proxy returns 200 but the data object is empty.
269
+ *
270
+ * @throws {@link ProxyError}
271
+ * Thrown when the proxy returns a non-200 status code.
272
+ */
273
+ async function responseHandler(response, pageUrl) {
274
+ const url = pageUrl !== null && pageUrl !== void 0 ? pageUrl : 'unknown';
275
+ if (response.status === 200) {
276
+ const json = await response.json();
277
+ if ((json === null || json === void 0 ? void 0 : json.data) && Object.keys(json.data).length > 0)
278
+ return json;
279
+ throw new NxisWarning(JSON.stringify({ message: `No Nxis resource found for ${url}` }));
280
+ }
281
+ // Attempt to parse a structured error response from the proxy
282
+ const errorBody = await parseErrorBody(response);
283
+ if ((errorBody === null || errorBody === void 0 ? void 0 : errorBody.code) !== undefined && (errorBody === null || errorBody === void 0 ? void 0 : errorBody.message)) {
284
+ throw ProxyError.fromResponse(response.status, errorBody);
285
+ }
286
+ // Fallback for non-structured error responses
287
+ switch (response.status) {
288
+ case 500: throw new ProxyError(13, 500, "An internal server error occurred, please contact technical support.");
289
+ case 502: throw new ProxyError(13, 502, "An internal server error occurred, please contact technical support.");
290
+ case 503: throw new ProxyError(8, 503, "Service is temporarily unavailable, please try again later.");
291
+ default: throw new ProxyError(13, response.status, `Unexpected response status: ${response.status}`);
292
+ }
293
+ }
294
+ /**
295
+ * Fetches structured data from the Nxis AI Proxy's SSR endpoint (`/v1/nxis:ssr`).
296
+ *
297
+ * @remarks
298
+ * This is the low-level fetch function used by {@link NxisClient}. It sends
299
+ * the request with a `Bearer` access token obtained from the OAuth token manager.
300
+ *
301
+ * @param uri - The full URI of the page being rendered.
302
+ * @param accessToken - A valid OAuth Bearer access token.
303
+ * @param apiHost - The Nxis API host URL.
304
+ * @param userAgent - Optional User-Agent string for bot detection.
305
+ * @returns The full {@link StructuredDataResponse} from the proxy.
306
+ *
307
+ * @throws {@link ProxyError}
308
+ * Thrown if the proxy returns a non-200 response.
309
+ *
310
+ * @throws {@link NxisWarning}
311
+ * Thrown if the proxy returns 200 but no data is available for the page.
312
+ *
313
+ * @internal
314
+ */
315
+ async function fetchStructuredData(uri, accessToken, apiHost, userAgent, siteId) {
316
+ const endpoint = new URL(`${apiHost}/v1/nxis:ssr`);
317
+ endpoint.searchParams.append("uri", uri);
318
+ if (siteId)
319
+ endpoint.searchParams.append("site_id", siteId);
320
+ const hdrs = {
321
+ "Content-Type": "application/json",
322
+ "Authorization": `Bearer ${accessToken}`,
323
+ };
324
+ if (userAgent)
325
+ hdrs["User-Agent"] = userAgent;
326
+ const response = await fetch(endpoint.toString(), { headers: hdrs });
327
+ return responseHandler(response, uri);
328
+ }
329
+
330
+ /**
331
+ * A client for fetching JSON-LD structured data from the Nxis AI platform.
332
+ *
333
+ * @remarks
334
+ * `NxisClient` encapsulates OAuth authentication and token lifecycle
335
+ * management. Initialize once with your client credentials, then call
336
+ * {@link NxisClient.getStructuredData} for each page render.
337
+ *
338
+ * Tokens are cached in memory and refreshed automatically before
339
+ * expiration — no manual token handling is needed.
340
+ *
341
+ * @example
342
+ * ```tsx
343
+ * // Next.js App Router
344
+ * import { NxisClient } from '@nxisai/nxis/ssr';
345
+ * import { headers } from 'next/headers';
346
+ *
347
+ * const nxis = new NxisClient({
348
+ * clientId: process.env.NXIS_CLIENT_ID!,
349
+ * clientSecret: process.env.NXIS_CLIENT_SECRET!,
350
+ * });
351
+ *
352
+ * export default async function Page() {
353
+ * const headersList = await headers();
354
+ * const host = headersList.get('host') ?? 'localhost:3000';
355
+ * const proto = headersList.get('x-forwarded-proto') ?? 'http';
356
+ *
357
+ * const jsonLd = await nxis.getStructuredData({
358
+ * uri: `${proto}://${host}/`,
359
+ * userAgent: headersList.get('user-agent') ?? undefined,
360
+ * });
361
+ *
362
+ * return (
363
+ * <script
364
+ * type="application/ld+json"
365
+ * dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
366
+ * />
367
+ * );
368
+ * }
369
+ * ```
370
+ */
371
+ class NxisClient {
372
+ /**
373
+ * Creates a new Nxis client.
374
+ *
375
+ * @param config - Client configuration including OAuth credentials and
376
+ * optional host/token URL overrides.
377
+ *
378
+ * @throws {@link Error}
379
+ * Thrown if `NXIS_API_HOST` is not set and no `apiHost` override is provided.
380
+ */
381
+ constructor(config) {
382
+ var _a, _b;
383
+ this.apiHost = (_b = (_a = config.apiHost) !== null && _a !== void 0 ? _a : process.env.NXIS_API_HOST) !== null && _b !== void 0 ? _b : '';
384
+ if (!this.apiHost) {
385
+ throw new Error('NXIS_API_HOST is not set. Pass apiHost in the config or set the NXIS_API_HOST environment variable.');
386
+ }
387
+ this.tokenManager = new OAuthTokenManager({
388
+ clientId: config.clientId,
389
+ clientSecret: config.clientSecret,
390
+ tokenUrl: config.tokenUrl,
391
+ scope: config.scope,
392
+ });
393
+ }
394
+ /**
395
+ * Fetches JSON-LD structured data for a given page URL.
396
+ *
397
+ * @remarks
398
+ * Returns a JSON-LD object ready to be serialized into a
399
+ * `<script type="application/ld+json">` tag in your server-rendered HTML.
400
+ *
401
+ * The client automatically obtains a valid OAuth access token before
402
+ * making the request. Tokens are cached and refreshed transparently.
403
+ *
404
+ * @param req - Request-specific parameters (page URI and optional User-Agent).
405
+ * @returns A JSON-LD object to embed in the page.
406
+ *
407
+ * @throws {@link ProxyError}
408
+ * Thrown when the proxy returns a non-200 response (auth failures, rate
409
+ * limits, server errors, etc.).
410
+ *
411
+ * @throws {@link NxisWarning}
412
+ * Thrown when the proxy returns 200 but no structured data exists for the page.
413
+ */
414
+ async getStructuredData(req) {
415
+ const accessToken = await this.tokenManager.getAccessToken();
416
+ const response = await fetchStructuredData(req.uri, accessToken, this.apiHost, req.userAgent, req.siteId);
417
+ return response.data;
418
+ }
419
+ }
420
+
421
+ exports.NxisClient = NxisClient;
422
+ exports.ProxyError = ProxyError;
423
+ exports.errorCodeToHttp = errorCodeToHttp;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * Nxis.js — a lightweight client for the Nxis AI structured data platform.
5
+ *
6
+ * @remarks
7
+ * This package provides two integration paths:
8
+ *
9
+ * - **Client-side (browser):** Load `nxis.js` via a `<script>` tag from the
10
+ * Nxis CDN. The script auto-injects JSON-LD into the page.
11
+ *
12
+ * - **Server-side (SSR):** Import {@link NxisClient} from
13
+ * `@nxisai/nxis/ssr` and initialize it with your OAuth client
14
+ * credentials. The client manages access tokens automatically and
15
+ * fetches JSON-LD at render time to embed in the initial HTML response.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { NxisClient } from '@nxisai/nxis/ssr';
20
+ *
21
+ * const nxis = new NxisClient({
22
+ * clientId: process.env.NXIS_CLIENT_ID!,
23
+ * clientSecret: process.env.NXIS_CLIENT_SECRET!,
24
+ * });
25
+ *
26
+ * const jsonLd = await nxis.getStructuredData({
27
+ * uri: 'https://example.com/page',
28
+ * });
29
+ * ```
30
+ */
31
+ export { NxisClient } from './server';
32
+ export { ProxyError, ErrorCode, errorCodeToHttp } from './api';
33
+ export type { NxisClientConfig, NxisSSRRequest, StructuredDataResponse, NxisErrorResponse } from './api';