@neon-pixels/netlify-functions 0.0.0-stage → 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neon Pixels Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # @neon-pixels/netlify-functions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Helpers for scheduled and background Netlify functions, which run outside the server runtime: each one loads its own environment, starts and flushes error reporting, and can report to a Sentry cron monitor. Functions use the current Netlify handler form, `(request, context) => Response`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @neon-pixels/netlify-functions @dotenvx/dotenvx @sentry/node
9
+ ```
10
+
11
+ `@dotenvx/dotenvx` and `@sentry/node` are peer dependencies, so your app controls their versions. The package does not import `@neon-pixels/sentry`; the scrubber and environment name are arguments.
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import {
17
+ runInBatches,
18
+ scheduledFunction,
19
+ } from "@neon-pixels/netlify-functions";
20
+
21
+ export default scheduledFunction(
22
+ {
23
+ name: "purge-expired",
24
+ environment: (deployContext) =>
25
+ deployContext === "production" ? "production" : "preview",
26
+ beforeSend: scrubEvent,
27
+ tracesSampleRate: 0.1,
28
+ monitor: {
29
+ slug: "purge-expired",
30
+ schedule: "0 3 * * *",
31
+ checkinMargin: 5,
32
+ maxRuntime: 5,
33
+ },
34
+ },
35
+ async () => {
36
+ const { processed, failures, hasMore } = await runInBatches({
37
+ loadBatch: (limit) => loadExpiredRows(limit),
38
+ handle: (row) => purgeRow(row),
39
+ batchSize: 100,
40
+ timeBudgetMs: 20_000,
41
+ });
42
+ // Item failures are returned, not reported. A non-2xx response records an error check-in.
43
+ return Response.json(
44
+ { processed, hasMore, failed: failures.length },
45
+ { status: failures.length > 0 ? 500 : 200 },
46
+ );
47
+ },
48
+ );
49
+
50
+ // Netlify reads the schedule from source, so keep it an inline literal.
51
+ export const config = { schedule: "0 3 * * *" };
52
+ ```
53
+
54
+ `scheduledFunction` runs, in order: resolve the deploy context, load env, start Sentry, run the job (inside the monitor when `monitor` is given), capture any error, flush, rethrow. The Sentry DSN is read from `SENTRY_DSN` after the env file is decrypted. The job receives `{ request, context, deployContext }`. Sentry starts after the env file is decrypted (the DSN normally lives there), so a failure to resolve the context or load env is rethrown and logged but not sent to Sentry.
55
+
56
+ ### API
57
+
58
+ - `resolveDeployContext(context)` reads `context.deploy.context` and returns `production`, `deploy-preview`, `branch-deploy`, or `dev`. It throws when the value is missing or unknown, because guessing could load the wrong env file.
59
+ - `loadFunctionEnv(deployContext)` decrypts `.env.production` (production) or `.env.dev` (everything else) with dotenvx in strict mode, once per instance. It throws when decryption fails. Bundle both files with the function (`included_files` in `netlify.toml`) and set the matching `DOTENV_PRIVATE_KEY_*` variables in the Functions scope.
60
+ - `initFunctionSentry({ dsn, environment, beforeSend, tracesSampleRate })` starts the Sentry Node SDK once and never throws. Without a DSN it logs once and does nothing.
61
+ - `flushFunctionSentry(timeoutMs = 2000)` waits for queued events and never throws. A timeout is logged.
62
+ - `withCronMonitor({ slug, schedule, checkinMargin, maxRuntime }, job)` sends an `in_progress` check-in, runs the job, then sends `ok` or `error`. A throw or a non-2xx response counts as `error`; the original response or error passes through. Without a DSN it runs the job with no check-ins. `schedule` is a crontab expression; the margin and runtime are in minutes.
63
+ - `runInBatches({ loadBatch, handle, batchSize, timeBudgetMs })` loads up to `batchSize` items at a time until `loadBatch` returns none or the budget is spent (checked between batches). It returns `{ processed, failures, hasMore }`. One failed item does not stop its batch; a batch with failures ends the run with `hasMore: true`, so make `loadBatch` skip items that failed or were already handled. Failures are not reported automatically, and an error thrown by `loadBatch` propagates without the partial counts.
@@ -0,0 +1,57 @@
1
+ import * as Sentry from "@sentry/node";
2
+ type BatchFailure<Item> = {
3
+ item: Item;
4
+ error: unknown;
5
+ };
6
+ type BatchResult<Item> = {
7
+ processed: number;
8
+ failures: BatchFailure<Item>[];
9
+ hasMore: boolean;
10
+ };
11
+ type RunInBatchesOptions<Item> = {
12
+ loadBatch: (limit: number) => Promise<Item[]>;
13
+ handle: (item: Item) => Promise<void>;
14
+ batchSize: number;
15
+ timeBudgetMs: number;
16
+ };
17
+ export declare function runInBatches<Item>(options: RunInBatchesOptions<Item>): Promise<BatchResult<Item>>;
18
+ type CronMonitorOptions = {
19
+ slug: string;
20
+ schedule: string;
21
+ checkinMargin: number;
22
+ maxRuntime: number;
23
+ };
24
+ export declare function withCronMonitor(options: CronMonitorOptions, job: () => Promise<Response>): Promise<Response>;
25
+ export declare const DEPLOY_CONTEXTS: readonly ["production", "deploy-preview", "branch-deploy", "dev"];
26
+ type DeployContext = (typeof DEPLOY_CONTEXTS)[number];
27
+ type NetlifyFunctionContext = {
28
+ deploy?: {
29
+ context?: string;
30
+ };
31
+ };
32
+ export declare function resolveDeployContext(context: NetlifyFunctionContext | undefined): DeployContext;
33
+ export declare function loadFunctionEnv(deployContext: DeployContext): void;
34
+ export declare const DEFAULT_FLUSH_TIMEOUT_MS = 2000;
35
+ type FunctionSentryOptions = {
36
+ dsn: string | undefined;
37
+ environment: string;
38
+ beforeSend?: NonNullable<Sentry.NodeOptions["beforeSend"]>;
39
+ tracesSampleRate?: number;
40
+ };
41
+ export declare function initFunctionSentry(options: FunctionSentryOptions): void;
42
+ export declare function flushFunctionSentry(timeoutMs?: number): Promise<void>;
43
+ type ScheduledFunctionOptions = {
44
+ name: string;
45
+ monitor?: CronMonitorOptions;
46
+ environment: (deployContext: DeployContext) => string;
47
+ beforeSend?: FunctionSentryOptions["beforeSend"];
48
+ tracesSampleRate?: number;
49
+ };
50
+ type ScheduledJobArguments = {
51
+ request: Request;
52
+ context: NetlifyFunctionContext;
53
+ deployContext: DeployContext;
54
+ };
55
+ type ScheduledJob = (jobArguments: ScheduledJobArguments) => Promise<Response>;
56
+ export declare function scheduledFunction(options: ScheduledFunctionOptions, job: ScheduledJob): (request: Request, context: NetlifyFunctionContext) => Promise<Response>;
57
+ export type { BatchFailure, BatchResult, CronMonitorOptions, DeployContext, FunctionSentryOptions, NetlifyFunctionContext, RunInBatchesOptions, ScheduledFunctionOptions, ScheduledJob, ScheduledJobArguments };
package/dist/index.js ADDED
@@ -0,0 +1,198 @@
1
+ import * as Sentry from "@sentry/node";
2
+ import dotenvx from "@dotenvx/dotenvx";
3
+ // src/batches.ts
4
+ async function handleItem(item, handle) {
5
+ try {
6
+ await handle(item);
7
+ return;
8
+ } catch (error) {
9
+ return {
10
+ item,
11
+ error
12
+ };
13
+ }
14
+ }
15
+ async function handleBatch(batch, handle) {
16
+ const failures = [];
17
+ for (const item of batch) {
18
+ const failure = await handleItem(item, handle);
19
+ if (failure) failures.push(failure);
20
+ }
21
+ return failures;
22
+ }
23
+ async function runInBatches(options) {
24
+ if (!Number.isInteger(options.batchSize) || options.batchSize < 1) throw new RangeError("runInBatches: batchSize must be a positive integer.");
25
+ if (!Number.isFinite(options.timeBudgetMs) || options.timeBudgetMs < 0) throw new RangeError("runInBatches: timeBudgetMs must be a non-negative number.");
26
+ const deadline = Date.now() + options.timeBudgetMs;
27
+ const result = {
28
+ processed: 0,
29
+ failures: [],
30
+ hasMore: false
31
+ };
32
+ while (Date.now() < deadline) {
33
+ const batch = await options.loadBatch(options.batchSize);
34
+ if (batch.length === 0) return result;
35
+ const failures = await handleBatch(batch, options.handle);
36
+ result.processed += batch.length - failures.length;
37
+ result.failures.push(...failures);
38
+ if (failures.length > 0) {
39
+ result.hasMore = true;
40
+ return result;
41
+ }
42
+ }
43
+ result.hasMore = true;
44
+ return result;
45
+ }
46
+ // src/cronMonitor.ts
47
+ function monitorConfig(options) {
48
+ return {
49
+ schedule: {
50
+ type: "crontab",
51
+ value: options.schedule
52
+ },
53
+ checkinMargin: options.checkinMargin,
54
+ maxRuntime: options.maxRuntime
55
+ };
56
+ }
57
+ function hasDsn() {
58
+ return Boolean(Sentry.getClient()?.getOptions().dsn);
59
+ }
60
+ function startCheckIn(options) {
61
+ return sendCheckInSafely(() => Sentry.captureCheckIn({
62
+ monitorSlug: options.slug,
63
+ status: "in_progress"
64
+ }, monitorConfig(options)));
65
+ }
66
+ function finishCheckIn(options, status, checkInId) {
67
+ sendCheckInSafely(() => {
68
+ if (checkInId) return Sentry.captureCheckIn({
69
+ monitorSlug: options.slug,
70
+ status,
71
+ checkInId
72
+ });
73
+ return Sentry.captureCheckIn({
74
+ monitorSlug: options.slug,
75
+ status
76
+ }, monitorConfig(options));
77
+ });
78
+ }
79
+ function sendCheckInSafely(send) {
80
+ try {
81
+ return send();
82
+ } catch (checkInError) {
83
+ console.error("Failed to send Sentry cron check-in", checkInError);
84
+ return;
85
+ }
86
+ }
87
+ async function withCronMonitor(options, job) {
88
+ if (!hasDsn()) return job();
89
+ const checkInId = startCheckIn(options);
90
+ let response;
91
+ try {
92
+ response = await job();
93
+ } catch (jobError) {
94
+ finishCheckIn(options, "error", checkInId);
95
+ throw jobError;
96
+ }
97
+ finishCheckIn(options, response.ok ? "ok" : "error", checkInId);
98
+ return response;
99
+ }
100
+ // src/deployContext.ts
101
+ const DEPLOY_CONTEXTS = [
102
+ "production",
103
+ "deploy-preview",
104
+ "branch-deploy",
105
+ "dev"
106
+ ];
107
+ function isDeployContext(value) {
108
+ return DEPLOY_CONTEXTS.includes(value);
109
+ }
110
+ function resolveDeployContext(context) {
111
+ const value = context?.deploy?.context;
112
+ if (!value) throw new Error("resolveDeployContext: the function context has no deploy context.");
113
+ if (!isDeployContext(value)) throw new Error(`resolveDeployContext: unknown deploy context "${value}".`);
114
+ return value;
115
+ }
116
+ // src/env.ts
117
+ const PRODUCTION_ENV_FILE = ".env.production";
118
+ const NON_PRODUCTION_ENV_FILE = ".env.dev";
119
+ let loaded = false;
120
+ function envFileForDeployContext(deployContext) {
121
+ if (deployContext === "production") return PRODUCTION_ENV_FILE;
122
+ return NON_PRODUCTION_ENV_FILE;
123
+ }
124
+ function loadFunctionEnv(deployContext) {
125
+ if (loaded) return;
126
+ dotenvx.config({
127
+ path: envFileForDeployContext(deployContext),
128
+ strict: true
129
+ });
130
+ loaded = true;
131
+ }
132
+ // src/sentry.ts
133
+ const DEFAULT_FLUSH_TIMEOUT_MS = 2e3;
134
+ let initialized = false;
135
+ function initFunctionSentry(options) {
136
+ if (initialized) return;
137
+ if (!options.dsn) {
138
+ initialized = true;
139
+ console.error("Sentry DSN is not set; error reporting is disabled for this instance.");
140
+ return;
141
+ }
142
+ try {
143
+ Sentry.init({
144
+ dsn: options.dsn,
145
+ environment: options.environment,
146
+ beforeSend: options.beforeSend,
147
+ tracesSampleRate: options.tracesSampleRate
148
+ });
149
+ initialized = true;
150
+ } catch (initError) {
151
+ console.error("Failed to initialize Sentry", initError);
152
+ }
153
+ }
154
+ async function flushFunctionSentry(timeoutMs = DEFAULT_FLUSH_TIMEOUT_MS) {
155
+ if (!Sentry.getClient()) return;
156
+ try {
157
+ if (!await Sentry.flush(timeoutMs)) console.error("Sentry flush timed out; queued events may have been dropped");
158
+ } catch (flushError) {
159
+ console.error("Failed to flush Sentry", flushError);
160
+ }
161
+ }
162
+ function captureFunctionError(error, functionName) {
163
+ try {
164
+ Sentry.captureException(error, { tags: { function: functionName } });
165
+ } catch (captureError) {
166
+ console.error("Failed to capture error in Sentry", captureError);
167
+ }
168
+ }
169
+ // src/scheduledFunction.ts
170
+ function runJob(options, job, jobArguments) {
171
+ if (!options.monitor) return job(jobArguments);
172
+ return withCronMonitor(options.monitor, () => job(jobArguments));
173
+ }
174
+ function scheduledFunction(options, job) {
175
+ return async (request, context) => {
176
+ try {
177
+ const deployContext = resolveDeployContext(context);
178
+ loadFunctionEnv(deployContext);
179
+ initFunctionSentry({
180
+ dsn: process.env.SENTRY_DSN,
181
+ environment: options.environment(deployContext),
182
+ beforeSend: options.beforeSend,
183
+ tracesSampleRate: options.tracesSampleRate
184
+ });
185
+ return await runJob(options, job, {
186
+ request,
187
+ context,
188
+ deployContext
189
+ });
190
+ } catch (error) {
191
+ captureFunctionError(error, options.name);
192
+ throw error;
193
+ } finally {
194
+ await flushFunctionSentry();
195
+ }
196
+ };
197
+ }
198
+ export { DEFAULT_FLUSH_TIMEOUT_MS, DEPLOY_CONTEXTS, flushFunctionSentry, initFunctionSentry, loadFunctionEnv, resolveDeployContext, runInBatches, scheduledFunction, withCronMonitor };
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@neon-pixels/netlify-functions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Helpers for scheduled Netlify functions: deploy context, dotenvx env loading, Sentry start and flush, cron monitor check-ins, and bounded batch runs.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/neonpixels-studio/packages.git",
10
+ "directory": "packages/netlify-functions"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": "^22.17.0 || ^24.0.0 || >=26.0.0"
27
+ },
28
+ "peerDependencies": {
29
+ "@dotenvx/dotenvx": "^1.25.0",
30
+ "@sentry/node": "^10.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@dotenvx/dotenvx": "^1.25.0",
34
+ "@sentry/node": "^10.0.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsdown",
38
+ "typecheck": "tsc --noEmit -p tsconfig.json"
39
+ }
6
40
  }