@scalemule/nextjs 0.1.67 → 0.1.69

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/audio.d.mts CHANGED
@@ -202,6 +202,7 @@ declare class NetworkAudioController {
202
202
  constructor(resolve: ResolveNetworkAudio);
203
203
  setResolver(resolve: ResolveNetworkAudio): void;
204
204
  getSnapshot: () => NetworkAudioSnapshot;
205
+ getPosition: () => number;
205
206
  subscribe: (listener: () => void) => () => void;
206
207
  private patch;
207
208
  attach(audio: HTMLAudioElement): void;
@@ -292,6 +293,7 @@ interface NetworkAudioContextValue {
292
293
  notice: string | null;
293
294
  command: (command: NetworkAudioCommand) => void;
294
295
  openNetworkPlayer?: () => void;
296
+ getPosition?: () => number;
295
297
  highlightAvailable: boolean;
296
298
  highlightEnabled: boolean;
297
299
  setHighlightEnabled: (enabled: boolean) => void;
package/dist/audio.d.ts CHANGED
@@ -202,6 +202,7 @@ declare class NetworkAudioController {
202
202
  constructor(resolve: ResolveNetworkAudio);
203
203
  setResolver(resolve: ResolveNetworkAudio): void;
204
204
  getSnapshot: () => NetworkAudioSnapshot;
205
+ getPosition: () => number;
205
206
  subscribe: (listener: () => void) => () => void;
206
207
  private patch;
207
208
  attach(audio: HTMLAudioElement): void;
@@ -292,6 +293,7 @@ interface NetworkAudioContextValue {
292
293
  notice: string | null;
293
294
  command: (command: NetworkAudioCommand) => void;
294
295
  openNetworkPlayer?: () => void;
296
+ getPosition?: () => number;
295
297
  highlightAvailable: boolean;
296
298
  highlightEnabled: boolean;
297
299
  setHighlightEnabled: (enabled: boolean) => void;
package/dist/audio.js CHANGED
@@ -129,6 +129,131 @@ function wordIndexAt(words, timeMs) {
129
129
  }
130
130
  return ans;
131
131
  }
132
+ var UNSTRESSED_FUNCTION_WORDS = /* @__PURE__ */ new Set([
133
+ "a",
134
+ "an",
135
+ "the",
136
+ "of",
137
+ "to",
138
+ "in",
139
+ "on",
140
+ "at",
141
+ "for",
142
+ "and",
143
+ "or",
144
+ "by",
145
+ "as",
146
+ "is",
147
+ "was",
148
+ "were",
149
+ "be",
150
+ "are",
151
+ "with",
152
+ "from",
153
+ "that",
154
+ "this"
155
+ ]);
156
+ var DASH_TOKENS = /* @__PURE__ */ new Set(["\u2014", "\u2013", "--"]);
157
+ function isClauseEnd(sent, i) {
158
+ const n = sent.length;
159
+ if (i === n - 1) return true;
160
+ const stripped = sent[i][0].replace(/["'\u201d\u2019)\]}]+$/u, "");
161
+ if (DASH_TOKENS.has(stripped)) return true;
162
+ if (/[,;:\u2014\u2013]$/u.test(stripped)) {
163
+ if (i + 1 < n && DASH_TOKENS.has(sent[i + 1][0])) return false;
164
+ if (i + 2 < n && DASH_TOKENS.has(sent[i + 2][0])) return false;
165
+ return true;
166
+ }
167
+ return false;
168
+ }
169
+ function rebalanceLegacySentence(sent) {
170
+ const n = sent.length;
171
+ const sStart = sent[0][1];
172
+ const sEnd = sent[n - 1][2];
173
+ const sDur = sEnd - sStart;
174
+ if (n <= 1 || sDur < 600) return sent;
175
+ const clauses = [];
176
+ let startIdx = 0;
177
+ for (let i = 0; i < n; i++) {
178
+ if (isClauseEnd(sent, i)) {
179
+ clauses.push([startIdx, i]);
180
+ startIdx = i + 1;
181
+ }
182
+ }
183
+ const clauseBounds = clauses.map(([i0, i1]) => [sent[i0][1], sent[i1][2]]);
184
+ if (clauses.length >= 2) {
185
+ const [, i1] = clauses[0];
186
+ if (DASH_TOKENS.has(sent[i1][0]) && i1 <= 5) {
187
+ const c0Dur = clauseBounds[0][1] - clauseBounds[0][0];
188
+ const shift = Math.min(450, c0Dur * 0.24);
189
+ clauseBounds[0][1] -= shift;
190
+ clauseBounds[1][0] -= shift;
191
+ }
192
+ }
193
+ const out = [];
194
+ for (let c = 0; c < clauses.length; c++) {
195
+ const [i0, i1] = clauses[c];
196
+ const [cStart, cEnd] = clauseBounds[c];
197
+ const cDur = cEnd - cStart;
198
+ const cLen = i1 - i0 + 1;
199
+ const pauseMs = cLen >= 2 && cDur > 450 ? Math.min(340, cDur * 0.24) : cDur > 300 ? Math.min(180, cDur * 0.18) : 0;
200
+ const speechDur = Math.max(cDur - pauseMs, cDur * 0.72);
201
+ const weights = [];
202
+ for (let idx = i0; idx <= i1; idx++) {
203
+ const [w, st, en] = sent[idx];
204
+ const oldD = Math.max(en - st, 40);
205
+ const stripped = w.replace(/["'\u201d\u2019)\]}]+$/u, "");
206
+ const clean = stripped.replace(/^["'\u201c\u2018([{]+/u, "").replace(/[.,;:!?\u2014\u2013-]+$/u, "").toLowerCase();
207
+ if (DASH_TOKENS.has(w)) {
208
+ weights.push(30);
209
+ } else {
210
+ let weight = Math.pow(oldD, 0.85);
211
+ if (UNSTRESSED_FUNCTION_WORDS.has(clean) && stripped.toLowerCase() === clean) {
212
+ weight *= 0.58;
213
+ }
214
+ weights.push(weight);
215
+ }
216
+ }
217
+ const totW = weights.reduce((a, b) => a + b, 0) || 1;
218
+ let cur = cStart;
219
+ for (let k = 0; k < cLen; k++) {
220
+ const idx = i0 + k;
221
+ const [w, , , si] = sent[idx];
222
+ const wDur = speechDur * (weights[k] / totW);
223
+ const lead = idx > 0 ? Math.min(45, wDur * 0.22) : 0;
224
+ const wSt = Math.max(sStart, cur - lead);
225
+ const wEn = cur + wDur;
226
+ out.push([w, Math.round(wSt), Math.round(Math.max(wSt, wEn)), si]);
227
+ cur = wEn;
228
+ }
229
+ }
230
+ return out;
231
+ }
232
+ function rebalanceSentenceTimings(words) {
233
+ if (words.length <= 1) return words;
234
+ const out = [];
235
+ let i = 0;
236
+ while (i < words.length) {
237
+ let j = i + 1;
238
+ const sIdx = words[i][3];
239
+ while (j < words.length && words[j][3] === sIdx) j++;
240
+ const sent = words.slice(i, j);
241
+ let hasExplicitGaps = false;
242
+ for (let k = 0; k < sent.length - 1; k++) {
243
+ if (sent[k + 1][1] - sent[k][2] >= 25) {
244
+ hasExplicitGaps = true;
245
+ break;
246
+ }
247
+ }
248
+ if (!hasExplicitGaps && j < words.length && words[j][1] - sent[sent.length - 1][2] >= 25) {
249
+ hasExplicitGaps = true;
250
+ }
251
+ const processed = hasExplicitGaps ? sent : rebalanceLegacySentence(sent);
252
+ for (const row of processed) out.push(row);
253
+ i = j;
254
+ }
255
+ return out;
256
+ }
132
257
  function mergeLineBoxes(rects) {
133
258
  const lines = [];
134
259
  const sorted = rects.filter((r) => r.width > 0 && r.height > 0).sort((a, b) => a.top - b.top || a.left - b.left);
@@ -173,7 +298,7 @@ var NarrationHighlighter = class {
173
298
  this.resizeObserver = null;
174
299
  this.onWindowResize = null;
175
300
  this.root = root;
176
- this.words = timings.words;
301
+ this.words = rebalanceSentenceTimings(timings.words);
177
302
  const domWords = collectDomWords(root);
178
303
  const matches = alignWords(
179
304
  this.words.map((w) => normalizeWord(w[0])),
@@ -922,6 +1047,12 @@ var NetworkAudioController = class {
922
1047
  this.resumePosition = null;
923
1048
  this.candidates = [];
924
1049
  this.getSnapshot = () => this.snapshot;
1050
+ this.getPosition = () => {
1051
+ if (this.audio && this.source && this.resumePosition === null && finite(this.audio.currentTime)) {
1052
+ if (this.audio.currentTime > 0 || this.snapshot.position === 0) return this.audio.currentTime;
1053
+ }
1054
+ return this.snapshot.position;
1055
+ };
925
1056
  this.subscribe = (listener) => {
926
1057
  this.listeners.add(listener);
927
1058
  return () => {
@@ -1747,6 +1878,7 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1747
1878
  notice,
1748
1879
  command,
1749
1880
  openNetworkPlayer: connection ? openNetworkPlayer : void 0,
1881
+ getPosition: remoteSnapshot !== null ? void 0 : controller.getPosition,
1750
1882
  highlightAvailable,
1751
1883
  highlightEnabled,
1752
1884
  setHighlightEnabled,
@@ -1812,7 +1944,7 @@ function NetworkMediaSession() {
1812
1944
  var subscribeCapabilities = () => () => {
1813
1945
  };
1814
1946
  function useArticleNarration(track, narration) {
1815
- const { snapshot, highlightEnabled, setHighlightEnabled } = useNetworkAudio();
1947
+ const { snapshot, remote, getPosition, highlightEnabled, setHighlightEnabled } = useNetworkAudio();
1816
1948
  const supported = (0, import_react2.useSyncExternalStore)(subscribeCapabilities, narrationHighlightSupported, () => false);
1817
1949
  const registerNarration = (0, import_react2.useContext)(NarrationRegistration);
1818
1950
  const narrationKey = trackKey(track);
@@ -1822,9 +1954,16 @@ function useArticleNarration(track, narration) {
1822
1954
  }, [available, narrationKey, registerNarration]);
1823
1955
  const active = snapshot.queue[snapshot.index];
1824
1956
  const matching = !!active && trackKey(active) === trackKey(track);
1825
- const clock = (0, import_react2.useRef)({ snapshot, received: 0 });
1957
+ const clock = (0, import_react2.useRef)({ snapshot, received: 0, lastPosition: -1, lastStatus: "" });
1826
1958
  (0, import_react2.useEffect)(() => {
1827
- clock.current = { snapshot, received: performance.now() };
1959
+ const prev = clock.current;
1960
+ const changed = snapshot.position !== prev.lastPosition || snapshot.status !== prev.lastStatus;
1961
+ clock.current = {
1962
+ snapshot,
1963
+ received: changed ? performance.now() : prev.received,
1964
+ lastPosition: snapshot.position,
1965
+ lastStatus: snapshot.status
1966
+ };
1828
1967
  }, [snapshot]);
1829
1968
  (0, import_react2.useEffect)(() => {
1830
1969
  if (!narration || !matching || !highlightEnabled || !supported || snapshot.hidden) return;
@@ -1832,9 +1971,13 @@ function useArticleNarration(track, narration) {
1832
1971
  let highlighter = null;
1833
1972
  let frame = 0;
1834
1973
  const render = () => {
1835
- const { snapshot: current, received } = clock.current;
1836
- const elapsed = current.status === "playing" ? Math.min((performance.now() - received) / 1e3, 0.5) * current.rate : 0;
1837
- highlighter?.update((current.position + elapsed) * 1e3);
1974
+ if (!remote && getPosition) {
1975
+ highlighter?.update(getPosition() * 1e3);
1976
+ } else {
1977
+ const { snapshot: current, received } = clock.current;
1978
+ const elapsed = current.status === "playing" ? Math.min((performance.now() - received) / 1e3, 0.5) * current.rate : 0;
1979
+ highlighter?.update((current.position + elapsed) * 1e3);
1980
+ }
1838
1981
  frame = requestAnimationFrame(render);
1839
1982
  };
1840
1983
  const visibility = () => {
package/dist/audio.mjs CHANGED
@@ -99,6 +99,131 @@ function wordIndexAt(words, timeMs) {
99
99
  }
100
100
  return ans;
101
101
  }
102
+ var UNSTRESSED_FUNCTION_WORDS = /* @__PURE__ */ new Set([
103
+ "a",
104
+ "an",
105
+ "the",
106
+ "of",
107
+ "to",
108
+ "in",
109
+ "on",
110
+ "at",
111
+ "for",
112
+ "and",
113
+ "or",
114
+ "by",
115
+ "as",
116
+ "is",
117
+ "was",
118
+ "were",
119
+ "be",
120
+ "are",
121
+ "with",
122
+ "from",
123
+ "that",
124
+ "this"
125
+ ]);
126
+ var DASH_TOKENS = /* @__PURE__ */ new Set(["\u2014", "\u2013", "--"]);
127
+ function isClauseEnd(sent, i) {
128
+ const n = sent.length;
129
+ if (i === n - 1) return true;
130
+ const stripped = sent[i][0].replace(/["'\u201d\u2019)\]}]+$/u, "");
131
+ if (DASH_TOKENS.has(stripped)) return true;
132
+ if (/[,;:\u2014\u2013]$/u.test(stripped)) {
133
+ if (i + 1 < n && DASH_TOKENS.has(sent[i + 1][0])) return false;
134
+ if (i + 2 < n && DASH_TOKENS.has(sent[i + 2][0])) return false;
135
+ return true;
136
+ }
137
+ return false;
138
+ }
139
+ function rebalanceLegacySentence(sent) {
140
+ const n = sent.length;
141
+ const sStart = sent[0][1];
142
+ const sEnd = sent[n - 1][2];
143
+ const sDur = sEnd - sStart;
144
+ if (n <= 1 || sDur < 600) return sent;
145
+ const clauses = [];
146
+ let startIdx = 0;
147
+ for (let i = 0; i < n; i++) {
148
+ if (isClauseEnd(sent, i)) {
149
+ clauses.push([startIdx, i]);
150
+ startIdx = i + 1;
151
+ }
152
+ }
153
+ const clauseBounds = clauses.map(([i0, i1]) => [sent[i0][1], sent[i1][2]]);
154
+ if (clauses.length >= 2) {
155
+ const [, i1] = clauses[0];
156
+ if (DASH_TOKENS.has(sent[i1][0]) && i1 <= 5) {
157
+ const c0Dur = clauseBounds[0][1] - clauseBounds[0][0];
158
+ const shift = Math.min(450, c0Dur * 0.24);
159
+ clauseBounds[0][1] -= shift;
160
+ clauseBounds[1][0] -= shift;
161
+ }
162
+ }
163
+ const out = [];
164
+ for (let c = 0; c < clauses.length; c++) {
165
+ const [i0, i1] = clauses[c];
166
+ const [cStart, cEnd] = clauseBounds[c];
167
+ const cDur = cEnd - cStart;
168
+ const cLen = i1 - i0 + 1;
169
+ const pauseMs = cLen >= 2 && cDur > 450 ? Math.min(340, cDur * 0.24) : cDur > 300 ? Math.min(180, cDur * 0.18) : 0;
170
+ const speechDur = Math.max(cDur - pauseMs, cDur * 0.72);
171
+ const weights = [];
172
+ for (let idx = i0; idx <= i1; idx++) {
173
+ const [w, st, en] = sent[idx];
174
+ const oldD = Math.max(en - st, 40);
175
+ const stripped = w.replace(/["'\u201d\u2019)\]}]+$/u, "");
176
+ const clean = stripped.replace(/^["'\u201c\u2018([{]+/u, "").replace(/[.,;:!?\u2014\u2013-]+$/u, "").toLowerCase();
177
+ if (DASH_TOKENS.has(w)) {
178
+ weights.push(30);
179
+ } else {
180
+ let weight = Math.pow(oldD, 0.85);
181
+ if (UNSTRESSED_FUNCTION_WORDS.has(clean) && stripped.toLowerCase() === clean) {
182
+ weight *= 0.58;
183
+ }
184
+ weights.push(weight);
185
+ }
186
+ }
187
+ const totW = weights.reduce((a, b) => a + b, 0) || 1;
188
+ let cur = cStart;
189
+ for (let k = 0; k < cLen; k++) {
190
+ const idx = i0 + k;
191
+ const [w, , , si] = sent[idx];
192
+ const wDur = speechDur * (weights[k] / totW);
193
+ const lead = idx > 0 ? Math.min(45, wDur * 0.22) : 0;
194
+ const wSt = Math.max(sStart, cur - lead);
195
+ const wEn = cur + wDur;
196
+ out.push([w, Math.round(wSt), Math.round(Math.max(wSt, wEn)), si]);
197
+ cur = wEn;
198
+ }
199
+ }
200
+ return out;
201
+ }
202
+ function rebalanceSentenceTimings(words) {
203
+ if (words.length <= 1) return words;
204
+ const out = [];
205
+ let i = 0;
206
+ while (i < words.length) {
207
+ let j = i + 1;
208
+ const sIdx = words[i][3];
209
+ while (j < words.length && words[j][3] === sIdx) j++;
210
+ const sent = words.slice(i, j);
211
+ let hasExplicitGaps = false;
212
+ for (let k = 0; k < sent.length - 1; k++) {
213
+ if (sent[k + 1][1] - sent[k][2] >= 25) {
214
+ hasExplicitGaps = true;
215
+ break;
216
+ }
217
+ }
218
+ if (!hasExplicitGaps && j < words.length && words[j][1] - sent[sent.length - 1][2] >= 25) {
219
+ hasExplicitGaps = true;
220
+ }
221
+ const processed = hasExplicitGaps ? sent : rebalanceLegacySentence(sent);
222
+ for (const row of processed) out.push(row);
223
+ i = j;
224
+ }
225
+ return out;
226
+ }
102
227
  function mergeLineBoxes(rects) {
103
228
  const lines = [];
104
229
  const sorted = rects.filter((r) => r.width > 0 && r.height > 0).sort((a, b) => a.top - b.top || a.left - b.left);
@@ -143,7 +268,7 @@ var NarrationHighlighter = class {
143
268
  this.resizeObserver = null;
144
269
  this.onWindowResize = null;
145
270
  this.root = root;
146
- this.words = timings.words;
271
+ this.words = rebalanceSentenceTimings(timings.words);
147
272
  const domWords = collectDomWords(root);
148
273
  const matches = alignWords(
149
274
  this.words.map((w) => normalizeWord(w[0])),
@@ -901,6 +1026,12 @@ var NetworkAudioController = class {
901
1026
  this.resumePosition = null;
902
1027
  this.candidates = [];
903
1028
  this.getSnapshot = () => this.snapshot;
1029
+ this.getPosition = () => {
1030
+ if (this.audio && this.source && this.resumePosition === null && finite(this.audio.currentTime)) {
1031
+ if (this.audio.currentTime > 0 || this.snapshot.position === 0) return this.audio.currentTime;
1032
+ }
1033
+ return this.snapshot.position;
1034
+ };
904
1035
  this.subscribe = (listener) => {
905
1036
  this.listeners.add(listener);
906
1037
  return () => {
@@ -1726,6 +1857,7 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1726
1857
  notice,
1727
1858
  command,
1728
1859
  openNetworkPlayer: connection ? openNetworkPlayer : void 0,
1860
+ getPosition: remoteSnapshot !== null ? void 0 : controller.getPosition,
1729
1861
  highlightAvailable,
1730
1862
  highlightEnabled,
1731
1863
  setHighlightEnabled,
@@ -1791,7 +1923,7 @@ function NetworkMediaSession() {
1791
1923
  var subscribeCapabilities = () => () => {
1792
1924
  };
1793
1925
  function useArticleNarration(track, narration) {
1794
- const { snapshot, highlightEnabled, setHighlightEnabled } = useNetworkAudio();
1926
+ const { snapshot, remote, getPosition, highlightEnabled, setHighlightEnabled } = useNetworkAudio();
1795
1927
  const supported = useSyncExternalStore2(subscribeCapabilities, narrationHighlightSupported, () => false);
1796
1928
  const registerNarration = useContext(NarrationRegistration);
1797
1929
  const narrationKey = trackKey(track);
@@ -1801,9 +1933,16 @@ function useArticleNarration(track, narration) {
1801
1933
  }, [available, narrationKey, registerNarration]);
1802
1934
  const active = snapshot.queue[snapshot.index];
1803
1935
  const matching = !!active && trackKey(active) === trackKey(track);
1804
- const clock = useRef2({ snapshot, received: 0 });
1936
+ const clock = useRef2({ snapshot, received: 0, lastPosition: -1, lastStatus: "" });
1805
1937
  useEffect2(() => {
1806
- clock.current = { snapshot, received: performance.now() };
1938
+ const prev = clock.current;
1939
+ const changed = snapshot.position !== prev.lastPosition || snapshot.status !== prev.lastStatus;
1940
+ clock.current = {
1941
+ snapshot,
1942
+ received: changed ? performance.now() : prev.received,
1943
+ lastPosition: snapshot.position,
1944
+ lastStatus: snapshot.status
1945
+ };
1807
1946
  }, [snapshot]);
1808
1947
  useEffect2(() => {
1809
1948
  if (!narration || !matching || !highlightEnabled || !supported || snapshot.hidden) return;
@@ -1811,9 +1950,13 @@ function useArticleNarration(track, narration) {
1811
1950
  let highlighter = null;
1812
1951
  let frame = 0;
1813
1952
  const render = () => {
1814
- const { snapshot: current, received } = clock.current;
1815
- const elapsed = current.status === "playing" ? Math.min((performance.now() - received) / 1e3, 0.5) * current.rate : 0;
1816
- highlighter?.update((current.position + elapsed) * 1e3);
1953
+ if (!remote && getPosition) {
1954
+ highlighter?.update(getPosition() * 1e3);
1955
+ } else {
1956
+ const { snapshot: current, received } = clock.current;
1957
+ const elapsed = current.status === "playing" ? Math.min((performance.now() - received) / 1e3, 0.5) * current.rate : 0;
1958
+ highlighter?.update((current.position + elapsed) * 1e3);
1959
+ }
1817
1960
  frame = requestAnimationFrame(render);
1818
1961
  };
1819
1962
  const visibility = () => {
@@ -316,7 +316,7 @@ interface AuthRoutesConfig {
316
316
  email: string;
317
317
  }) => void | Promise<void>;
318
318
  }
319
- type RouteHandler$2 = (request: Request, context: {
319
+ type RouteHandler$3 = (request: Request, context: {
320
320
  params: Promise<{
321
321
  scalemule?: string[];
322
322
  }>;
@@ -349,11 +349,11 @@ type RouteHandler$2 = (request: Request, context: {
349
349
  * - POST /api/auth/verify-email - Verify email
350
350
  */
351
351
  declare function createAuthRoutes(config?: AuthRoutesConfig): {
352
- GET: RouteHandler$2;
353
- POST: RouteHandler$2;
354
- DELETE: RouteHandler$2;
355
- PATCH: RouteHandler$2;
356
- PUT: RouteHandler$2;
352
+ GET: RouteHandler$3;
353
+ POST: RouteHandler$3;
354
+ DELETE: RouteHandler$3;
355
+ PATCH: RouteHandler$3;
356
+ PUT: RouteHandler$3;
357
357
  };
358
358
  interface AnalyticsTrackingGateConfig {
359
359
  /** Feature flag key used to decide whether to forward analytics */
@@ -432,7 +432,7 @@ interface AnalyticsRoutesConfig {
432
432
  * ```
433
433
  */
434
434
  declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
435
- POST: RouteHandler$2;
435
+ POST: RouteHandler$3;
436
436
  };
437
437
 
438
438
  /**
@@ -460,16 +460,16 @@ interface PushRoutesConfig {
460
460
  /** Enable CSRF validation on POST/PUT/DELETE (default: true) */
461
461
  csrf?: boolean;
462
462
  }
463
- type RouteHandler$1 = (request: Request, context: {
463
+ type RouteHandler$2 = (request: Request, context: {
464
464
  params: Promise<{
465
465
  action?: string[];
466
466
  }>;
467
467
  }) => Promise<Response>;
468
468
  declare function createPushRoutes(config: PushRoutesConfig): {
469
- GET: RouteHandler$1;
470
- POST: RouteHandler$1;
471
- PUT: RouteHandler$1;
472
- DELETE: RouteHandler$1;
469
+ GET: RouteHandler$2;
470
+ POST: RouteHandler$2;
471
+ PUT: RouteHandler$2;
472
+ DELETE: RouteHandler$2;
473
473
  };
474
474
 
475
475
  /**
@@ -495,15 +495,78 @@ interface NotificationRoutesConfig {
495
495
  /** Gateway URL (e.g., https://api.scalemule.com) */
496
496
  gatewayUrl: string;
497
497
  }
498
- type RouteHandler = (request: Request, context: {
498
+ type RouteHandler$1 = (request: Request, context: {
499
499
  params: Promise<{
500
500
  action?: string[];
501
501
  }>;
502
502
  }) => Promise<Response>;
503
503
  declare function createNotificationRoutes(config: NotificationRoutesConfig): {
504
+ GET: RouteHandler$1;
505
+ PATCH: RouteHandler$1;
506
+ DELETE: RouteHandler$1;
507
+ };
508
+
509
+ /**
510
+ * Newsletter Proxy Routes
511
+ *
512
+ * Drop-in App Router handlers that forward newsletter sign-ups, confirmations,
513
+ * unsubscribes and preference changes to scalemule-newsletters with the
514
+ * READER's evidence (IP, browser, device fingerprint, referrer) and session,
515
+ * so the consent ledger records the person who subscribed, not your server.
516
+ * Your secret API key never reaches the browser.
517
+ *
518
+ * @example
519
+ * ```ts
520
+ * // app/api/newsletters/[...action]/route.ts
521
+ * import { createNewsletterRoutes } from '@scalemule/nextjs/server'
522
+ *
523
+ * export const { GET, POST, PUT } = createNewsletterRoutes({
524
+ * apiKey: process.env.SCALEMULE_API_KEY!,
525
+ * gatewayUrl: process.env.SCALEMULE_API_URL!,
526
+ * // The header your load balancer/CDN sets with the real client IP:
527
+ * // ScaleMule Hosting (AWS ALB straight to the app) → 'x-forwarded-for'
528
+ * // (last hop); Cloudflare → 'cf-connecting-ip'; Vercel → 'x-vercel-forwarded-for'.
529
+ * clientContext: { trustedIpHeader: 'x-forwarded-for' },
530
+ * })
531
+ * ```
532
+ *
533
+ * Browser calls then go to `/api/newsletters/lists/{slug}/subscriptions`,
534
+ * `/api/newsletters/subscriptions/confirm`, `/api/newsletters/unsubscribe`,
535
+ * `/api/newsletters/preferences?token=…` and `/api/newsletters/me/subscriptions`.
536
+ */
537
+
538
+ interface NewsletterRoutesConfig {
539
+ /** Server-side secret API key */
540
+ apiKey: string;
541
+ /** Gateway URL (e.g., https://api.scalemule.com) */
542
+ gatewayUrl: string;
543
+ /**
544
+ * Required: which header your proxy/CDN sets with the reader's IP. Without
545
+ * it a caller could put any IP into the consent record (and dodge per-IP
546
+ * limits), because client-supplied forwarding headers would be trusted.
547
+ */
548
+ clientContext: ClientContextOptions & {
549
+ trustedIpHeader: NonNullable<ClientContextOptions['trustedIpHeader']>;
550
+ };
551
+ /**
552
+ * Reject state-changing requests whose Origin is another site (default
553
+ * true). Sign-ups must come from your own pages.
554
+ */
555
+ requireSameOrigin?: boolean;
556
+ /** Extra origins allowed to write (e.g. `https://www.example.com`). */
557
+ allowedOrigins?: string[];
558
+ }
559
+ type RouteHandler = (request: Request, context: {
560
+ params: Promise<{
561
+ action?: string[];
562
+ }>;
563
+ }) => Promise<Response>;
564
+ /** The gateway sub-path for an allowed (method, action) pair, or null. */
565
+ declare function newsletterRoute(method: string, action: string[]): string | null;
566
+ declare function createNewsletterRoutes(config: NewsletterRoutesConfig): {
504
567
  GET: RouteHandler;
505
- PATCH: RouteHandler;
506
- DELETE: RouteHandler;
568
+ POST: RouteHandler;
569
+ PUT: RouteHandler;
507
570
  };
508
571
 
509
572
  /**
@@ -1300,4 +1363,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
1300
1363
  */
1301
1364
  declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
1302
1365
 
1303
- export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, KNOWN_ACCOUNTS_COOKIE_NAME, type KnownAccountEntry, type MySqlBundle, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, SESSION_COOKIE_NAME, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, type SessionCookieOptions, type SessionData, type SmtpBundle, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };
1366
+ export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, KNOWN_ACCOUNTS_COOKIE_NAME, type KnownAccountEntry, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, SESSION_COOKIE_NAME, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, type SessionCookieOptions, type SessionData, type SmtpBundle, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };
@@ -316,7 +316,7 @@ interface AuthRoutesConfig {
316
316
  email: string;
317
317
  }) => void | Promise<void>;
318
318
  }
319
- type RouteHandler$2 = (request: Request, context: {
319
+ type RouteHandler$3 = (request: Request, context: {
320
320
  params: Promise<{
321
321
  scalemule?: string[];
322
322
  }>;
@@ -349,11 +349,11 @@ type RouteHandler$2 = (request: Request, context: {
349
349
  * - POST /api/auth/verify-email - Verify email
350
350
  */
351
351
  declare function createAuthRoutes(config?: AuthRoutesConfig): {
352
- GET: RouteHandler$2;
353
- POST: RouteHandler$2;
354
- DELETE: RouteHandler$2;
355
- PATCH: RouteHandler$2;
356
- PUT: RouteHandler$2;
352
+ GET: RouteHandler$3;
353
+ POST: RouteHandler$3;
354
+ DELETE: RouteHandler$3;
355
+ PATCH: RouteHandler$3;
356
+ PUT: RouteHandler$3;
357
357
  };
358
358
  interface AnalyticsTrackingGateConfig {
359
359
  /** Feature flag key used to decide whether to forward analytics */
@@ -432,7 +432,7 @@ interface AnalyticsRoutesConfig {
432
432
  * ```
433
433
  */
434
434
  declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
435
- POST: RouteHandler$2;
435
+ POST: RouteHandler$3;
436
436
  };
437
437
 
438
438
  /**
@@ -460,16 +460,16 @@ interface PushRoutesConfig {
460
460
  /** Enable CSRF validation on POST/PUT/DELETE (default: true) */
461
461
  csrf?: boolean;
462
462
  }
463
- type RouteHandler$1 = (request: Request, context: {
463
+ type RouteHandler$2 = (request: Request, context: {
464
464
  params: Promise<{
465
465
  action?: string[];
466
466
  }>;
467
467
  }) => Promise<Response>;
468
468
  declare function createPushRoutes(config: PushRoutesConfig): {
469
- GET: RouteHandler$1;
470
- POST: RouteHandler$1;
471
- PUT: RouteHandler$1;
472
- DELETE: RouteHandler$1;
469
+ GET: RouteHandler$2;
470
+ POST: RouteHandler$2;
471
+ PUT: RouteHandler$2;
472
+ DELETE: RouteHandler$2;
473
473
  };
474
474
 
475
475
  /**
@@ -495,15 +495,78 @@ interface NotificationRoutesConfig {
495
495
  /** Gateway URL (e.g., https://api.scalemule.com) */
496
496
  gatewayUrl: string;
497
497
  }
498
- type RouteHandler = (request: Request, context: {
498
+ type RouteHandler$1 = (request: Request, context: {
499
499
  params: Promise<{
500
500
  action?: string[];
501
501
  }>;
502
502
  }) => Promise<Response>;
503
503
  declare function createNotificationRoutes(config: NotificationRoutesConfig): {
504
+ GET: RouteHandler$1;
505
+ PATCH: RouteHandler$1;
506
+ DELETE: RouteHandler$1;
507
+ };
508
+
509
+ /**
510
+ * Newsletter Proxy Routes
511
+ *
512
+ * Drop-in App Router handlers that forward newsletter sign-ups, confirmations,
513
+ * unsubscribes and preference changes to scalemule-newsletters with the
514
+ * READER's evidence (IP, browser, device fingerprint, referrer) and session,
515
+ * so the consent ledger records the person who subscribed, not your server.
516
+ * Your secret API key never reaches the browser.
517
+ *
518
+ * @example
519
+ * ```ts
520
+ * // app/api/newsletters/[...action]/route.ts
521
+ * import { createNewsletterRoutes } from '@scalemule/nextjs/server'
522
+ *
523
+ * export const { GET, POST, PUT } = createNewsletterRoutes({
524
+ * apiKey: process.env.SCALEMULE_API_KEY!,
525
+ * gatewayUrl: process.env.SCALEMULE_API_URL!,
526
+ * // The header your load balancer/CDN sets with the real client IP:
527
+ * // ScaleMule Hosting (AWS ALB straight to the app) → 'x-forwarded-for'
528
+ * // (last hop); Cloudflare → 'cf-connecting-ip'; Vercel → 'x-vercel-forwarded-for'.
529
+ * clientContext: { trustedIpHeader: 'x-forwarded-for' },
530
+ * })
531
+ * ```
532
+ *
533
+ * Browser calls then go to `/api/newsletters/lists/{slug}/subscriptions`,
534
+ * `/api/newsletters/subscriptions/confirm`, `/api/newsletters/unsubscribe`,
535
+ * `/api/newsletters/preferences?token=…` and `/api/newsletters/me/subscriptions`.
536
+ */
537
+
538
+ interface NewsletterRoutesConfig {
539
+ /** Server-side secret API key */
540
+ apiKey: string;
541
+ /** Gateway URL (e.g., https://api.scalemule.com) */
542
+ gatewayUrl: string;
543
+ /**
544
+ * Required: which header your proxy/CDN sets with the reader's IP. Without
545
+ * it a caller could put any IP into the consent record (and dodge per-IP
546
+ * limits), because client-supplied forwarding headers would be trusted.
547
+ */
548
+ clientContext: ClientContextOptions & {
549
+ trustedIpHeader: NonNullable<ClientContextOptions['trustedIpHeader']>;
550
+ };
551
+ /**
552
+ * Reject state-changing requests whose Origin is another site (default
553
+ * true). Sign-ups must come from your own pages.
554
+ */
555
+ requireSameOrigin?: boolean;
556
+ /** Extra origins allowed to write (e.g. `https://www.example.com`). */
557
+ allowedOrigins?: string[];
558
+ }
559
+ type RouteHandler = (request: Request, context: {
560
+ params: Promise<{
561
+ action?: string[];
562
+ }>;
563
+ }) => Promise<Response>;
564
+ /** The gateway sub-path for an allowed (method, action) pair, or null. */
565
+ declare function newsletterRoute(method: string, action: string[]): string | null;
566
+ declare function createNewsletterRoutes(config: NewsletterRoutesConfig): {
504
567
  GET: RouteHandler;
505
- PATCH: RouteHandler;
506
- DELETE: RouteHandler;
568
+ POST: RouteHandler;
569
+ PUT: RouteHandler;
507
570
  };
508
571
 
509
572
  /**
@@ -1300,4 +1363,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
1300
1363
  */
1301
1364
  declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
1302
1365
 
1303
- export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, KNOWN_ACCOUNTS_COOKIE_NAME, type KnownAccountEntry, type MySqlBundle, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, SESSION_COOKIE_NAME, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, type SessionCookieOptions, type SessionData, type SmtpBundle, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };
1366
+ export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, KNOWN_ACCOUNTS_COOKIE_NAME, type KnownAccountEntry, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, SESSION_COOKIE_NAME, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, type SessionCookieOptions, type SessionData, type SmtpBundle, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };
@@ -2769,15 +2769,15 @@ function createPushRoutes(config) {
2769
2769
  }
2770
2770
  const contentType = response.headers.get("content-type") || "";
2771
2771
  if (contentType.includes("application/json")) {
2772
- const json = await response.json();
2772
+ const json2 = await response.json();
2773
2773
  if (response.ok) {
2774
- return new Response(JSON.stringify(json), {
2774
+ return new Response(JSON.stringify(json2), {
2775
2775
  status: response.status,
2776
2776
  headers: { "Content-Type": "application/json" }
2777
2777
  });
2778
2778
  } else {
2779
- const errMsg = json?.error?.message || json?.message || "Request failed";
2780
- const errCode = json?.error?.code || json?.code || "PUSH_ERROR";
2779
+ const errMsg = json2?.error?.message || json2?.message || "Request failed";
2780
+ const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
2781
2781
  return errorResponse2(errCode, errMsg, response.status);
2782
2782
  }
2783
2783
  }
@@ -2914,6 +2914,118 @@ function createNotificationRoutes(config) {
2914
2914
  return { GET, PATCH, DELETE };
2915
2915
  }
2916
2916
 
2917
+ // src/server/newsletters.ts
2918
+ var MAX_BODY_BYTES2 = 16 * 1024;
2919
+ var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
2920
+ function newsletterRoute(method, action) {
2921
+ const path = action.join("/");
2922
+ switch (method) {
2923
+ case "GET":
2924
+ return ["lists", "preferences", "me/subscriptions"].includes(path) ? path : null;
2925
+ case "PUT":
2926
+ return ["preferences", "me/subscriptions"].includes(path) ? path : null;
2927
+ case "POST":
2928
+ if (path === "subscriptions/confirm" || path === "unsubscribe") return path;
2929
+ if (action.length === 3 && action[0] === "lists" && action[2] === "subscriptions" && SLUG.test(action[1])) {
2930
+ return `lists/${action[1]}/subscriptions`;
2931
+ }
2932
+ return null;
2933
+ default:
2934
+ return null;
2935
+ }
2936
+ }
2937
+ async function readCapped(request, limit) {
2938
+ if (!request.body) return "";
2939
+ const reader = request.body.getReader();
2940
+ const chunks = [];
2941
+ let size = 0;
2942
+ for (; ; ) {
2943
+ const { done, value } = await reader.read();
2944
+ if (done) break;
2945
+ size += value.byteLength;
2946
+ if (size > limit) {
2947
+ await reader.cancel();
2948
+ return null;
2949
+ }
2950
+ chunks.push(value);
2951
+ }
2952
+ const all = new Uint8Array(size);
2953
+ let offset = 0;
2954
+ for (const c of chunks) {
2955
+ all.set(c, offset);
2956
+ offset += c.byteLength;
2957
+ }
2958
+ return new TextDecoder().decode(all);
2959
+ }
2960
+ function json(status, code, message) {
2961
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
2962
+ status,
2963
+ headers: { "Content-Type": "application/json" }
2964
+ });
2965
+ }
2966
+ function sameOrigin(request, allowedOrigins) {
2967
+ const origin = request.headers.get("origin");
2968
+ if (!origin) return true;
2969
+ if (allowedOrigins.includes(origin)) return true;
2970
+ let originHost;
2971
+ try {
2972
+ originHost = new URL(origin).host;
2973
+ } catch {
2974
+ return false;
2975
+ }
2976
+ const publicHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host") || new URL(request.url).host;
2977
+ return originHost === publicHost;
2978
+ }
2979
+ function createNewsletterRoutes(config) {
2980
+ const { apiKey, gatewayUrl } = config;
2981
+ if (!config.clientContext?.trustedIpHeader) {
2982
+ throw new Error("createNewsletterRoutes: clientContext.trustedIpHeader is required");
2983
+ }
2984
+ const requireSameOrigin = config.requireSameOrigin ?? true;
2985
+ async function forward(request, method, action) {
2986
+ const route = newsletterRoute(method, action);
2987
+ if (!route) return json(404, "NOT_FOUND", "Not found");
2988
+ if (method !== "GET" && requireSameOrigin && !sameOrigin(request, config.allowedOrigins ?? [])) {
2989
+ return json(403, "FORBIDDEN", "Cross-site newsletter requests are not allowed");
2990
+ }
2991
+ const headers3 = { "x-api-key": apiKey, "Content-Type": "application/json" };
2992
+ const session = getSessionFromRequest(request);
2993
+ if (session?.sessionToken) headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2994
+ Object.assign(
2995
+ headers3,
2996
+ buildClientContextHeaders(
2997
+ extractClientContext(request, config.clientContext)
2998
+ )
2999
+ );
3000
+ const init = { method, headers: headers3 };
3001
+ if (method !== "GET") {
3002
+ const declared = Number(request.headers.get("content-length") ?? "0");
3003
+ if (declared > MAX_BODY_BYTES2) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3004
+ const body = await readCapped(request, MAX_BODY_BYTES2);
3005
+ if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3006
+ if (body) init.body = body;
3007
+ }
3008
+ const search = new URL(request.url).search;
3009
+ let response;
3010
+ try {
3011
+ response = await fetch(`${gatewayUrl}/v1/newsletters/${route}${search}`, init);
3012
+ } catch {
3013
+ return json(502, "UPSTREAM_UNAVAILABLE", "The newsletter service is temporarily unavailable");
3014
+ }
3015
+ const out = { "Content-Type": "application/json", "Cache-Control": "no-store" };
3016
+ for (const h of ["x-request-id", "retry-after"]) {
3017
+ const v = response.headers.get(h);
3018
+ if (v) out[h] = v;
3019
+ }
3020
+ return new Response(await response.text(), { status: response.status, headers: out });
3021
+ }
3022
+ const handler = (method) => async (request, context) => {
3023
+ const params = await context.params;
3024
+ return forward(request, method, params.action ?? []);
3025
+ };
3026
+ return { GET: handler("GET"), POST: handler("POST"), PUT: handler("PUT") };
3027
+ }
3028
+
2917
3029
  // src/server/errors.ts
2918
3030
  var ScaleMuleError = class extends Error {
2919
3031
  constructor(code, message, status = 400, details, requestId) {
@@ -3622,6 +3734,7 @@ exports.createAnalyticsRoutes = createAnalyticsRoutes;
3622
3734
  exports.createAuthMiddleware = createAuthMiddleware;
3623
3735
  exports.createAuthRoutes = createAuthRoutes;
3624
3736
  exports.createLedveryRoutes = createLedveryRoutes;
3737
+ exports.createNewsletterRoutes = createNewsletterRoutes;
3625
3738
  exports.createNotificationRoutes = createNotificationRoutes;
3626
3739
  exports.createPushRoutes = createPushRoutes;
3627
3740
  exports.createServerClient = createServerClient;
@@ -3650,6 +3763,7 @@ exports.getSmtpBundle = getSmtpBundle;
3650
3763
  exports.invalidateBundleCache = invalidateBundleCache;
3651
3764
  exports.invalidateSecretCache = invalidateSecretCache;
3652
3765
  exports.isSafeRedirect = isSafeRedirect;
3766
+ exports.newsletterRoute = newsletterRoute;
3653
3767
  exports.normalizeKnownAccountsCookie = normalizeKnownAccountsCookie;
3654
3768
  exports.parseWebhookEvent = parseWebhookEvent;
3655
3769
  exports.prefetchBundles = prefetchBundles;
@@ -2767,15 +2767,15 @@ function createPushRoutes(config) {
2767
2767
  }
2768
2768
  const contentType = response.headers.get("content-type") || "";
2769
2769
  if (contentType.includes("application/json")) {
2770
- const json = await response.json();
2770
+ const json2 = await response.json();
2771
2771
  if (response.ok) {
2772
- return new Response(JSON.stringify(json), {
2772
+ return new Response(JSON.stringify(json2), {
2773
2773
  status: response.status,
2774
2774
  headers: { "Content-Type": "application/json" }
2775
2775
  });
2776
2776
  } else {
2777
- const errMsg = json?.error?.message || json?.message || "Request failed";
2778
- const errCode = json?.error?.code || json?.code || "PUSH_ERROR";
2777
+ const errMsg = json2?.error?.message || json2?.message || "Request failed";
2778
+ const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
2779
2779
  return errorResponse2(errCode, errMsg, response.status);
2780
2780
  }
2781
2781
  }
@@ -2912,6 +2912,118 @@ function createNotificationRoutes(config) {
2912
2912
  return { GET, PATCH, DELETE };
2913
2913
  }
2914
2914
 
2915
+ // src/server/newsletters.ts
2916
+ var MAX_BODY_BYTES2 = 16 * 1024;
2917
+ var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
2918
+ function newsletterRoute(method, action) {
2919
+ const path = action.join("/");
2920
+ switch (method) {
2921
+ case "GET":
2922
+ return ["lists", "preferences", "me/subscriptions"].includes(path) ? path : null;
2923
+ case "PUT":
2924
+ return ["preferences", "me/subscriptions"].includes(path) ? path : null;
2925
+ case "POST":
2926
+ if (path === "subscriptions/confirm" || path === "unsubscribe") return path;
2927
+ if (action.length === 3 && action[0] === "lists" && action[2] === "subscriptions" && SLUG.test(action[1])) {
2928
+ return `lists/${action[1]}/subscriptions`;
2929
+ }
2930
+ return null;
2931
+ default:
2932
+ return null;
2933
+ }
2934
+ }
2935
+ async function readCapped(request, limit) {
2936
+ if (!request.body) return "";
2937
+ const reader = request.body.getReader();
2938
+ const chunks = [];
2939
+ let size = 0;
2940
+ for (; ; ) {
2941
+ const { done, value } = await reader.read();
2942
+ if (done) break;
2943
+ size += value.byteLength;
2944
+ if (size > limit) {
2945
+ await reader.cancel();
2946
+ return null;
2947
+ }
2948
+ chunks.push(value);
2949
+ }
2950
+ const all = new Uint8Array(size);
2951
+ let offset = 0;
2952
+ for (const c of chunks) {
2953
+ all.set(c, offset);
2954
+ offset += c.byteLength;
2955
+ }
2956
+ return new TextDecoder().decode(all);
2957
+ }
2958
+ function json(status, code, message) {
2959
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
2960
+ status,
2961
+ headers: { "Content-Type": "application/json" }
2962
+ });
2963
+ }
2964
+ function sameOrigin(request, allowedOrigins) {
2965
+ const origin = request.headers.get("origin");
2966
+ if (!origin) return true;
2967
+ if (allowedOrigins.includes(origin)) return true;
2968
+ let originHost;
2969
+ try {
2970
+ originHost = new URL(origin).host;
2971
+ } catch {
2972
+ return false;
2973
+ }
2974
+ const publicHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host") || new URL(request.url).host;
2975
+ return originHost === publicHost;
2976
+ }
2977
+ function createNewsletterRoutes(config) {
2978
+ const { apiKey, gatewayUrl } = config;
2979
+ if (!config.clientContext?.trustedIpHeader) {
2980
+ throw new Error("createNewsletterRoutes: clientContext.trustedIpHeader is required");
2981
+ }
2982
+ const requireSameOrigin = config.requireSameOrigin ?? true;
2983
+ async function forward(request, method, action) {
2984
+ const route = newsletterRoute(method, action);
2985
+ if (!route) return json(404, "NOT_FOUND", "Not found");
2986
+ if (method !== "GET" && requireSameOrigin && !sameOrigin(request, config.allowedOrigins ?? [])) {
2987
+ return json(403, "FORBIDDEN", "Cross-site newsletter requests are not allowed");
2988
+ }
2989
+ const headers3 = { "x-api-key": apiKey, "Content-Type": "application/json" };
2990
+ const session = getSessionFromRequest(request);
2991
+ if (session?.sessionToken) headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2992
+ Object.assign(
2993
+ headers3,
2994
+ buildClientContextHeaders(
2995
+ extractClientContext(request, config.clientContext)
2996
+ )
2997
+ );
2998
+ const init = { method, headers: headers3 };
2999
+ if (method !== "GET") {
3000
+ const declared = Number(request.headers.get("content-length") ?? "0");
3001
+ if (declared > MAX_BODY_BYTES2) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3002
+ const body = await readCapped(request, MAX_BODY_BYTES2);
3003
+ if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3004
+ if (body) init.body = body;
3005
+ }
3006
+ const search = new URL(request.url).search;
3007
+ let response;
3008
+ try {
3009
+ response = await fetch(`${gatewayUrl}/v1/newsletters/${route}${search}`, init);
3010
+ } catch {
3011
+ return json(502, "UPSTREAM_UNAVAILABLE", "The newsletter service is temporarily unavailable");
3012
+ }
3013
+ const out = { "Content-Type": "application/json", "Cache-Control": "no-store" };
3014
+ for (const h of ["x-request-id", "retry-after"]) {
3015
+ const v = response.headers.get(h);
3016
+ if (v) out[h] = v;
3017
+ }
3018
+ return new Response(await response.text(), { status: response.status, headers: out });
3019
+ }
3020
+ const handler = (method) => async (request, context) => {
3021
+ const params = await context.params;
3022
+ return forward(request, method, params.action ?? []);
3023
+ };
3024
+ return { GET: handler("GET"), POST: handler("POST"), PUT: handler("PUT") };
3025
+ }
3026
+
2915
3027
  // src/server/errors.ts
2916
3028
  var ScaleMuleError = class extends Error {
2917
3029
  constructor(code, message, status = 400, details, requestId) {
@@ -3592,4 +3704,4 @@ function buildSecurityHeaders(opts = {}) {
3592
3704
  return headers3;
3593
3705
  }
3594
3706
 
3595
- export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };
3707
+ export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/nextjs",
3
- "version": "0.1.67",
3
+ "version": "0.1.69",
4
4
  "description": "ScaleMule SDK for Next.js applications - authentication, storage, and user management",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",