@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.
- package/.github/workflows/deploy.yml +110 -0
- package/README.md +401 -0
- package/bin/deploy.sh +2 -0
- package/build/api.d.ts +244 -0
- package/build/auth.d.ts +91 -0
- package/build/core.d.ts +56 -0
- package/build/index.cjs.js +423 -0
- package/build/index.d.ts +33 -0
- package/build/index.esm.js +417 -0
- package/build/nxis.js +1 -0
- package/build/server.d.ts +77 -0
- package/docs/ssr.md +606 -0
- package/nxisbucket.json +16 -0
- package/package.json +53 -0
- package/rollup.config.js +50 -0
- package/src/api.ts +281 -0
- package/src/auth.ts +171 -0
- package/src/client.ts +104 -0
- package/src/core.ts +124 -0
- package/src/index.ts +33 -0
- package/src/server.ts +106 -0
- package/tsconfig.json +66 -0
package/src/core.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { StructuredDataRequest, NxisWarning, StructuredDataResponse, NxisErrorResponse, ProxyError } from './api';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Serializes a {@link StructuredDataRequest} into URL query parameters for
|
|
5
|
+
* the client-side `/v1/nxis:inject` endpoint.
|
|
6
|
+
*
|
|
7
|
+
* @param request - The structured data request containing org, site, URI,
|
|
8
|
+
* referrer, and session info.
|
|
9
|
+
* @returns A `URLSearchParams` instance ready to be appended to the request URL.
|
|
10
|
+
*
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
export function buildParams(request: StructuredDataRequest): URLSearchParams {
|
|
14
|
+
const output = new URLSearchParams();
|
|
15
|
+
if (request.organization_id?.value) output.append("organization_id", request.organization_id.value);
|
|
16
|
+
if (request.site_id?.value) output.append("site_id", request.site_id.value);
|
|
17
|
+
output.append("uri", request.uri.href);
|
|
18
|
+
if (request.referrer) output.append("referrer", request.referrer);
|
|
19
|
+
if (request.session) output.append("session", request.session);
|
|
20
|
+
return output;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Attempts to parse the response body as a {@link NxisErrorResponse}.
|
|
25
|
+
*
|
|
26
|
+
* @param response - The `fetch` Response object to parse.
|
|
27
|
+
* @returns The parsed error body, or `null` if the body is not valid JSON.
|
|
28
|
+
*
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
async function parseErrorBody(response: Response): Promise<NxisErrorResponse | null> {
|
|
32
|
+
try {
|
|
33
|
+
return await response.json() as NxisErrorResponse;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Processes an HTTP response from the Nxis API and returns the structured
|
|
41
|
+
* data payload, or throws an appropriate error.
|
|
42
|
+
*
|
|
43
|
+
* @remarks
|
|
44
|
+
* - On a `200` response with data, returns the {@link StructuredDataResponse}.
|
|
45
|
+
* - On a `200` response with an empty `data` object, throws {@link NxisWarning}.
|
|
46
|
+
* - On error responses, attempts to parse a structured {@link NxisErrorResponse}
|
|
47
|
+
* and throws a {@link ProxyError}. Falls back to generic status-based errors
|
|
48
|
+
* if the body cannot be parsed.
|
|
49
|
+
*
|
|
50
|
+
* @param response - The raw `fetch` Response from the proxy.
|
|
51
|
+
* @param pageUrl - The page URL for use in error messages. Defaults to `"unknown"`.
|
|
52
|
+
* @returns The parsed structured data response.
|
|
53
|
+
*
|
|
54
|
+
* @throws {@link NxisWarning}
|
|
55
|
+
* Thrown when the proxy returns 200 but the data object is empty.
|
|
56
|
+
*
|
|
57
|
+
* @throws {@link ProxyError}
|
|
58
|
+
* Thrown when the proxy returns a non-200 status code.
|
|
59
|
+
*/
|
|
60
|
+
export async function responseHandler(response: Response, pageUrl?: string): Promise<StructuredDataResponse> {
|
|
61
|
+
const url = pageUrl ?? 'unknown';
|
|
62
|
+
|
|
63
|
+
if (response.status === 200) {
|
|
64
|
+
const json: StructuredDataResponse = await response.json();
|
|
65
|
+
if (json?.data && Object.keys(json.data).length > 0) return json;
|
|
66
|
+
throw new NxisWarning(JSON.stringify({ message: `No Nxis resource found for ${url}` }));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Attempt to parse a structured error response from the proxy
|
|
70
|
+
const errorBody = await parseErrorBody(response);
|
|
71
|
+
if (errorBody?.code !== undefined && errorBody?.message) {
|
|
72
|
+
throw ProxyError.fromResponse(response.status, errorBody);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Fallback for non-structured error responses
|
|
76
|
+
switch (response.status) {
|
|
77
|
+
case 500: throw new ProxyError(13, 500, "An internal server error occurred, please contact technical support.");
|
|
78
|
+
case 502: throw new ProxyError(13, 502, "An internal server error occurred, please contact technical support.");
|
|
79
|
+
case 503: throw new ProxyError(8, 503, "Service is temporarily unavailable, please try again later.");
|
|
80
|
+
default: throw new ProxyError(13, response.status, `Unexpected response status: ${response.status}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Fetches structured data from the Nxis AI Proxy's SSR endpoint (`/v1/nxis:ssr`).
|
|
86
|
+
*
|
|
87
|
+
* @remarks
|
|
88
|
+
* This is the low-level fetch function used by {@link NxisClient}. It sends
|
|
89
|
+
* the request with a `Bearer` access token obtained from the OAuth token manager.
|
|
90
|
+
*
|
|
91
|
+
* @param uri - The full URI of the page being rendered.
|
|
92
|
+
* @param accessToken - A valid OAuth Bearer access token.
|
|
93
|
+
* @param apiHost - The Nxis API host URL.
|
|
94
|
+
* @param userAgent - Optional User-Agent string for bot detection.
|
|
95
|
+
* @returns The full {@link StructuredDataResponse} from the proxy.
|
|
96
|
+
*
|
|
97
|
+
* @throws {@link ProxyError}
|
|
98
|
+
* Thrown if the proxy returns a non-200 response.
|
|
99
|
+
*
|
|
100
|
+
* @throws {@link NxisWarning}
|
|
101
|
+
* Thrown if the proxy returns 200 but no data is available for the page.
|
|
102
|
+
*
|
|
103
|
+
* @internal
|
|
104
|
+
*/
|
|
105
|
+
export async function fetchStructuredData(
|
|
106
|
+
uri: string,
|
|
107
|
+
accessToken: string,
|
|
108
|
+
apiHost: string,
|
|
109
|
+
userAgent?: string,
|
|
110
|
+
siteId?: string,
|
|
111
|
+
): Promise<StructuredDataResponse> {
|
|
112
|
+
const endpoint = new URL(`${apiHost}/v1/nxis:ssr`);
|
|
113
|
+
endpoint.searchParams.append("uri", uri);
|
|
114
|
+
if (siteId) endpoint.searchParams.append("site_id", siteId);
|
|
115
|
+
|
|
116
|
+
const hdrs: Record<string, string> = {
|
|
117
|
+
"Content-Type": "application/json",
|
|
118
|
+
"Authorization": `Bearer ${accessToken}`,
|
|
119
|
+
};
|
|
120
|
+
if (userAgent) hdrs["User-Agent"] = userAgent;
|
|
121
|
+
const response = await fetch(endpoint.toString(), { headers: hdrs });
|
|
122
|
+
return responseHandler(response, uri);
|
|
123
|
+
}
|
|
124
|
+
|
package/src/index.ts
ADDED
|
@@ -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';
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { NxisClientConfig, NxisSSRRequest } from './api';
|
|
2
|
+
import { OAuthTokenManager } from './auth';
|
|
3
|
+
import { fetchStructuredData } from './core';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A client for fetching JSON-LD structured data from the Nxis AI platform.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* `NxisClient` encapsulates OAuth authentication and token lifecycle
|
|
10
|
+
* management. Initialize once with your client credentials, then call
|
|
11
|
+
* {@link NxisClient.getStructuredData} for each page render.
|
|
12
|
+
*
|
|
13
|
+
* Tokens are cached in memory and refreshed automatically before
|
|
14
|
+
* expiration — no manual token handling is needed.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```tsx
|
|
18
|
+
* // Next.js App Router
|
|
19
|
+
* import { NxisClient } from '@nxisai/nxis/ssr';
|
|
20
|
+
* import { headers } from 'next/headers';
|
|
21
|
+
*
|
|
22
|
+
* const nxis = new NxisClient({
|
|
23
|
+
* clientId: process.env.NXIS_CLIENT_ID!,
|
|
24
|
+
* clientSecret: process.env.NXIS_CLIENT_SECRET!,
|
|
25
|
+
* });
|
|
26
|
+
*
|
|
27
|
+
* export default async function Page() {
|
|
28
|
+
* const headersList = await headers();
|
|
29
|
+
* const host = headersList.get('host') ?? 'localhost:3000';
|
|
30
|
+
* const proto = headersList.get('x-forwarded-proto') ?? 'http';
|
|
31
|
+
*
|
|
32
|
+
* const jsonLd = await nxis.getStructuredData({
|
|
33
|
+
* uri: `${proto}://${host}/`,
|
|
34
|
+
* userAgent: headersList.get('user-agent') ?? undefined,
|
|
35
|
+
* });
|
|
36
|
+
*
|
|
37
|
+
* return (
|
|
38
|
+
* <script
|
|
39
|
+
* type="application/ld+json"
|
|
40
|
+
* dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
|
|
41
|
+
* />
|
|
42
|
+
* );
|
|
43
|
+
* }
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export class NxisClient {
|
|
47
|
+
private readonly tokenManager: OAuthTokenManager;
|
|
48
|
+
private readonly apiHost: string;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Creates a new Nxis client.
|
|
52
|
+
*
|
|
53
|
+
* @param config - Client configuration including OAuth credentials and
|
|
54
|
+
* optional host/token URL overrides.
|
|
55
|
+
*
|
|
56
|
+
* @throws {@link Error}
|
|
57
|
+
* Thrown if `NXIS_API_HOST` is not set and no `apiHost` override is provided.
|
|
58
|
+
*/
|
|
59
|
+
constructor(config: NxisClientConfig) {
|
|
60
|
+
this.apiHost = config.apiHost ?? process.env.NXIS_API_HOST ?? '';
|
|
61
|
+
if (!this.apiHost) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
'NXIS_API_HOST is not set. Pass apiHost in the config or set the NXIS_API_HOST environment variable.',
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
this.tokenManager = new OAuthTokenManager({
|
|
68
|
+
clientId: config.clientId,
|
|
69
|
+
clientSecret: config.clientSecret,
|
|
70
|
+
tokenUrl: config.tokenUrl,
|
|
71
|
+
scope: config.scope,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Fetches JSON-LD structured data for a given page URL.
|
|
77
|
+
*
|
|
78
|
+
* @remarks
|
|
79
|
+
* Returns a JSON-LD object ready to be serialized into a
|
|
80
|
+
* `<script type="application/ld+json">` tag in your server-rendered HTML.
|
|
81
|
+
*
|
|
82
|
+
* The client automatically obtains a valid OAuth access token before
|
|
83
|
+
* making the request. Tokens are cached and refreshed transparently.
|
|
84
|
+
*
|
|
85
|
+
* @param req - Request-specific parameters (page URI and optional User-Agent).
|
|
86
|
+
* @returns A JSON-LD object to embed in the page.
|
|
87
|
+
*
|
|
88
|
+
* @throws {@link ProxyError}
|
|
89
|
+
* Thrown when the proxy returns a non-200 response (auth failures, rate
|
|
90
|
+
* limits, server errors, etc.).
|
|
91
|
+
*
|
|
92
|
+
* @throws {@link NxisWarning}
|
|
93
|
+
* Thrown when the proxy returns 200 but no structured data exists for the page.
|
|
94
|
+
*/
|
|
95
|
+
async getStructuredData(req: NxisSSRRequest): Promise<Record<string, unknown>> {
|
|
96
|
+
const accessToken = await this.tokenManager.getAccessToken();
|
|
97
|
+
const response = await fetchStructuredData(
|
|
98
|
+
req.uri,
|
|
99
|
+
accessToken,
|
|
100
|
+
this.apiHost,
|
|
101
|
+
req.userAgent,
|
|
102
|
+
req.siteId,
|
|
103
|
+
);
|
|
104
|
+
return response.data;
|
|
105
|
+
}
|
|
106
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
/* Basic Options */
|
|
4
|
+
// "incremental": true, /* Enable incremental compilation */
|
|
5
|
+
"target": "es2018",
|
|
6
|
+
"module": "esnext",
|
|
7
|
+
"moduleResolution": "node",
|
|
8
|
+
// "lib": [], /* Specify library files to be included in the compilation. */
|
|
9
|
+
// "allowJs": true, /* Allow javascript files to be compiled. */
|
|
10
|
+
// "checkJs": true, /* Report errors in .js files. */
|
|
11
|
+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
|
12
|
+
"declaration": true, /* Generates corresponding '.d.ts' file. */
|
|
13
|
+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
|
14
|
+
// "sourceMap": true, /* Generates corresponding '.map' file. */
|
|
15
|
+
// "outFile": "./", /* Concatenate and emit output to single file. */
|
|
16
|
+
// "outDir": "./", /* Redirect output structure to the directory. */
|
|
17
|
+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
|
18
|
+
// "composite": true, /* Enable project compilation */
|
|
19
|
+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
|
20
|
+
// "removeComments": true, /* Do not emit comments to output. */
|
|
21
|
+
// "noEmit": true, /* Do not emit outputs. */
|
|
22
|
+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
|
23
|
+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
|
24
|
+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
|
25
|
+
|
|
26
|
+
/* Strict Type-Checking Options */
|
|
27
|
+
"strict": true, /* Enable all strict type-checking options. */
|
|
28
|
+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
|
29
|
+
// "strictNullChecks": true, /* Enable strict null checks. */
|
|
30
|
+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
|
31
|
+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
|
32
|
+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
|
33
|
+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
|
34
|
+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
|
35
|
+
|
|
36
|
+
/* Additional Checks */
|
|
37
|
+
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
|
38
|
+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
|
39
|
+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
|
40
|
+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
|
41
|
+
|
|
42
|
+
/* Module Resolution Options */
|
|
43
|
+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
|
44
|
+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
|
45
|
+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
|
46
|
+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
|
47
|
+
// "typeRoots": [], /* List of folders to include type definitions from. */
|
|
48
|
+
// "types": [], /* Type declaration files to be included in compilation. */
|
|
49
|
+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
|
50
|
+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
|
51
|
+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
|
52
|
+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
53
|
+
|
|
54
|
+
/* Source Map Options */
|
|
55
|
+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
|
56
|
+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
57
|
+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
|
58
|
+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
|
59
|
+
|
|
60
|
+
/* Experimental Options */
|
|
61
|
+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
|
62
|
+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
|
63
|
+
},
|
|
64
|
+
"include": ["src"],
|
|
65
|
+
"exclude": ["node_modules", "build", "examples"]
|
|
66
|
+
}
|