@levo-so/next-middleware 0.1.97 → 0.3.7

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,37 @@
1
+ /**
2
+ * GeoIP header extractor.
3
+ *
4
+ * Pulls visitor country + language from HTTP headers across CDN providers
5
+ * (Cloudflare, Vercel, AWS CloudFront, Azure, BunnyCDN), nginx-ingress, and
6
+ * Traefik GeoIP2. Only surfaces `bestCountry` + `languageData` — the helpers
7
+ * that were historically exported (client IPs, provider-specific getters,
8
+ * raw header maps) are no longer used by any consumer.
9
+ */
10
+ export interface ICountryInfo {
11
+ countryCode: string;
12
+ city?: string;
13
+ region?: string;
14
+ latitude?: string;
15
+ longitude?: string;
16
+ source: string;
17
+ }
18
+ export interface ILanguageInfo {
19
+ locale: string;
20
+ language: string;
21
+ region?: string;
22
+ quality: number;
23
+ }
24
+ export interface IParsedLanguageData {
25
+ languages: ILanguageInfo[];
26
+ primaryLanguage: string;
27
+ inferredRegions: string[];
28
+ }
29
+ /**
30
+ * Main entry: extract visitor country + language preferences.
31
+ * Accepts any header carrier — normalization is internal.
32
+ */
33
+ export declare const extractGeoAndLanguageData: (headers: Record<string, string | string[]> | Headers | null | undefined) => {
34
+ bestCountry: ICountryInfo | null;
35
+ languageData: IParsedLanguageData;
36
+ };
37
+ //# sourceMappingURL=geoIp.d.ts.map
package/dist/geoIp.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * GeoIP header extractor.
3
+ *
4
+ * Pulls visitor country + language from HTTP headers across CDN providers
5
+ * (Cloudflare, Vercel, AWS CloudFront, Azure, BunnyCDN), nginx-ingress, and
6
+ * Traefik GeoIP2. Only surfaces `bestCountry` + `languageData` — the helpers
7
+ * that were historically exported (client IPs, provider-specific getters,
8
+ * raw header maps) are no longer used by any consumer.
9
+ */
10
+ const safeDecode = (value) => {
11
+ try {
12
+ return decodeURIComponent(value);
13
+ }
14
+ catch {
15
+ return value;
16
+ }
17
+ };
18
+ /** Best country info from CDN (preferred) or nginx/traefik (fallback). */
19
+ const extractCountry = (headers) => {
20
+ // Cloudflare — "XX" is Cloudflare's "unknown" sentinel
21
+ const cf = headers["cf-ipcountry"];
22
+ if (cf && cf !== "XX")
23
+ return { countryCode: cf, source: "Cloudflare CDN" };
24
+ // Vercel Edge — city is URL-encoded (e.g. `San%20Francisco`)
25
+ const vercel = headers["x-vercel-ip-country"];
26
+ if (vercel) {
27
+ const rawCity = headers["x-vercel-ip-city"];
28
+ return {
29
+ countryCode: vercel,
30
+ city: rawCity ? safeDecode(rawCity) : undefined,
31
+ region: headers["x-vercel-ip-country-region"],
32
+ latitude: headers["x-vercel-ip-latitude"],
33
+ longitude: headers["x-vercel-ip-longitude"],
34
+ source: "Vercel Edge",
35
+ };
36
+ }
37
+ const aws = headers["cloudfront-viewer-country"];
38
+ if (aws)
39
+ return { countryCode: aws, source: "AWS CloudFront" };
40
+ const azure = headers["x-azure-country"];
41
+ if (azure)
42
+ return { countryCode: azure, source: "Azure CDN" };
43
+ const bunny = headers["x-edge-country"];
44
+ if (bunny)
45
+ return { countryCode: bunny, source: "BunnyCDN" };
46
+ const generic = headers["x-client-country"] || headers["x-forwarded-country"] || headers["x-country"];
47
+ if (generic)
48
+ return { countryCode: generic, source: "Generic CDN" };
49
+ // Infrastructure fallbacks
50
+ const nginx = headers["x-country-code"];
51
+ if (nginx) {
52
+ return {
53
+ countryCode: nginx,
54
+ city: headers["x-city"],
55
+ latitude: headers["x-latitude"],
56
+ longitude: headers["x-longitude"],
57
+ source: "nginx-ingress",
58
+ };
59
+ }
60
+ const traefik = headers["x-geoip2-country"];
61
+ if (traefik) {
62
+ return {
63
+ countryCode: traefik,
64
+ city: headers["x-geoip2-city"],
65
+ region: headers["x-geoip2-region"],
66
+ source: "traefik-geoip2",
67
+ };
68
+ }
69
+ return null;
70
+ };
71
+ /** Parse Accept-Language into quality-sorted list + derived regions. */
72
+ const parseAcceptLanguage = (acceptLanguage) => {
73
+ if (!acceptLanguage) {
74
+ return { languages: [], primaryLanguage: "unknown", inferredRegions: [] };
75
+ }
76
+ const languages = acceptLanguage
77
+ .split(",")
78
+ .map((lang) => {
79
+ const [locale, quality] = lang.trim().split(";q=");
80
+ const [language, region] = (locale || "").split("-");
81
+ return {
82
+ locale: locale?.trim() || "",
83
+ language: language?.trim() || "",
84
+ region: region?.trim().toUpperCase(),
85
+ quality: quality ? parseFloat(quality) : 1.0,
86
+ };
87
+ })
88
+ .filter((l) => l.locale)
89
+ .sort((a, b) => b.quality - a.quality);
90
+ const inferredRegions = languages
91
+ .map((l) => l.region)
92
+ .filter((r) => Boolean(r))
93
+ .filter((r, i, arr) => arr.indexOf(r) === i);
94
+ return {
95
+ languages,
96
+ primaryLanguage: languages[0]?.locale || "unknown",
97
+ inferredRegions,
98
+ };
99
+ };
100
+ /**
101
+ * Normalize any header carrier (Fetch `Headers`, Node `req.headers`, plain
102
+ * object) into a lowercase-keyed map.
103
+ */
104
+ const headersToObject = (headers) => {
105
+ if (!headers)
106
+ return {};
107
+ if (typeof headers.entries === "function") {
108
+ const obj = {};
109
+ for (const [k, v] of headers.entries())
110
+ obj[k.toLowerCase()] = v;
111
+ return obj;
112
+ }
113
+ const obj = {};
114
+ for (const [k, v] of Object.entries(headers)) {
115
+ obj[k.toLowerCase()] = Array.isArray(v) ? v.join(", ") : String(v);
116
+ }
117
+ return obj;
118
+ };
119
+ /**
120
+ * Main entry: extract visitor country + language preferences.
121
+ * Accepts any header carrier — normalization is internal.
122
+ */
123
+ export const extractGeoAndLanguageData = (headers) => {
124
+ const normalized = headersToObject(headers);
125
+ return {
126
+ bestCountry: extractCountry(normalized),
127
+ languageData: parseAcceptLanguage(normalized["accept-language"] || ""),
128
+ };
129
+ };
package/dist/index.d.ts CHANGED
@@ -16,6 +16,8 @@ declare function middleware(request: NextRequest, options?: {
16
16
  declare const levoConfig: {
17
17
  matcher: string[];
18
18
  };
19
+ export * from "./geoIp";
20
+ export * from "./params";
19
21
  export default middleware;
20
- export { middleware, levoConfig };
22
+ export { levoConfig, middleware };
21
23
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -22,12 +22,35 @@ function middleware(request, options = {}) {
22
22
  // new URL(request.url).protocol = "http:"
23
23
  modified_headers.set("origin", `${new URL(request.url).protocol}//${host}`);
24
24
  }
25
+ // Dev-only: tell the backend the proxied request is https so its
26
+ // ingress-nginx `force-ssl-redirect` doesn't 308 us to a port-stripped
27
+ // URL (`next dev` serves over plain http). Gated off in production, where
28
+ // genuine http must still redirect and these paths bypass this code.
29
+ if (process.env.NODE_ENV !== "production") {
30
+ modified_headers.set("x-forwarded-proto", "https");
31
+ }
25
32
  if (host && pathname.startsWith("/.levo/public/api")) {
26
33
  const targetPath = pathname.replace(/^\/.levo\/public\/api/, "");
27
34
  const workspaceQuery = workspace && !search.includes("workspace=")
28
35
  ? `${search ? "&" : "?"}workspace=${workspace}`
29
36
  : "";
30
37
  const targetURL = `${apiUrl}${targetPath}${search}${workspaceQuery}${hash}`;
38
+ // SSE endpoints must opt out of Next.js's gzip layer when running under
39
+ // `next dev`. Dev mode buffers ~16KB before flushing, which collapses
40
+ // per-token text-deltas into one frame and breaks the wire-level streaming
41
+ // the BE provides. We can't set a response header from middleware on
42
+ // absolute-URL rewrites (Next discards them), so we override the incoming
43
+ // `Accept-Encoding` to `identity` — Next's compression middleware reads
44
+ // request accept-encoding before deciding to gzip, and `identity` skips it.
45
+ //
46
+ // Gated to `NODE_ENV !== "production"` because production runs behind a
47
+ // CDN / nginx layer that handles SSE pass-through correctly; we don't want
48
+ // to force-disable encoding negotiation for real traffic. `NODE_ENV` is
49
+ // inlined at build time, so the entire block is dead-code-eliminated from
50
+ // the production bundle.
51
+ if (process.env.NODE_ENV !== "production" && targetPath.endsWith("/stream")) {
52
+ modified_headers.set("accept-encoding", "identity");
53
+ }
31
54
  return NextResponse.rewrite(targetURL, {
32
55
  request: {
33
56
  headers: modified_headers,
@@ -82,5 +105,7 @@ const levoConfig = {
82
105
  "/(.*sitemap.*\\.xml)",
83
106
  ],
84
107
  };
108
+ export * from "./geoIp";
109
+ export * from "./params";
85
110
  export default middleware;
86
- export { middleware, levoConfig };
111
+ export { levoConfig, middleware };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Helpers for reading Next.js route `params` produced by the proxy's
3
+ * `/visitor:{...json}/...` rewrite.
4
+ */
5
+ export interface IParsedRouteParams {
6
+ slug: string[];
7
+ visitorParams: Record<string, unknown>;
8
+ }
9
+ /** Parse a `visitor:{...}` segment back into its JSON payload. */
10
+ export declare const parseVisitorParam: (visitor: string | undefined) => Record<string, unknown>;
11
+ /**
12
+ * Pull `visitorParams` + clean `slug` out of a Next.js catch-all `params`.
13
+ * If the first slug segment is a `visitor:{...}` prefix, it is stripped and
14
+ * decoded; otherwise `visitorParams` falls back to `{}`.
15
+ */
16
+ export declare const parseParams: (params: Record<string, string | string[] | undefined> | undefined) => IParsedRouteParams;
17
+ //# sourceMappingURL=params.d.ts.map
package/dist/params.js ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Helpers for reading Next.js route `params` produced by the proxy's
3
+ * `/visitor:{...json}/...` rewrite.
4
+ */
5
+ /** Parse a `visitor:{...}` segment back into its JSON payload. */
6
+ export const parseVisitorParam = (visitor) => {
7
+ if (typeof visitor !== "string")
8
+ return {};
9
+ try {
10
+ return JSON.parse(visitor.replace(/^visitor:/, ""));
11
+ }
12
+ catch {
13
+ return {};
14
+ }
15
+ };
16
+ /**
17
+ * Pull `visitorParams` + clean `slug` out of a Next.js catch-all `params`.
18
+ * If the first slug segment is a `visitor:{...}` prefix, it is stripped and
19
+ * decoded; otherwise `visitorParams` falls back to `{}`.
20
+ */
21
+ export const parseParams = (params) => {
22
+ const rawSlug = Array.isArray(params?.slug) ? params.slug : [];
23
+ const [first, ...rest] = rawSlug;
24
+ if (typeof first === "string" && first.startsWith("visitor:")) {
25
+ return { slug: rest, visitorParams: parseVisitorParam(first) };
26
+ }
27
+ return { slug: rawSlug, visitorParams: {} };
28
+ };
package/package.json CHANGED
@@ -1,37 +1,38 @@
1
1
  {
2
2
  "name": "@levo-so/next-middleware",
3
- "version": "0.1.97",
4
- "author": "Levo Engineering <devs@theinternetfolks.com>",
5
3
  "description": "Next middleware to add a proxy for levo integration in apps",
6
- "type": "module",
7
- "sideEffects": false,
8
- "publishConfig": {
9
- "access": "public"
10
- },
11
- "files": [
12
- "dist/**",
13
- "!dist/**/*.d.ts.map",
14
- "package.json"
15
- ],
16
- "peerDependencies": {
17
- "next": ">13.0.0 <=17"
18
- },
4
+ "version": "0.3.7",
5
+ "author": "Levo Engineering <devs@theinternetfolks.com>",
19
6
  "devDependencies": {
20
7
  "@types/react": "19.2.14",
21
8
  "@types/react-dom": "19.2.3",
22
9
  "babel-plugin-react-compiler": "19.1.0-rc.3",
23
- "next": "16.2.1",
10
+ "next": "16.2.6",
24
11
  "react": "19.2.4",
25
12
  "react-dom": "19.2.4",
26
13
  "@levo/ts-config": "0.0.0"
27
14
  },
15
+ "files": [
16
+ "dist/**",
17
+ "!dist/**/*.d.ts.map",
18
+ "!dist/**/*.js.map",
19
+ "package.json"
20
+ ],
28
21
  "main": "./dist/index.js",
29
22
  "module": "./dist/index.js",
23
+ "peerDependencies": {
24
+ "next": ">13.0.0 <=17"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "sideEffects": false,
30
+ "type": "module",
30
31
  "types": "./dist/index.d.ts",
31
32
  "scripts": {
32
- "clean": "rimraf dist node_modules .turbo",
33
- "check-types": "tsc --noEmit",
34
33
  "build": "tsc",
34
+ "check-types": "tsc --noEmit",
35
+ "clean": "npx rimraf dist node_modules .turbo",
35
36
  "dev": "tsc --watch"
36
37
  }
37
38
  }