@koderlabs/tasks-sdk-nextjs 0.1.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,179 @@
1
+ PROPRIETARY SOFTWARE LICENSE — ALL RIGHTS RESERVED
2
+
3
+ Copyright (c) 2026 KoderLabs. All rights reserved.
4
+ Author: Jawaid Gadiwala <jawaidgadiwala@gmail.com>
5
+
6
+ ================================================================================
7
+ 1. NO LICENSE GRANTED BY DEFAULT
8
+ ================================================================================
9
+
10
+ This software, including all source code, object code, documentation,
11
+ configuration files, build artifacts, test fixtures, and any associated
12
+ materials (collectively, the "Software"), is the proprietary and confidential
13
+ property of KoderLabs.
14
+
15
+ NO license, right, title, interest, or permission of any kind — express,
16
+ implied, statutory, by estoppel, by exhaustion, by patent exhaustion, or by
17
+ any other legal theory — is granted to any person or entity by:
18
+
19
+ (a) viewing the Software on any registry, repository, mirror, CDN,
20
+ cache, or other distribution channel (including but not limited to
21
+ npmjs.com, GitHub, GitLab, or any private registry);
22
+ (b) downloading, cloning, or otherwise obtaining a copy of the Software;
23
+ (c) the act of the Software being technically accessible due to a registry
24
+ requirement, mirror, or third-party distribution;
25
+ (d) any prior course of dealing, custom, or industry practice.
26
+
27
+ The ability to access the Software does NOT imply any permission to use it.
28
+ A separate, signed, written license agreement executed by an authorised
29
+ representative of KoderLabs is the ONLY mechanism by which any rights may be
30
+ granted.
31
+
32
+ ================================================================================
33
+ 2. PROHIBITED ACTIVITIES (NON-EXHAUSTIVE)
34
+ ================================================================================
35
+
36
+ Without prior signed written permission from KoderLabs, the following are
37
+ expressly PROHIBITED and constitute infringement, breach of contract, and
38
+ unauthorised use:
39
+
40
+ (a) Copying the Software in whole or in part, in any medium;
41
+ (b) Modifying, adapting, translating, porting, or creating derivative works
42
+ of the Software;
43
+ (c) Distributing, republishing, mirroring, hosting, transmitting,
44
+ sublicensing, leasing, lending, renting, selling, offering for sale,
45
+ bartering, gifting, or otherwise transferring the Software or any
46
+ portion of it;
47
+ (d) Forking the Software's repository, whether on GitHub, GitLab, Bitbucket,
48
+ Codeberg, Sourcehut, or any other version-control hosting service;
49
+ (e) Reverse engineering, decompiling, disassembling, deobfuscating,
50
+ extracting source from compiled or minified artifacts, or attempting to
51
+ derive the source code, algorithms, or trade secrets;
52
+ (f) Removing, altering, or obscuring any copyright, trademark, license,
53
+ attribution, or proprietary notice;
54
+ (g) Using the Software, in whole or in part, to train, fine-tune,
55
+ evaluate, or benchmark any machine-learning model, embedding model, or
56
+ AI system;
57
+ (h) Using the Software to provide a hosted service, SaaS offering,
58
+ managed offering, or any form of public or commercial offering;
59
+ (i) Using the Software in any production, staging, development, evaluation,
60
+ or testing capacity, whether commercial or non-commercial;
61
+ (j) Bypassing, disabling, or attempting to circumvent any technical
62
+ protection measure (license check, telemetry, signature verification,
63
+ etc.) embedded in the Software;
64
+ (k) Combining or integrating the Software with any work licensed under a
65
+ copyleft licence (including but not limited to GPL, AGPL, LGPL, MPL,
66
+ EPL) in a manner that would purport to relicense the Software;
67
+ (l) Filing, prosecuting, or threatening patent litigation against KoderLabs
68
+ or its customers based on any feature, design, or behaviour of the
69
+ Software ("defensive termination" — any such action automatically and
70
+ immediately terminates any rights granted to the litigant elsewhere).
71
+
72
+ ================================================================================
73
+ 3. NO IMPLIED RIGHT TO INTERNAL USE
74
+ ================================================================================
75
+
76
+ The Software is NOT licensed for internal evaluation, internal production,
77
+ internal testing, or any other internal use unless and until a separate
78
+ written commercial licence is executed. Possession of a copy of the Software,
79
+ by whatever means, confers no right to execute, run, deploy, or use it.
80
+
81
+ ================================================================================
82
+ 4. NO PATENT, TRADEMARK, OR OTHER IP GRANT
83
+ ================================================================================
84
+
85
+ No patent licence, trademark licence, trade-secret disclosure, design-right
86
+ licence, or any other intellectual-property licence is granted under this
87
+ notice. KoderLabs retains all such rights.
88
+
89
+ ================================================================================
90
+ 5. CONFIDENTIALITY
91
+ ================================================================================
92
+
93
+ The Software contains trade secrets and confidential information of
94
+ KoderLabs. Any party in possession of the Software shall (a) treat it as
95
+ confidential, (b) take reasonable measures to prevent unauthorised access or
96
+ disclosure, and (c) not disclose, publish, or make available the Software or
97
+ any portion thereof to any third party.
98
+
99
+ ================================================================================
100
+ 6. AUTOMATIC TERMINATION
101
+ ================================================================================
102
+
103
+ Any rights that may exist under a separate written agreement terminate
104
+ AUTOMATICALLY AND IMMEDIATELY upon any breach of this notice, without notice
105
+ and without judicial action. Upon termination, the breaching party shall
106
+ immediately destroy all copies of the Software in its possession or control
107
+ and certify destruction in writing to KoderLabs.
108
+
109
+ ================================================================================
110
+ 7. NO WARRANTY
111
+ ================================================================================
112
+
113
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
114
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
115
+ FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ACCURACY, RELIABILITY,
116
+ TITLE, AVAILABILITY, OR THAT THE SOFTWARE WILL OPERATE UNINTERRUPTED OR
117
+ ERROR-FREE.
118
+
119
+ ================================================================================
120
+ 8. NO LIABILITY
121
+ ================================================================================
122
+
123
+ IN NO EVENT SHALL KODERLABS OR ITS AFFILIATES, OFFICERS, EMPLOYEES, AGENTS,
124
+ LICENSORS, OR CONTRIBUTORS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
125
+ LIABILITY (INCLUDING DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
126
+ CONSEQUENTIAL, PUNITIVE, LOST PROFITS, LOST DATA, OR BUSINESS INTERRUPTION),
127
+ WHETHER IN AN ACTION OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT
128
+ LIABILITY, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE
129
+ SOFTWARE OR THE USE OF OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF
130
+ THE POSSIBILITY OF SUCH DAMAGE. IN NO EVENT SHALL KODERLABS' TOTAL CUMULATIVE
131
+ LIABILITY EXCEED ONE U.S. DOLLAR (USD 1.00).
132
+
133
+ ================================================================================
134
+ 9. EQUITABLE RELIEF
135
+ ================================================================================
136
+
137
+ The parties acknowledge that any breach of this notice would cause
138
+ irreparable harm to KoderLabs for which monetary damages would be inadequate.
139
+ KoderLabs is therefore entitled, in addition to all other remedies available
140
+ at law, to specific performance and injunctive relief without the need to
141
+ post bond.
142
+
143
+ ================================================================================
144
+ 10. GOVERNING LAW AND VENUE
145
+ ================================================================================
146
+
147
+ This notice shall be governed by and construed in accordance with the laws
148
+ of the Islamic Republic of Pakistan, without regard to its conflict-of-laws
149
+ principles. Any dispute arising out of or in connection with this notice
150
+ shall be subject to the exclusive jurisdiction of the courts of Karachi,
151
+ Pakistan.
152
+
153
+ The United Nations Convention on Contracts for the International Sale of
154
+ Goods shall not apply.
155
+
156
+ ================================================================================
157
+ 11. SEVERABILITY AND ENTIRE NOTICE
158
+ ================================================================================
159
+
160
+ If any provision of this notice is held invalid or unenforceable, the
161
+ remaining provisions shall continue in full force and effect. This notice,
162
+ together with any separate signed written licence executed between KoderLabs
163
+ and a licensee, constitutes the entire agreement concerning the Software and
164
+ supersedes all prior or contemporaneous understandings.
165
+
166
+ ================================================================================
167
+ 12. CONTACT
168
+ ================================================================================
169
+
170
+ For licensing inquiries, audit requests, or notice of suspected
171
+ infringement, contact:
172
+
173
+ KoderLabs
174
+ Attn: Jawaid Gadiwala
175
+ Email: jawaidgadiwala@gmail.com
176
+
177
+ ================================================================================
178
+ END OF LICENCE
179
+ ================================================================================
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # Proprietary Software
2
+
3
+ KoderLabs proprietary. All rights reserved.
4
+
5
+ See the bundled `LICENSE` for terms. No grant of any rights, express or
6
+ implied, is conferred by access to or possession of this package. A
7
+ separate signed written licence from KoderLabs is required for any use.
8
+
9
+ Licensing inquiries: jawaidgadiwala@gmail.com
@@ -0,0 +1,177 @@
1
+ // src/sourcemaps-upload.ts
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ var DEFAULT_MAX_BYTES = 50 * 1024 * 1024;
5
+ var MAX_RETRIES = 2;
6
+ var RETRY_BASE_MS = 1e3;
7
+ var InstantTasksSourceMapsPlugin = class {
8
+ constructor(opts) {
9
+ this.opts = {
10
+ distDir: ".next",
11
+ maxFileBytes: DEFAULT_MAX_BYTES,
12
+ strict: opts.strict ?? process.env.CI === "true",
13
+ ...opts
14
+ };
15
+ }
16
+ apply(compiler) {
17
+ const isProduction = compiler.options?.mode === "production";
18
+ const isClientCompiler = !compiler.name || compiler.name === "client" || compiler.name === "browser";
19
+ if (!isProduction || !isClientCompiler) return;
20
+ compiler.hooks.afterEmit.tapAsync(
21
+ "InstantTasksSourceMapsPlugin",
22
+ async (compilation, callback) => {
23
+ try {
24
+ const failed = await this._uploadMaps(compilation.outputPath ?? this.opts.distDir);
25
+ if (failed.length > 0 && this.opts.strict) {
26
+ const summary = failed.map((f) => ` ${f.file}: ${f.status ? `HTTP ${f.status}` : f.error ?? "unknown"}`).join("\n");
27
+ callback(new Error(`[InstantTasks] ${failed.length} source-map upload(s) failed:
28
+ ${summary}`));
29
+ return;
30
+ }
31
+ } catch (err) {
32
+ if (this.opts.strict) {
33
+ callback(err);
34
+ return;
35
+ }
36
+ console.warn("[InstantTasks] source-map upload failed:", err);
37
+ }
38
+ callback();
39
+ }
40
+ );
41
+ }
42
+ async _uploadMaps(outputPath) {
43
+ const resolvedRoot = path.resolve(outputPath);
44
+ const mapFiles = this._findMapFiles(resolvedRoot);
45
+ if (mapFiles.length === 0) {
46
+ console.log("[InstantTasks] No .map files found to upload in", resolvedRoot);
47
+ return [];
48
+ }
49
+ console.log(`[InstantTasks] Uploading ${mapFiles.length} source map(s)\u2026`);
50
+ const uploadUrl = `${this.opts.endpoint}/api/v1/sdk/source-maps`;
51
+ const results = await Promise.all(mapFiles.map((f) => this._uploadOne(uploadUrl, resolvedRoot, f)));
52
+ const failed = results.filter((r) => !r.ok);
53
+ const ok = results.length - failed.length;
54
+ console.log(`[InstantTasks] Source map upload complete \u2014 ${ok} ok, ${failed.length} failed.`);
55
+ return failed;
56
+ }
57
+ async _uploadOne(uploadUrl, root, filePath) {
58
+ const resolved = path.resolve(filePath);
59
+ if (!resolved.startsWith(root + path.sep) && resolved !== root) {
60
+ return { file: filePath, ok: false, error: "path escapes dist root" };
61
+ }
62
+ const relativePath = path.relative(root, resolved);
63
+ if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
64
+ return { file: filePath, ok: false, error: "invalid relative path" };
65
+ }
66
+ let stat;
67
+ try {
68
+ stat = await fs.promises.stat(resolved);
69
+ } catch (e) {
70
+ return { file: relativePath, ok: false, error: e.message };
71
+ }
72
+ if (stat.size > this.opts.maxFileBytes) {
73
+ console.warn(`[InstantTasks] Skipping ${relativePath} \u2014 ${stat.size} bytes exceeds cap ${this.opts.maxFileBytes}`);
74
+ return { file: relativePath, ok: false, error: `file too large (${stat.size} bytes)` };
75
+ }
76
+ let content;
77
+ try {
78
+ content = await fs.promises.readFile(resolved, "utf-8");
79
+ } catch (e) {
80
+ return { file: relativePath, ok: false, error: e.message };
81
+ }
82
+ let lastErr;
83
+ let lastStatus;
84
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
85
+ try {
86
+ const res = await fetch(uploadUrl, {
87
+ method: "POST",
88
+ headers: {
89
+ "Content-Type": "application/json",
90
+ Authorization: `Bearer ${this.opts.secretKey}`
91
+ },
92
+ body: JSON.stringify({ path: relativePath, content })
93
+ });
94
+ if (res.ok) return { file: relativePath, ok: true, status: res.status };
95
+ lastStatus = res.status;
96
+ if (res.status < 500 || res.status >= 600) break;
97
+ } catch (e) {
98
+ lastErr = e.message;
99
+ }
100
+ if (attempt < MAX_RETRIES) {
101
+ await new Promise((r) => setTimeout(r, RETRY_BASE_MS * Math.pow(2, attempt)));
102
+ }
103
+ }
104
+ console.warn(`[InstantTasks] Failed to upload ${relativePath}: ${lastStatus ? `HTTP ${lastStatus}` : lastErr ?? "unknown"}`);
105
+ return { file: relativePath, ok: false, status: lastStatus, error: lastErr };
106
+ }
107
+ _findMapFiles(dir) {
108
+ if (!fs.existsSync(dir)) return [];
109
+ const results = [];
110
+ const root = path.resolve(dir);
111
+ const walk = (current) => {
112
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
113
+ const full = path.join(current, entry.name);
114
+ if (entry.isSymbolicLink()) continue;
115
+ if (entry.isDirectory()) {
116
+ walk(full);
117
+ } else if (entry.isFile() && entry.name.endsWith(".map")) {
118
+ const resolved = path.resolve(full);
119
+ if (resolved.startsWith(root + path.sep) || resolved === root) results.push(full);
120
+ }
121
+ }
122
+ };
123
+ walk(root);
124
+ return results;
125
+ }
126
+ };
127
+
128
+ // src/plugin.ts
129
+ function withInstantTasks(opts = {}) {
130
+ return function applyInstantTasks(nextConfig) {
131
+ if (typeof nextConfig === "function") {
132
+ return async (phase, args) => {
133
+ const resolved = await nextConfig(phase, args);
134
+ return applyConfig(resolved, opts);
135
+ };
136
+ }
137
+ return applyConfig(nextConfig, opts);
138
+ };
139
+ }
140
+ function applyConfig(config, opts) {
141
+ for (const key of Object.keys(process.env)) {
142
+ if (/^NEXT_PUBLIC_.*INSTANTTASKS.*SECRET/i.test(key)) {
143
+ throw new Error(
144
+ `[InstantTasks] ${key} is exposed via NEXT_PUBLIC_* and will leak into the client bundle. Move the value to a non-NEXT_PUBLIC env (e.g. .env.local or CI secret) and read via INSTANTTASKS_SECRET_KEY.`
145
+ );
146
+ }
147
+ }
148
+ const secretKey = opts.secretKey ?? process.env["INSTANTTASKS_SECRET_KEY"] ?? "";
149
+ const endpoint = opts.endpoint ?? "https://tasks.koderlabs.net";
150
+ const distDir = opts.distDir ?? config.distDir ?? ".next";
151
+ const merged = {
152
+ ...config,
153
+ // Always emit browser source maps in production — required for meaningful
154
+ // stack traces in the Issues dashboard.
155
+ productionBrowserSourceMaps: true
156
+ };
157
+ const previousWebpack = config.webpack;
158
+ merged.webpack = (webpackConfig, context) => {
159
+ let finalConfig = previousWebpack ? previousWebpack(webpackConfig, context) : webpackConfig;
160
+ const { isServer, dev } = context;
161
+ const shouldUpload = !dev && !isServer && !opts.disableSourceMapUpload && Boolean(secretKey);
162
+ if (shouldUpload) {
163
+ finalConfig.plugins = [
164
+ ...finalConfig.plugins ?? [],
165
+ new InstantTasksSourceMapsPlugin({ endpoint, secretKey, distDir })
166
+ ];
167
+ }
168
+ return finalConfig;
169
+ };
170
+ return merged;
171
+ }
172
+
173
+ export {
174
+ InstantTasksSourceMapsPlugin,
175
+ withInstantTasks
176
+ };
177
+ //# sourceMappingURL=chunk-2YRBUQGE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sourcemaps-upload.ts","../src/plugin.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Options for the source-maps upload webpack plugin.\n */\nexport interface SourceMapsUploadOptions {\n /** InstantTasks API base URL (e.g. \"https://tasks.koderlabs.net\") */\n endpoint: string;\n /** Project access key with upload permissions */\n secretKey: string;\n /** Directory to scan for .map files (defaults to \".next\") */\n distDir?: string;\n /**\n * When true (or `process.env.CI === 'true'`), exit the build with a non-zero\n * code if ANY map fails to upload. Default: opt-in via env so existing\n * pipelines don't break on rollout — set explicitly once stable.\n */\n strict?: boolean;\n /**\n * Skip files larger than this (bytes). Default 50MB — beyond which the upload\n * is almost certainly going to OOM or time out anyway.\n */\n maxFileBytes?: number;\n}\n\nconst DEFAULT_MAX_BYTES = 50 * 1024 * 1024;\nconst MAX_RETRIES = 2;\nconst RETRY_BASE_MS = 1_000;\n\ninterface UploadOutcome { file: string; ok: boolean; status?: number; error?: string }\n\n/**\n * Webpack plugin that uploads source maps to the InstantTasks SDK endpoint\n * after a **production** build completes.\n *\n * Failure handling: when `strict` is true (or `CI=true`), any failed upload\n * fails the build. Otherwise failures are warned but the build continues\n * — same as before, but with a much louder report (per-file + summary).\n *\n * Path safety: the relative path stored alongside the map is validated to\n * never contain `..` or be absolute — defends against a misconfigured\n * `outputPath` accidentally letting the plugin walk symlinked files outside\n * the dist directory and store them under attacker-influenced keys.\n */\nexport class InstantTasksSourceMapsPlugin {\n private readonly opts: Required<Omit<SourceMapsUploadOptions, 'strict'>> & { strict: boolean };\n\n constructor(opts: SourceMapsUploadOptions) {\n this.opts = {\n distDir: '.next',\n maxFileBytes: DEFAULT_MAX_BYTES,\n strict: opts.strict ?? process.env.CI === 'true',\n ...opts,\n };\n }\n\n apply(compiler: any) {\n // Skip in any environment other than a production client build.\n const isProduction = compiler.options?.mode === 'production';\n const isClientCompiler =\n !compiler.name || compiler.name === 'client' || compiler.name === 'browser';\n\n if (!isProduction || !isClientCompiler) return;\n\n compiler.hooks.afterEmit.tapAsync(\n 'InstantTasksSourceMapsPlugin',\n async (compilation: any, callback: (err?: Error) => void) => {\n try {\n const failed = await this._uploadMaps(compilation.outputPath ?? this.opts.distDir);\n if (failed.length > 0 && this.opts.strict) {\n const summary = failed\n .map((f) => ` ${f.file}: ${f.status ? `HTTP ${f.status}` : f.error ?? 'unknown'}`)\n .join('\\n');\n callback(new Error(`[InstantTasks] ${failed.length} source-map upload(s) failed:\\n${summary}`));\n return;\n }\n } catch (err) {\n if (this.opts.strict) {\n callback(err as Error);\n return;\n }\n console.warn('[InstantTasks] source-map upload failed:', err);\n }\n callback();\n },\n );\n }\n\n private async _uploadMaps(outputPath: string): Promise<UploadOutcome[]> {\n const resolvedRoot = path.resolve(outputPath);\n const mapFiles = this._findMapFiles(resolvedRoot);\n if (mapFiles.length === 0) {\n console.log('[InstantTasks] No .map files found to upload in', resolvedRoot);\n return [];\n }\n\n console.log(`[InstantTasks] Uploading ${mapFiles.length} source map(s)…`);\n\n const uploadUrl = `${this.opts.endpoint}/api/v1/sdk/source-maps`;\n const results = await Promise.all(mapFiles.map((f) => this._uploadOne(uploadUrl, resolvedRoot, f)));\n const failed = results.filter((r) => !r.ok);\n const ok = results.length - failed.length;\n console.log(`[InstantTasks] Source map upload complete — ${ok} ok, ${failed.length} failed.`);\n return failed;\n }\n\n private async _uploadOne(uploadUrl: string, root: string, filePath: string): Promise<UploadOutcome> {\n // Path traversal defense — the on-disk file path must resolve inside the\n // dist root, and the stored relative key must not climb above it.\n const resolved = path.resolve(filePath);\n if (!resolved.startsWith(root + path.sep) && resolved !== root) {\n return { file: filePath, ok: false, error: 'path escapes dist root' };\n }\n const relativePath = path.relative(root, resolved);\n if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n return { file: filePath, ok: false, error: 'invalid relative path' };\n }\n\n let stat: fs.Stats;\n try {\n stat = await fs.promises.stat(resolved);\n } catch (e) {\n return { file: relativePath, ok: false, error: (e as Error).message };\n }\n if (stat.size > this.opts.maxFileBytes) {\n console.warn(`[InstantTasks] Skipping ${relativePath} — ${stat.size} bytes exceeds cap ${this.opts.maxFileBytes}`);\n return { file: relativePath, ok: false, error: `file too large (${stat.size} bytes)` };\n }\n\n let content: string;\n try {\n content = await fs.promises.readFile(resolved, 'utf-8');\n } catch (e) {\n return { file: relativePath, ok: false, error: (e as Error).message };\n }\n\n let lastErr: string | undefined;\n let lastStatus: number | undefined;\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n try {\n const res = await fetch(uploadUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.opts.secretKey}`,\n },\n body: JSON.stringify({ path: relativePath, content }),\n });\n if (res.ok) return { file: relativePath, ok: true, status: res.status };\n lastStatus = res.status;\n // Retry only transient 5xx; 4xx is configuration — fail fast.\n if (res.status < 500 || res.status >= 600) break;\n } catch (e) {\n lastErr = (e as Error).message;\n }\n if (attempt < MAX_RETRIES) {\n await new Promise((r) => setTimeout(r, RETRY_BASE_MS * Math.pow(2, attempt)));\n }\n }\n console.warn(`[InstantTasks] Failed to upload ${relativePath}: ${lastStatus ? `HTTP ${lastStatus}` : lastErr ?? 'unknown'}`);\n return { file: relativePath, ok: false, status: lastStatus, error: lastErr };\n }\n\n private _findMapFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const results: string[] = [];\n const root = path.resolve(dir);\n const walk = (current: string) => {\n for (const entry of fs.readdirSync(current, { withFileTypes: true })) {\n const full = path.join(current, entry.name);\n // Refuse to follow symlinks — they could point outside dist root.\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory()) {\n walk(full);\n } else if (entry.isFile() && entry.name.endsWith('.map')) {\n const resolved = path.resolve(full);\n if (resolved.startsWith(root + path.sep) || resolved === root) results.push(full);\n }\n }\n };\n walk(root);\n return results;\n }\n}\n","import { InstantTasksSourceMapsPlugin } from './sourcemaps-upload';\nimport type { InitOptions } from '@koderlabs/tasks-sdk';\n\nexport interface WithInstantTasksOptions {\n /** Matches InitOptions.endpoint — where to POST source maps */\n endpoint?: string;\n /**\n * Management secret key for source-map uploads.\n * Defaults to process.env.INSTANTTASKS_SECRET_KEY.\n */\n secretKey?: string;\n /**\n * Skip source-map upload even in production. Useful during CI dry-runs.\n * @default false\n */\n disableSourceMapUpload?: boolean;\n /**\n * Relative path to Next.js output directory.\n * @default '.next'\n */\n distDir?: string;\n}\n\ntype NextConfig = Record<string, any>;\ntype NextConfigFn = (phase: string, args: Record<string, any>) => NextConfig | Promise<NextConfig>;\n\n/**\n * `withInstantTasks(opts)(nextConfig)` — higher-order wrapper for next.config.js/ts.\n *\n * What it does:\n * 1. Enables `productionBrowserSourceMaps: true` so Next.js emits browser .map files.\n * 2. In production builds only, injects `InstantTasksSourceMapsPlugin` into the\n * Webpack config so source maps are uploaded after the client bundle is emitted.\n *\n * Turbopack v1 decision: Next.js 15 ships Turbopack as the **dev** bundler only;\n * production builds continue to use Webpack. We hook into `webpack` here (v1).\n * Turbopack plugin support is deferred to v1.1 once the `experimental.turbopack`\n * plugin API stabilises.\n *\n * @example\n * ```js\n * // next.config.js\n * const { withInstantTasks } = require('@koderlabs/tasks-sdk-nextjs/plugin');\n * module.exports = withInstantTasks({ secretKey: process.env.IT_KEY })({});\n * ```\n */\nexport function withInstantTasks(opts: WithInstantTasksOptions = {}) {\n return function applyInstantTasks(nextConfig: NextConfig | NextConfigFn): NextConfig | NextConfigFn {\n // Support next.config.js that exports a function (phase-based config).\n if (typeof nextConfig === 'function') {\n return async (phase: string, args: Record<string, any>) => {\n const resolved = await (nextConfig as NextConfigFn)(phase, args);\n return applyConfig(resolved, opts);\n };\n }\n return applyConfig(nextConfig, opts);\n };\n}\n\nfunction applyConfig(config: NextConfig, opts: WithInstantTasksOptions): NextConfig {\n // Refuse to read the secret from a NEXT_PUBLIC_* env. Next.js inlines those into\n // the client bundle; any value present there is already compromised. Crashing\n // the build is the only safe response.\n for (const key of Object.keys(process.env)) {\n if (/^NEXT_PUBLIC_.*INSTANTTASKS.*SECRET/i.test(key)) {\n throw new Error(\n `[InstantTasks] ${key} is exposed via NEXT_PUBLIC_* and will leak into the client bundle. ` +\n 'Move the value to a non-NEXT_PUBLIC env (e.g. .env.local or CI secret) and read via INSTANTTASKS_SECRET_KEY.',\n );\n }\n }\n const secretKey =\n opts.secretKey ?? process.env['INSTANTTASKS_SECRET_KEY'] ?? '';\n const endpoint =\n opts.endpoint ?? 'https://tasks.koderlabs.net';\n const distDir = opts.distDir ?? config.distDir ?? '.next';\n\n const merged: NextConfig = {\n ...config,\n // Always emit browser source maps in production — required for meaningful\n // stack traces in the Issues dashboard.\n productionBrowserSourceMaps: true,\n };\n\n // Wrap the existing webpack config function (or create one).\n const previousWebpack = config.webpack;\n\n merged.webpack = (webpackConfig: any, context: any) => {\n // Call any pre-existing webpack customisation first.\n let finalConfig = previousWebpack\n ? previousWebpack(webpackConfig, context)\n : webpackConfig;\n\n // Only upload in production builds; skip in dev and in the server compiler.\n const { isServer, dev } = context;\n const shouldUpload =\n !dev &&\n !isServer &&\n !opts.disableSourceMapUpload &&\n Boolean(secretKey);\n\n if (shouldUpload) {\n finalConfig.plugins = [\n ...(finalConfig.plugins ?? []),\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AAI,IAAI;AAC1B,UAAM,eACJ,CAAC,OACD,CAAC,YACD,CAAC,KAAK,0BACN,QAAQ,SAAS;AAEnB,QAAI,cAAc;AAChB,kBAAY,UAAU;AAAA,QACpB,GAAI,YAAY,WAAW,CAAC;AAAA,QAC5B,IAAI,6BAA6B,EAAE,UAAU,WAAW,QAAQ,CAAC;AAAA,MACnE;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ "use client";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/client.ts
22
+ var client_exports = {};
23
+ __export(client_exports, {
24
+ ErrorBoundary: () => import_tasks_sdk_react.ErrorBoundary,
25
+ InstantTasksProvider: () => import_tasks_sdk_react.InstantTasksProvider,
26
+ useInstantTasks: () => import_tasks_sdk_react.useInstantTasks,
27
+ useUser: () => import_tasks_sdk_react.useUser
28
+ });
29
+ module.exports = __toCommonJS(client_exports);
30
+ var import_tasks_sdk_react = require("@koderlabs/tasks-sdk-react");
31
+ // Annotate the CommonJS export names for ESM import in node:
32
+ 0 && (module.exports = {
33
+ ErrorBoundary,
34
+ InstantTasksProvider,
35
+ useInstantTasks,
36
+ useUser
37
+ });
38
+ //# sourceMappingURL=client.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["'use client';\n\n// Re-export React adapter hooks for use in Next.js App Router Client Components.\n// The 'use client' directive at the top of this file marks the module boundary\n// for the React Server Components bundler.\n\nexport {\n InstantTasksProvider,\n ErrorBoundary,\n useInstantTasks,\n useUser,\n} from '@koderlabs/tasks-sdk-react';\nexport type {\n InstantTasksProviderProps,\n ErrorBoundaryProps,\n UseInstantTasksResult,\n InstantTasksContextValue,\n} from '@koderlabs/tasks-sdk-react';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,6BAKO;","names":[]}
package/dist/client.js ADDED
@@ -0,0 +1,16 @@
1
+ "use client";
2
+
3
+ // src/client.ts
4
+ import {
5
+ InstantTasksProvider,
6
+ ErrorBoundary,
7
+ useInstantTasks,
8
+ useUser
9
+ } from "@koderlabs/tasks-sdk-react";
10
+ export {
11
+ ErrorBoundary,
12
+ InstantTasksProvider,
13
+ useInstantTasks,
14
+ useUser
15
+ };
16
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["'use client';\n\n// Re-export React adapter hooks for use in Next.js App Router Client Components.\n// The 'use client' directive at the top of this file marks the module boundary\n// for the React Server Components bundler.\n\nexport {\n InstantTasksProvider,\n ErrorBoundary,\n useInstantTasks,\n useUser,\n} from '@koderlabs/tasks-sdk-react';\nexport type {\n InstantTasksProviderProps,\n ErrorBoundaryProps,\n UseInstantTasksResult,\n InstantTasksContextValue,\n} from '@koderlabs/tasks-sdk-react';\n"],"mappings":";;;AAMA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":[]}