local-lite 0.2.5 → 1.0.0

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,431 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DevMailbox = void 0;
4
+ exports.loadNodemailer = loadNodemailer;
5
+ exports.resolveTransporter = resolveTransporter;
6
+ exports.renderReactEmail = renderReactEmail;
7
+ exports.hydrateAttachment = hydrateAttachment;
8
+ exports.buildMailOptions = buildMailOptions;
9
+ exports.createNodemailerHandler = createNodemailerHandler;
10
+ exports.createHttpEmailHandler = createHttpEmailHandler;
11
+ exports.createDevEmailHandler = createDevEmailHandler;
12
+ exports.createEmailHandler = createEmailHandler;
13
+ const dynamic_js_1 = require("../utils/dynamic.js");
14
+ /**
15
+ * In-memory Dev Mailbox for inspecting locally dispatched emails during development.
16
+ */
17
+ class DevMailbox {
18
+ static inbox = [];
19
+ static getInbox() {
20
+ return [...this.inbox];
21
+ }
22
+ static getLatest() {
23
+ return this.inbox[this.inbox.length - 1];
24
+ }
25
+ static clear() {
26
+ this.inbox = [];
27
+ }
28
+ static record(email) {
29
+ this.inbox.push(email);
30
+ }
31
+ }
32
+ exports.DevMailbox = DevMailbox;
33
+ /**
34
+ * Dynamically loads the nodemailer module if not already available.
35
+ */
36
+ async function loadNodemailer() {
37
+ try {
38
+ const mod = await import('nodemailer');
39
+ return mod.default || mod;
40
+ }
41
+ catch (err) {
42
+ throw new Error("The 'nodemailer' package is required to send emails via Nodemailer transport. Please install it via 'npm install nodemailer'.");
43
+ }
44
+ }
45
+ /**
46
+ * Resolves or instantiates a Nodemailer Transporter instance.
47
+ */
48
+ async function resolveTransporter(input, defaults) {
49
+ if (input && typeof input.sendMail === 'function') {
50
+ return input;
51
+ }
52
+ const nm = await loadNodemailer();
53
+ return nm.createTransport(input, defaults);
54
+ }
55
+ function interpolate(templateStr, data) {
56
+ return templateStr.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => {
57
+ const val = data[key];
58
+ return val !== undefined ? String(val) : '';
59
+ });
60
+ }
61
+ /**
62
+ * Renders a React element or JSX component into clean HTML and plaintext fallback.
63
+ */
64
+ async function renderReactEmail(element) {
65
+ if (!element)
66
+ return { html: '', text: '' };
67
+ const component = typeof element === 'function' ? element() : element;
68
+ // 1. Try @react-email/render if installed
69
+ try {
70
+ const reactEmail = await (0, dynamic_js_1.safeDynamicImport)('@react-email/render');
71
+ const render = reactEmail?.render || reactEmail?.default?.render;
72
+ if (typeof render === 'function') {
73
+ const html = await render(component);
74
+ const text = await render(component, { plainText: true });
75
+ return { html, text };
76
+ }
77
+ }
78
+ catch { }
79
+ // 2. Try react-dom/server
80
+ try {
81
+ const ReactDOMServer = await (0, dynamic_js_1.safeDynamicImport)('react-dom/server');
82
+ const renderToStaticMarkup = ReactDOMServer?.renderToStaticMarkup || ReactDOMServer?.default?.renderToStaticMarkup;
83
+ if (typeof renderToStaticMarkup === 'function') {
84
+ const html = renderToStaticMarkup(component);
85
+ const text = html.replace(/<[^>]*>/g, '').trim();
86
+ return { html, text };
87
+ }
88
+ }
89
+ catch { }
90
+ return { html: String(component), text: String(component) };
91
+ }
92
+ /**
93
+ * Hydrates an attachment from a mobile file:// URI or local file path if possible.
94
+ */
95
+ async function hydrateAttachment(att) {
96
+ const item = { filename: att.filename };
97
+ if (att.contentType)
98
+ item.contentType = att.contentType;
99
+ if (att.content !== undefined)
100
+ item.content = att.content;
101
+ if (att.url) {
102
+ const rawUrl = att.url;
103
+ if (rawUrl.startsWith('file://') ||
104
+ (!rawUrl.startsWith('http://') && !rawUrl.startsWith('https://') && !rawUrl.startsWith('data:'))) {
105
+ const filePath = rawUrl.startsWith('file://') ? rawUrl.slice(7) : rawUrl;
106
+ try {
107
+ const fs = await import('node:fs/promises');
108
+ const buffer = await fs.readFile(filePath);
109
+ item.content = buffer;
110
+ return item;
111
+ }
112
+ catch {
113
+ item.path = rawUrl;
114
+ return item;
115
+ }
116
+ }
117
+ item.path = rawUrl;
118
+ }
119
+ return item;
120
+ }
121
+ /**
122
+ * Maps an offline Local-Lite EmailPayload to standard email options.
123
+ */
124
+ function buildMailOptions(payload, options = {}) {
125
+ const mailOptions = {
126
+ ...options.defaults,
127
+ to: payload.to,
128
+ subject: payload.subject,
129
+ from: payload.from || options.defaultFrom || options.defaults?.from,
130
+ };
131
+ if (payload.text !== undefined)
132
+ mailOptions.text = payload.text;
133
+ if (payload.html !== undefined)
134
+ mailOptions.html = payload.html;
135
+ if (payload.cc !== undefined)
136
+ mailOptions.cc = payload.cc;
137
+ if (payload.bcc !== undefined)
138
+ mailOptions.bcc = payload.bcc;
139
+ if (payload.replyTo !== undefined)
140
+ mailOptions.replyTo = payload.replyTo;
141
+ if (payload.headers) {
142
+ mailOptions.headers = {
143
+ ...(typeof options.defaults?.headers === 'object' ? options.defaults.headers : {}),
144
+ ...payload.headers,
145
+ };
146
+ }
147
+ if (payload.attachments && payload.attachments.length > 0) {
148
+ const existingAttachments = Array.isArray(options.defaults?.attachments)
149
+ ? options.defaults.attachments
150
+ : [];
151
+ const convertedAttachments = payload.attachments.map((att) => {
152
+ const item = {
153
+ filename: att.filename,
154
+ };
155
+ if (att.contentType) {
156
+ item.contentType = att.contentType;
157
+ }
158
+ if (att.url) {
159
+ item.path = att.url;
160
+ }
161
+ if (att.content !== undefined) {
162
+ item.content = att.content;
163
+ }
164
+ return item;
165
+ });
166
+ mailOptions.attachments = [...existingAttachments, ...convertedAttachments];
167
+ }
168
+ return mailOptions;
169
+ }
170
+ async function prepareMailOptions(payload, options, record) {
171
+ let mailOptions = buildMailOptions(payload, options);
172
+ // 1. React Email / JSX rendering support
173
+ if (payload.react) {
174
+ const rendered = await renderReactEmail(payload.react);
175
+ mailOptions.html = rendered.html;
176
+ if (!mailOptions.text && rendered.text)
177
+ mailOptions.text = rendered.text;
178
+ }
179
+ // 2. Custom template rendering
180
+ if (options.renderTemplate && (payload.template || payload.templateData)) {
181
+ const rendered = await options.renderTemplate(payload.template, payload.templateData, payload);
182
+ if (rendered.html !== undefined)
183
+ mailOptions.html = rendered.html;
184
+ if (rendered.text !== undefined)
185
+ mailOptions.text = rendered.text;
186
+ }
187
+ else if (payload.templateData) {
188
+ if (typeof mailOptions.html === 'string') {
189
+ mailOptions.html = interpolate(mailOptions.html, payload.templateData);
190
+ }
191
+ if (typeof mailOptions.text === 'string') {
192
+ mailOptions.text = interpolate(mailOptions.text, payload.templateData);
193
+ }
194
+ }
195
+ // 3. Auto-hydrate attachments (mobile file:// URIs)
196
+ if (payload.attachments && payload.attachments.length > 0) {
197
+ const hydrated = await Promise.all(payload.attachments.map((a) => hydrateAttachment(a)));
198
+ mailOptions.attachments = hydrated;
199
+ }
200
+ if (options.beforeSend) {
201
+ const modified = await options.beforeSend(mailOptions, payload, record);
202
+ if (modified) {
203
+ mailOptions = modified;
204
+ }
205
+ }
206
+ if (!mailOptions.to) {
207
+ throw new Error("Recipient 'to' address is required to dispatch email.");
208
+ }
209
+ if (!mailOptions.from) {
210
+ throw new Error("Sender 'from' address is required to dispatch email. Provide 'from' in the email payload or set 'defaultFrom' in options.");
211
+ }
212
+ return mailOptions;
213
+ }
214
+ /**
215
+ * Creates an EmailHandler for local-lite ActionManager that sends emails
216
+ * directly via Nodemailer (SMTP, Sendmail, SES, etc.).
217
+ */
218
+ function createNodemailerHandler(transporterOrOptions, handlerOptions = {}) {
219
+ let cachedTransporter = transporterOrOptions && typeof transporterOrOptions.sendMail === 'function'
220
+ ? transporterOrOptions
221
+ : null;
222
+ const getTransporter = async () => {
223
+ if (!cachedTransporter) {
224
+ cachedTransporter = await resolveTransporter(transporterOrOptions, handlerOptions.defaults);
225
+ }
226
+ return cachedTransporter;
227
+ };
228
+ return async (payload, record, _context) => {
229
+ const transporter = await getTransporter();
230
+ const mailOptions = await prepareMailOptions(payload, handlerOptions, record);
231
+ const info = await transporter.sendMail(mailOptions);
232
+ if (handlerOptions.afterSend) {
233
+ await handlerOptions.afterSend(info, payload, record);
234
+ }
235
+ return {
236
+ messageId: info.messageId,
237
+ response: info.response,
238
+ accepted: info.accepted,
239
+ rejected: info.rejected,
240
+ };
241
+ };
242
+ }
243
+ /**
244
+ * Creates an EmailHandler for local-lite ActionManager that dispatches emails
245
+ * via HTTP APIs (e.g. Resend, SendGrid, Postmark, or custom webhooks/endpoints).
246
+ */
247
+ function createHttpEmailHandler(options) {
248
+ const fetchFn = options.fetch || globalThis.fetch;
249
+ if (!fetchFn) {
250
+ throw new Error('A global or configured fetch function is required for HTTP email dispatch.');
251
+ }
252
+ const provider = options.provider || 'http';
253
+ return async (payload, record, _context) => {
254
+ const mailOptions = await prepareMailOptions(payload, options, record);
255
+ let url;
256
+ let headers = {
257
+ 'Content-Type': 'application/json',
258
+ ...options.headers,
259
+ };
260
+ let body;
261
+ if (provider === 'resend') {
262
+ url = options.endpoint || 'https://api.resend.com/emails';
263
+ if (options.apiKey) {
264
+ headers['Authorization'] = `Bearer ${options.apiKey}`;
265
+ }
266
+ body = {
267
+ from: mailOptions.from,
268
+ to: mailOptions.to,
269
+ subject: mailOptions.subject,
270
+ html: mailOptions.html,
271
+ text: mailOptions.text,
272
+ cc: mailOptions.cc,
273
+ bcc: mailOptions.bcc,
274
+ reply_to: mailOptions.replyTo,
275
+ headers: mailOptions.headers,
276
+ attachments: mailOptions.attachments,
277
+ };
278
+ }
279
+ else if (provider === 'sendgrid') {
280
+ url = options.endpoint || 'https://api.sendgrid.com/v3/mail/send';
281
+ if (options.apiKey) {
282
+ headers['Authorization'] = `Bearer ${options.apiKey}`;
283
+ }
284
+ const toAddresses = Array.isArray(mailOptions.to) ? mailOptions.to : [mailOptions.to];
285
+ const personalizations = {
286
+ to: toAddresses.map((email) => (typeof email === 'string' ? { email } : email)),
287
+ };
288
+ if (mailOptions.cc) {
289
+ const ccAddresses = Array.isArray(mailOptions.cc) ? mailOptions.cc : [mailOptions.cc];
290
+ personalizations.cc = ccAddresses.map((email) => (typeof email === 'string' ? { email } : email));
291
+ }
292
+ if (mailOptions.bcc) {
293
+ const bccAddresses = Array.isArray(mailOptions.bcc) ? mailOptions.bcc : [mailOptions.bcc];
294
+ personalizations.bcc = bccAddresses.map((email) => (typeof email === 'string' ? { email } : email));
295
+ }
296
+ const content = [];
297
+ if (mailOptions.text)
298
+ content.push({ type: 'text/plain', value: String(mailOptions.text) });
299
+ if (mailOptions.html)
300
+ content.push({ type: 'text/html', value: String(mailOptions.html) });
301
+ body = {
302
+ personalizations: [personalizations],
303
+ from: typeof mailOptions.from === 'string' ? { email: mailOptions.from } : mailOptions.from,
304
+ subject: mailOptions.subject,
305
+ content: content.length > 0 ? content : [{ type: 'text/plain', value: '' }],
306
+ };
307
+ }
308
+ else if (provider === 'postmark') {
309
+ url = options.endpoint || 'https://api.postmarkapp.com/email';
310
+ if (options.apiKey) {
311
+ headers['X-Postmark-Server-Token'] = options.apiKey;
312
+ }
313
+ body = {
314
+ From: mailOptions.from,
315
+ To: Array.isArray(mailOptions.to) ? mailOptions.to.join(',') : mailOptions.to,
316
+ Subject: mailOptions.subject,
317
+ HtmlBody: mailOptions.html,
318
+ TextBody: mailOptions.text,
319
+ Cc: Array.isArray(mailOptions.cc) ? mailOptions.cc.join(',') : mailOptions.cc,
320
+ Bcc: Array.isArray(mailOptions.bcc) ? mailOptions.bcc.join(',') : mailOptions.bcc,
321
+ ReplyTo: mailOptions.replyTo,
322
+ };
323
+ }
324
+ else {
325
+ url = options.endpoint || '/api/email';
326
+ if (options.apiKey && !headers['Authorization']) {
327
+ headers['Authorization'] = `Bearer ${options.apiKey}`;
328
+ }
329
+ body = {
330
+ ...mailOptions,
331
+ attachments: mailOptions.attachments,
332
+ template: payload.template,
333
+ templateData: payload.templateData,
334
+ };
335
+ }
336
+ const response = await fetchFn(url, {
337
+ method: 'POST',
338
+ headers,
339
+ body: JSON.stringify(body),
340
+ });
341
+ if (!response.ok) {
342
+ let errorText = '';
343
+ try {
344
+ errorText = await response.text();
345
+ }
346
+ catch {
347
+ errorText = response.statusText;
348
+ }
349
+ throw new Error(`Email dispatch failed via HTTP (${response.status}): ${errorText}`);
350
+ }
351
+ let resultData = {};
352
+ try {
353
+ resultData = await response.json();
354
+ }
355
+ catch {
356
+ resultData = { ok: true, status: response.status };
357
+ }
358
+ const messageId = resultData.id ||
359
+ resultData.messageId ||
360
+ resultData.MessageID ||
361
+ response.headers.get('x-message-id') ||
362
+ `http-${record.id}`;
363
+ const sendResult = {
364
+ messageId,
365
+ response: resultData,
366
+ accepted: Array.isArray(mailOptions.to) ? mailOptions.to : [mailOptions.to],
367
+ };
368
+ if (options.afterSend) {
369
+ await options.afterSend(sendResult, payload, record);
370
+ }
371
+ return sendResult;
372
+ };
373
+ }
374
+ /**
375
+ * Creates a local dev email handler that stores outgoing emails in DevMailbox
376
+ * and logs an interactive terminal preview without sending real network requests.
377
+ */
378
+ function createDevEmailHandler(options = {}) {
379
+ return async (payload, record, _context) => {
380
+ const mailOptions = await prepareMailOptions(payload, options, record);
381
+ const sentRecord = {
382
+ id: `dev-${record.id}`,
383
+ sentAt: Date.now(),
384
+ mailOptions,
385
+ payload,
386
+ record,
387
+ };
388
+ DevMailbox.record(sentRecord);
389
+ if (!options.silent) {
390
+ const toStr = Array.isArray(mailOptions.to) ? mailOptions.to.join(', ') : mailOptions.to;
391
+ const previewText = (mailOptions.text || mailOptions.html || '').toString().slice(0, 120);
392
+ console.log(`[local-lite:email:dev] Dispatched to: ${toStr} | Subject: "${mailOptions.subject}" | Body: "${previewText}"`);
393
+ }
394
+ const result = {
395
+ messageId: sentRecord.id,
396
+ response: { dev: true, previewUrl: `dev://mailbox/${sentRecord.id}` },
397
+ accepted: Array.isArray(mailOptions.to) ? mailOptions.to : [mailOptions.to],
398
+ };
399
+ if (options.afterSend) {
400
+ await options.afterSend(result, payload, record);
401
+ }
402
+ return result;
403
+ };
404
+ }
405
+ /**
406
+ * Universal email handler factory that creates a dispatch handler
407
+ * supporting Nodemailer (SMTP, Sendmail), HTTP providers (Resend, SendGrid, Postmark),
408
+ * local dev mailbox, or custom webhooks.
409
+ */
410
+ function createEmailHandler(config) {
411
+ if (config.provider === 'dev' || config.provider === 'preview') {
412
+ return createDevEmailHandler({ ...config, silent: config.silentDev });
413
+ }
414
+ if (config.transport || config.provider === 'nodemailer') {
415
+ return createNodemailerHandler(config.transport || config, config);
416
+ }
417
+ if (config.provider === 'resend' ||
418
+ config.provider === 'sendgrid' ||
419
+ config.provider === 'postmark' ||
420
+ config.provider === 'http' ||
421
+ config.endpoint) {
422
+ return createHttpEmailHandler(config);
423
+ }
424
+ if (config.apiKey) {
425
+ return createHttpEmailHandler({
426
+ ...config,
427
+ provider: 'resend',
428
+ });
429
+ }
430
+ throw new Error("Invalid email configuration: Provide 'transport' (for Nodemailer/SMTP), 'provider' ('resend'|'sendgrid'|'postmark'|'dev'), or 'endpoint' (for HTTP delivery).");
431
+ }
@@ -0,0 +1,41 @@
1
+ import type { ApiEndpoint } from './index.js';
2
+ export interface EmailEndpointOptions {
3
+ /**
4
+ * Secret token required in `Authorization: Bearer <secret>` or `x-app-secret` header.
5
+ * If not set, incoming requests are processed without secret token validation.
6
+ */
7
+ secret?: string;
8
+ /**
9
+ * CORS allowed origins (e.g. '*' or 'https://myapp.com'). Default: '*'
10
+ */
11
+ corsOrigin?: string;
12
+ /**
13
+ * Direct Nodemailer transporter instance, SMTP options, or custom dispatcher function.
14
+ */
15
+ transport?: any;
16
+ /**
17
+ * HTTP email provider if relaying through an API (e.g. 'resend', 'sendgrid', 'postmark').
18
+ */
19
+ provider?: 'nodemailer' | 'resend' | 'sendgrid' | 'postmark' | 'dev';
20
+ /**
21
+ * API Key for provider if relaying.
22
+ */
23
+ apiKey?: string;
24
+ /**
25
+ * Custom dispatch function: receives the parsed email payload and returns { messageId, ... }.
26
+ */
27
+ dispatch?: (payload: any, request: Request) => Promise<any> | any;
28
+ /**
29
+ * Fallback 'from' address if not present in request payload.
30
+ */
31
+ defaultFrom?: string;
32
+ /**
33
+ * Hook called before dispatching to sanitize or validate payload.
34
+ */
35
+ beforeSend?: (payload: any, request: Request) => Promise<any | void> | any | void;
36
+ }
37
+ /**
38
+ * Creates a turnkey Request/Response API endpoint for receiving offline-enqueued emails
39
+ * from local-lite clients and dispatching them via Nodemailer or cloud providers.
40
+ */
41
+ export declare function createEmailEndpoint(options?: EmailEndpointOptions): ApiEndpoint;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createEmailEndpoint = createEmailEndpoint;
4
+ /**
5
+ * Creates a turnkey Request/Response API endpoint for receiving offline-enqueued emails
6
+ * from local-lite clients and dispatching them via Nodemailer or cloud providers.
7
+ */
8
+ function createEmailEndpoint(options = {}) {
9
+ const corsHeaders = {
10
+ 'Access-Control-Allow-Origin': options.corsOrigin || '*',
11
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
12
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-App-Secret, X-Message-ID',
13
+ };
14
+ const handlePost = async ({ request }) => {
15
+ // 1. Check secret token if configured
16
+ if (options.secret) {
17
+ const authHeader = request.headers.get('authorization') || request.headers.get('x-app-secret');
18
+ const expectedBearer = `Bearer ${options.secret}`;
19
+ if (authHeader !== expectedBearer && authHeader !== options.secret) {
20
+ return Response.json({ error: 'Unauthorized: Invalid email endpoint secret' }, { status: 401, headers: corsHeaders });
21
+ }
22
+ }
23
+ // 2. Parse payload
24
+ let payload;
25
+ try {
26
+ payload = await request.json();
27
+ }
28
+ catch {
29
+ return Response.json({ error: 'Bad Request: Invalid JSON payload' }, { status: 400, headers: corsHeaders });
30
+ }
31
+ if (!payload || !payload.to || !payload.subject) {
32
+ return Response.json({ error: "Bad Request: Fields 'to' and 'subject' are required." }, { status: 400, headers: corsHeaders });
33
+ }
34
+ if (!payload.from && options.defaultFrom) {
35
+ payload.from = options.defaultFrom;
36
+ }
37
+ if (options.beforeSend) {
38
+ const modified = await options.beforeSend(payload, request);
39
+ if (modified)
40
+ payload = modified;
41
+ }
42
+ // 3. Dispatch
43
+ try {
44
+ let result;
45
+ if (options.dispatch) {
46
+ result = await options.dispatch(payload, request);
47
+ }
48
+ else if (options.transport || (!options.provider && !options.apiKey)) {
49
+ const { createNodemailerHandler } = await import('../email/index.js');
50
+ const handler = createNodemailerHandler(options.transport || {}, {
51
+ defaultFrom: options.defaultFrom,
52
+ });
53
+ result = await handler(payload, { id: 'srv-' + Date.now() }, {});
54
+ }
55
+ else {
56
+ const { createHttpEmailHandler } = await import('../email/index.js');
57
+ const handler = createHttpEmailHandler({
58
+ provider: options.provider,
59
+ apiKey: options.apiKey,
60
+ defaultFrom: options.defaultFrom,
61
+ });
62
+ result = await handler(payload, { id: 'srv-' + Date.now() }, {});
63
+ }
64
+ const messageId = result?.messageId || result?.id || `msg-${Date.now()}`;
65
+ return Response.json({ ok: true, id: messageId, result }, { status: 200, headers: corsHeaders });
66
+ }
67
+ catch (err) {
68
+ const message = err instanceof Error ? err.message : String(err);
69
+ return Response.json({ error: 'Email dispatch failed: ' + message }, { status: 500, headers: corsHeaders });
70
+ }
71
+ };
72
+ const handleOptions = async () => {
73
+ return new Response(null, { status: 204, headers: corsHeaders });
74
+ };
75
+ return {
76
+ POST: handlePost,
77
+ OPTIONS: handleOptions,
78
+ };
79
+ }
@@ -1,4 +1,6 @@
1
1
  export type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
2
+ export * from './email.js';
3
+ export * from './sync.js';
2
4
  export interface ApiRequestContext<TConfig = unknown> {
3
5
  request: Request;
4
6
  config: TConfig;
@@ -1,7 +1,23 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
17
  exports.defineServerConfig = defineServerConfig;
4
18
  exports.createServer = createServer;
19
+ __exportStar(require("./email.js"), exports);
20
+ __exportStar(require("./sync.js"), exports);
5
21
  function normalizePath(path) {
6
22
  const normalized = `/${path.split('/').filter(Boolean).join('/')}`;
7
23
  return normalized === '/' ? normalized : normalized.replace(/\/$/, '');
@@ -0,0 +1,77 @@
1
+ import type { DeltaChanges, SyncOperation, SyncOp } from '../core/types.js';
2
+ import type { ApiEndpoint } from './index.js';
3
+ export interface ServerSyncRecord {
4
+ rowId: string;
5
+ tableName: string;
6
+ payload: Record<string, any>;
7
+ timestamp: number;
8
+ operation: SyncOp;
9
+ cursor: number;
10
+ }
11
+ export interface ServerSyncStorage {
12
+ /**
13
+ * Applies client mutations to the server store atomically using Last-Write-Wins.
14
+ */
15
+ applyOperations(operations: SyncOperation[], serverTime?: number): Promise<{
16
+ applied: number;
17
+ successfulIds: string[];
18
+ serverTime: number;
19
+ cursor: number;
20
+ }>;
21
+ /**
22
+ * Fetches delta changes across tables since a given cursor or timestamp.
23
+ */
24
+ getDeltas(tables: string[], since: number, limit?: number): Promise<{
25
+ changes: DeltaChanges;
26
+ cursor: number;
27
+ hasMore: boolean;
28
+ serverTime: number;
29
+ }>;
30
+ }
31
+ /**
32
+ * In-memory server sync storage.
33
+ * Ideal for development, testing, serverless functions, or lightweight microservices.
34
+ */
35
+ export declare class MemoryServerSyncStorage implements ServerSyncStorage {
36
+ private tables;
37
+ private changeLog;
38
+ private monotonicCursor;
39
+ applyOperations(operations: SyncOperation[], overrideTime?: number): Promise<{
40
+ applied: number;
41
+ successfulIds: string[];
42
+ serverTime: number;
43
+ cursor: number;
44
+ }>;
45
+ getDeltas(tables: string[], since: number, limit?: number): Promise<{
46
+ changes: DeltaChanges;
47
+ cursor: number;
48
+ hasMore: boolean;
49
+ serverTime: number;
50
+ }>;
51
+ /**
52
+ * Resets all in-memory tables and logs.
53
+ */
54
+ clear(): void;
55
+ }
56
+ export interface ServerSyncEndpointOptions {
57
+ /**
58
+ * Optional secret token expected in `Authorization: Bearer <token>` or `x-sync-secret`.
59
+ */
60
+ secret?: string;
61
+ /**
62
+ * Storage backend for server sync data. Default: MemoryServerSyncStorage instance.
63
+ */
64
+ storage?: ServerSyncStorage;
65
+ /**
66
+ * CORS allowed origin. Default: '*'
67
+ */
68
+ corsOrigin?: string;
69
+ /**
70
+ * Hook called before applying mutations to authorize or mutate incoming operations.
71
+ */
72
+ onBeforePush?: (operations: SyncOperation[], request: Request) => Promise<SyncOperation[] | void> | SyncOperation[] | void;
73
+ }
74
+ /**
75
+ * Creates turnkey push and pull API endpoints for self-hosted multi-device data synchronization.
76
+ */
77
+ export declare function createSyncEndpoint(options?: ServerSyncEndpointOptions): ApiEndpoint;