@ninetailed/experience.js-next-esr 1.0.0-beta.13

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/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # experience-sdk-nextjs-esr
2
+
3
+ This library was generated with [Nx](https://nx.dev).
4
+
5
+ ## Running unit tests
6
+
7
+ Run `nx test experience-sdk-nextjs-esr` to execute the unit tests via [Jest](https://jestjs.io).
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './lib/build-esr-context';
2
+ export * from './lib/get-edge-side-profile';
3
+ export * from './lib/selector';
package/index.esm.js ADDED
@@ -0,0 +1,155 @@
1
+ import { v4 } from 'uuid';
2
+ import { buildPageEvent, buildEmptyCache } from '@ninetailed/experience.js-shared';
3
+
4
+ function absoluteUrl(req, localhostAddress = 'localhost:3000') {
5
+ const hostHeader = req.headers.get('host');
6
+ let host = hostHeader ? hostHeader : localhostAddress;
7
+ let protocol = /^localhost(:\d+)?$/.test(host) ? 'http:' : 'https:';
8
+
9
+ if (req && req.headers.get('x-forwarded-host') && typeof req.headers.get('x-forwarded-host') === 'string') {
10
+ host = req.headers.get('x-forwarded-host');
11
+ }
12
+
13
+ if (req && req.headers.get('x-forwarded-proto') && typeof req.headers.get('x-forwarded-proto') === 'string') {
14
+ protocol = `${req.headers.get('x-forwarded-proto')}:`;
15
+ }
16
+
17
+ return {
18
+ protocol,
19
+ host,
20
+ origin: protocol + '//' + host
21
+ };
22
+ }
23
+
24
+ const getLocale = req => {
25
+ try {
26
+ return req.nextUrl.locale;
27
+ } catch (error) {
28
+ return req.nextUrl.defaultLocale || '';
29
+ }
30
+ };
31
+
32
+ const buildEsrNinetailedRequestContext = ({
33
+ req
34
+ }) => {
35
+ const url = new URL(`${req.nextUrl.pathname}${req.nextUrl.search}`, absoluteUrl(req).origin);
36
+ return {
37
+ url: url.toString(),
38
+ locale: getLocale(req),
39
+ referrer: req.headers.get('referer') || '',
40
+ userAgent: req.headers.get('user-agent') || ''
41
+ };
42
+ };
43
+
44
+ /*! *****************************************************************************
45
+ Copyright (c) Microsoft Corporation.
46
+
47
+ Permission to use, copy, modify, and/or distribute this software for any
48
+ purpose with or without fee is hereby granted.
49
+
50
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
51
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
52
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
53
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
54
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
55
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
56
+ PERFORMANCE OF THIS SOFTWARE.
57
+ ***************************************************************************** */
58
+
59
+ function __awaiter(thisArg, _arguments, P, generator) {
60
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
61
+ return new (P || (P = Promise))(function (resolve, reject) {
62
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
63
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
64
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
65
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
66
+ });
67
+ }
68
+
69
+ const NINETAILED_PROFILE_CACHE_COOKIE = 'ntpc';
70
+ const BASE_URL = 'https://api.ninetailed.co';
71
+
72
+ const getProfileCache = cookies => {
73
+ const cacheString = cookies[NINETAILED_PROFILE_CACHE_COOKIE];
74
+
75
+ if (cacheString) {
76
+ try {
77
+ return JSON.parse(decodeURIComponent(cacheString));
78
+ } catch (error) {
79
+ console.error(error);
80
+ }
81
+ }
82
+
83
+ return buildEmptyCache();
84
+ };
85
+
86
+ const getEdgeSideProfile = ({
87
+ ctx,
88
+ cookies,
89
+ apiKey,
90
+ url = BASE_URL,
91
+ ip,
92
+ location
93
+ }) => __awaiter(void 0, void 0, void 0, function* () {
94
+ const cacheFromCookie = getProfileCache(cookies);
95
+ const anonymousId = cacheFromCookie.id;
96
+ const pageEvent = buildPageEvent({
97
+ ctx,
98
+ anonymousId,
99
+ messageId: v4(),
100
+ timestamp: Date.now(),
101
+ properties: {}
102
+ });
103
+ const request = yield fetch(`${url}/profile/${anonymousId}/events`, {
104
+ method: 'POST',
105
+ headers: {
106
+ 'Content-Type': 'application/json',
107
+ 'x-ninetailed-api-key': apiKey
108
+ },
109
+ body: JSON.stringify(Object.assign(Object.assign(Object.assign({
110
+ events: [pageEvent]
111
+ }, cacheFromCookie), {
112
+ ip
113
+ }), {
114
+ location
115
+ }))
116
+ });
117
+ const {
118
+ data: {
119
+ profile,
120
+ traitsUpdatedAt,
121
+ signals
122
+ }
123
+ } = yield request.json();
124
+ return {
125
+ profile,
126
+ cache: {
127
+ id: profile.id,
128
+ random: profile.random,
129
+ audiences: profile.audiences,
130
+ location: profile.location,
131
+ session: profile.session,
132
+ traitsUpdatedAt,
133
+ traits: profile.traits,
134
+ signals,
135
+ sessions: cacheFromCookie.sessions
136
+ }
137
+ };
138
+ });
139
+
140
+ const selectNinetailedProfile = ({
141
+ ninetailed
142
+ }) => {
143
+ if (!ninetailed) {
144
+ return null;
145
+ }
146
+
147
+ try {
148
+ const data = JSON.parse(ninetailed);
149
+ return data.profile;
150
+ } catch (_a) {
151
+ return null;
152
+ }
153
+ };
154
+
155
+ export { NINETAILED_PROFILE_CACHE_COOKIE, buildEsrNinetailedRequestContext, getEdgeSideProfile, selectNinetailedProfile };
package/index.umd.js ADDED
@@ -0,0 +1,222 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('uuid'), require('@ninetailed/experience.js-shared')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'uuid', '@ninetailed/experience.js-shared'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NextjsEsr = {}, global.uuid, global.experience_jsShared));
5
+ })(this, (function (exports, uuid, experience_jsShared) { 'use strict';
6
+
7
+ function absoluteUrl(req, localhostAddress) {
8
+ if (localhostAddress === void 0) {
9
+ localhostAddress = 'localhost:3000';
10
+ }
11
+
12
+ var hostHeader = req.headers.get('host');
13
+ var host = hostHeader ? hostHeader : localhostAddress;
14
+ var protocol = /^localhost(:\d+)?$/.test(host) ? 'http:' : 'https:';
15
+
16
+ if (req && req.headers.get('x-forwarded-host') && typeof req.headers.get('x-forwarded-host') === 'string') {
17
+ host = req.headers.get('x-forwarded-host');
18
+ }
19
+
20
+ if (req && req.headers.get('x-forwarded-proto') && typeof req.headers.get('x-forwarded-proto') === 'string') {
21
+ protocol = "".concat(req.headers.get('x-forwarded-proto'), ":");
22
+ }
23
+
24
+ return {
25
+ protocol: protocol,
26
+ host: host,
27
+ origin: protocol + '//' + host
28
+ };
29
+ }
30
+
31
+ var getLocale = function (req) {
32
+ try {
33
+ return req.nextUrl.locale;
34
+ } catch (error) {
35
+ return req.nextUrl.defaultLocale || '';
36
+ }
37
+ };
38
+
39
+ var buildEsrNinetailedRequestContext = function (_a) {
40
+ var req = _a.req;
41
+ var url = new URL("".concat(req.nextUrl.pathname).concat(req.nextUrl.search), absoluteUrl(req).origin);
42
+ return {
43
+ url: url.toString(),
44
+ locale: getLocale(req),
45
+ referrer: req.headers.get('referer') || '',
46
+ userAgent: req.headers.get('user-agent') || ''
47
+ };
48
+ };
49
+
50
+ /*! *****************************************************************************
51
+ Copyright (c) Microsoft Corporation.
52
+
53
+ Permission to use, copy, modify, and/or distribute this software for any
54
+ purpose with or without fee is hereby granted.
55
+
56
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
57
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
58
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
59
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
60
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
61
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
62
+ PERFORMANCE OF THIS SOFTWARE.
63
+ ***************************************************************************** */
64
+
65
+ var __assign = function() {
66
+ __assign = Object.assign || function __assign(t) {
67
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
68
+ s = arguments[i];
69
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
70
+ }
71
+ return t;
72
+ };
73
+ return __assign.apply(this, arguments);
74
+ };
75
+
76
+ function __awaiter(thisArg, _arguments, P, generator) {
77
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
78
+ return new (P || (P = Promise))(function (resolve, reject) {
79
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
80
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
81
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
82
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
83
+ });
84
+ }
85
+
86
+ function __generator(thisArg, body) {
87
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
88
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
89
+ function verb(n) { return function (v) { return step([n, v]); }; }
90
+ function step(op) {
91
+ if (f) throw new TypeError("Generator is already executing.");
92
+ while (_) try {
93
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
94
+ if (y = 0, t) op = [op[0] & 2, t.value];
95
+ switch (op[0]) {
96
+ case 0: case 1: t = op; break;
97
+ case 4: _.label++; return { value: op[1], done: false };
98
+ case 5: _.label++; y = op[1]; op = [0]; continue;
99
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
100
+ default:
101
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
102
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
103
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
104
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
105
+ if (t[2]) _.ops.pop();
106
+ _.trys.pop(); continue;
107
+ }
108
+ op = body.call(thisArg, _);
109
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
110
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
111
+ }
112
+ }
113
+
114
+ var NINETAILED_PROFILE_CACHE_COOKIE = 'ntpc';
115
+ var BASE_URL = 'https://api.ninetailed.co';
116
+
117
+ var getProfileCache = function (cookies) {
118
+ var cacheString = cookies[NINETAILED_PROFILE_CACHE_COOKIE];
119
+
120
+ if (cacheString) {
121
+ try {
122
+ return JSON.parse(decodeURIComponent(cacheString));
123
+ } catch (error) {
124
+ console.error(error);
125
+ }
126
+ }
127
+
128
+ return experience_jsShared.buildEmptyCache();
129
+ };
130
+
131
+ var getEdgeSideProfile = function (_a) {
132
+ var ctx = _a.ctx,
133
+ cookies = _a.cookies,
134
+ apiKey = _a.apiKey,
135
+ _b = _a.url,
136
+ url = _b === void 0 ? BASE_URL : _b,
137
+ ip = _a.ip,
138
+ location = _a.location;
139
+ return __awaiter(void 0, void 0, void 0, function () {
140
+ var cacheFromCookie, anonymousId, pageEvent, request, _c, profile, traitsUpdatedAt, signals;
141
+
142
+ return __generator(this, function (_d) {
143
+ switch (_d.label) {
144
+ case 0:
145
+ cacheFromCookie = getProfileCache(cookies);
146
+ anonymousId = cacheFromCookie.id;
147
+ pageEvent = experience_jsShared.buildPageEvent({
148
+ ctx: ctx,
149
+ anonymousId: anonymousId,
150
+ messageId: uuid.v4(),
151
+ timestamp: Date.now(),
152
+ properties: {}
153
+ });
154
+ return [4
155
+ /*yield*/
156
+ , fetch("".concat(url, "/profile/").concat(anonymousId, "/events"), {
157
+ method: 'POST',
158
+ headers: {
159
+ 'Content-Type': 'application/json',
160
+ 'x-ninetailed-api-key': apiKey
161
+ },
162
+ body: JSON.stringify(__assign(__assign(__assign({
163
+ events: [pageEvent]
164
+ }, cacheFromCookie), {
165
+ ip: ip
166
+ }), {
167
+ location: location
168
+ }))
169
+ })];
170
+
171
+ case 1:
172
+ request = _d.sent();
173
+ return [4
174
+ /*yield*/
175
+ , request.json()];
176
+
177
+ case 2:
178
+ _c = _d.sent().data, profile = _c.profile, traitsUpdatedAt = _c.traitsUpdatedAt, signals = _c.signals;
179
+ return [2
180
+ /*return*/
181
+ , {
182
+ profile: profile,
183
+ cache: {
184
+ id: profile.id,
185
+ random: profile.random,
186
+ audiences: profile.audiences,
187
+ location: profile.location,
188
+ session: profile.session,
189
+ traitsUpdatedAt: traitsUpdatedAt,
190
+ traits: profile.traits,
191
+ signals: signals,
192
+ sessions: cacheFromCookie.sessions
193
+ }
194
+ }];
195
+ }
196
+ });
197
+ });
198
+ };
199
+
200
+ var selectNinetailedProfile = function (_a) {
201
+ var ninetailed = _a.ninetailed;
202
+
203
+ if (!ninetailed) {
204
+ return null;
205
+ }
206
+
207
+ try {
208
+ var data = JSON.parse(ninetailed);
209
+ return data.profile;
210
+ } catch (_b) {
211
+ return null;
212
+ }
213
+ };
214
+
215
+ exports.NINETAILED_PROFILE_CACHE_COOKIE = NINETAILED_PROFILE_CACHE_COOKIE;
216
+ exports.buildEsrNinetailedRequestContext = buildEsrNinetailedRequestContext;
217
+ exports.getEdgeSideProfile = getEdgeSideProfile;
218
+ exports.selectNinetailedProfile = selectNinetailedProfile;
219
+
220
+ Object.defineProperty(exports, '__esModule', { value: true });
221
+
222
+ }));
@@ -0,0 +1,6 @@
1
+ import { NextRequest } from 'next/server';
2
+ export declare function absoluteUrl(req: NextRequest, localhostAddress?: string): {
3
+ protocol: string;
4
+ host: string;
5
+ origin: string;
6
+ };
@@ -0,0 +1,5 @@
1
+ import type { NextRequest } from 'next/server';
2
+ import { NinetailedRequestContext } from '@ninetailed/experience.js-shared';
3
+ export declare const buildEsrNinetailedRequestContext: ({ req, }: {
4
+ req: NextRequest;
5
+ }) => NinetailedRequestContext;
@@ -0,0 +1,18 @@
1
+ import { Profile, GeoLocation, NinetailedRequestContext, Cache } from '@ninetailed/experience.js-shared';
2
+ export declare const NINETAILED_PROFILE_CACHE_COOKIE = "ntpc";
3
+ declare type Cookies = {
4
+ [key: string]: string;
5
+ };
6
+ declare type GetServerSideProfileOptions = {
7
+ ctx: NinetailedRequestContext;
8
+ cookies: Cookies;
9
+ apiKey: string;
10
+ url?: string;
11
+ ip?: string;
12
+ location?: GeoLocation;
13
+ };
14
+ export declare const getEdgeSideProfile: ({ ctx, cookies, apiKey, url, ip, location, }: GetServerSideProfileOptions) => Promise<{
15
+ profile: Profile;
16
+ cache: Cache;
17
+ }>;
18
+ export {};
File without changes
@@ -0,0 +1,6 @@
1
+ import { Profile } from '@ninetailed/experience.js-shared';
2
+ declare type SelectNinetailedProfileOptions = {
3
+ ninetailed: string;
4
+ };
5
+ export declare const selectNinetailedProfile: ({ ninetailed, }: SelectNinetailedProfileOptions) => Profile | null;
6
+ export {};
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@ninetailed/experience.js-next-esr",
3
+ "version": "1.0.0-beta.13",
4
+ "dependencies": {
5
+ "next": "12.1.0"
6
+ },
7
+ "main": "./index.umd.js",
8
+ "module": "./index.esm.js",
9
+ "typings": "./index.d.ts",
10
+ "peerDependencies": {
11
+ "@ninetailed/experience.js-shared": "1.0.0-beta.13",
12
+ "uuid": "^8.3.2",
13
+ "ts-toolbelt": "^9.6.0",
14
+ "locale-enum": "^1.1.1",
15
+ "i18n-iso-countries": "^7.3.0"
16
+ }
17
+ }