Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(file-loaders): drop 25MB @napi-rs/canvas from PDF parsing (#17858)

Innei787b24de7050
diff --git a/.npmrc b/.npmrc
index 999be965034..a99986425a9 100644
--- a/.npmrc
+++ b/.npmrc
@@ -18,4 +18,3 @@ public-hoist-pattern[]=*stylelint*
public-hoist-pattern[]=@auth/core
public-hoist-pattern[]=pdfjs-dist
-public-hoist-pattern[]=@napi-rs/canvas-*
diff --git a/apps/cli/tsdown.config.ts b/apps/cli/tsdown.config.ts
index 3b3505e7be1..3a17b9f4c2d 100644
--- a/apps/cli/tsdown.config.ts
+++ b/apps/cli/tsdown.config.ts
@@ -9,7 +9,6 @@ export default defineConfig({
// production dependency inside the bundle so the embedded CLI is truly
// self-contained instead of failing at startup with ERR_MODULE_NOT_FOUND.
alwaysBundle: ['ws'],
- neverBundle: ['@napi-rs/canvas'],
},
entry: ['src/index.ts'],
fixedExtension: false,
diff --git a/apps/desktop/native-deps.config.mjs b/apps/desktop/native-deps.config.mjs
index 7d1ae2c7cf5..6d635fe046a 100644
--- a/apps/desktop/native-deps.config.mjs
+++ b/apps/desktop/native-deps.config.mjs
@@ -41,7 +41,6 @@ export const nativeModules = [
// macOS-only native modules
...(isDarwin ? ['node-mac-permissions'] : []),
'@lydell/node-pty',
- '@napi-rs/canvas',
'get-windows',
'node-screenshots',
];
@@ -71,7 +70,6 @@ export function getAsarUnpackPatterns() {
return [
'node_modules/@lydell/node-pty-*/prebuilds/**/*.node',
'node_modules/@lydell/node-pty-*/prebuilds/*/spawn-helper',
- 'node_modules/@napi-rs/canvas-*/*.node',
'node_modules/font-list/libs/darwin/fontlist',
'node_modules/get-windows/main',
'node_modules/node-mac-permissions/build/Release/permissions.node',
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 48d7f033633..2e09ece9845 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -49,7 +49,6 @@
"dependencies": {
"@lobehub/fluent-emoji": "^4.1.0",
"@lydell/node-pty": "1.2.0-beta.12",
- "@napi-rs/canvas": "^0.1.100",
"electron-log": "^5.4.4",
"font-list": "^2.1.0",
"get-windows": "^9.3.0",
@@ -127,7 +126,6 @@
},
"pnpm": {
"onlyBuiltDependencies": [
- "@napi-rs/canvas",
"electron",
"electron-builder",
"node-mac-permissions"
diff --git a/next.config.ts b/next.config.ts
index 77b9fa022eb..583c4ea2564 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -5,10 +5,9 @@ const isVercel = !!process.env.VERCEL_ENV;
const vercelConfig = {
// Vercel serverless optimization: exclude musl binaries from all routes
// Vercel uses Amazon Linux (glibc), not Alpine Linux (musl)
- // This saves ~45MB (29MB canvas-musl + 16MB sharp-musl) per serverless function
+ // This saves ~16MB (sharp-musl) per serverless function
outputFileTracingExcludes: {
'*': [
- 'node_modules/.pnpm/@napi-rs+canvas-*-musl*',
'node_modules/.pnpm/@img+sharp-libvips-*musl*',
// Exclude SPA/desktop/mobile build artifacts from serverless functions
'public/_spa/**',
diff --git a/package.json b/package.json
index 44655b2646d..751ef816412 100644
--- a/package.json
+++ b/package.json
@@ -305,7 +305,6 @@
"@lobehub/tts": "^5.1.2",
"@lobehub/ui": "^5.28.0",
"@modelcontextprotocol/sdk": "^1.29.0",
- "@napi-rs/canvas": "^0.1.100",
"@neondatabase/serverless": "^1.1.0",
"@next/third-parties": "^16.3.0",
"@opentelemetry/auto-instrumentations-node": "^0.76.0",
diff --git a/packages/file-loaders/package.json b/packages/file-loaders/package.json
index be5a0307f4f..c6c4d181270 100644
--- a/packages/file-loaders/package.json
+++ b/packages/file-loaders/package.json
@@ -25,7 +25,6 @@
"test:coverage": "vitest --coverage --silent='passed-only'"
},
"dependencies": {
- "@napi-rs/canvas": "^0.1.100",
"@xmldom/xmldom": "^0.9.10",
"concat-stream": "^2.0.0",
"debug": "^4.4.3",
diff --git a/packages/file-loaders/src/loaders/index.ts b/packages/file-loaders/src/loaders/index.ts
index f4aab8c16d5..6665942440a 100644
--- a/packages/file-loaders/src/loaders/index.ts
+++ b/packages/file-loaders/src/loaders/index.ts
@@ -32,20 +32,6 @@ const lazyFileLoaders: Record<Exclude<SupportedFileType, 'txt'>, LazyLoaderFacto
return IpynbLoader;
},
pdf: async () => {
- // Polyfill DOMMatrix for Node.js environment before importing pdfjs-dist
- // pdfjs-dist 5.x uses DOMMatrix at module initialization which doesn't exist in Node.js
- if (typeof globalThis.DOMMatrix === 'undefined') {
- try {
- const canvas = require('@napi-rs/canvas');
- globalThis.DOMMatrix = canvas.DOMMatrix;
- globalThis.DOMPoint = canvas.DOMPoint;
- globalThis.DOMRect = canvas.DOMRect;
- globalThis.Path2D = canvas.Path2D;
- } catch (e) {
- console.error('Error importing @napi-rs/canvas:', e);
- // @napi-rs/canvas not available, pdfjs-dist may fail if DOMMatrix is needed
- }
- }
const { PdfLoader } = await import('./pdf');
return PdfLoader;
},
diff --git a/packages/file-loaders/src/loaders/pdf/domMatrix.test.ts b/packages/file-loaders/src/loaders/pdf/domMatrix.test.ts
new file mode 100644
index 00000000000..3e79a690fda
--- /dev/null
+++ b/packages/file-loaders/src/loaders/pdf/domMatrix.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest';
+
+import { DOMMatrixPolyfill } from './domMatrix';
+
+const tuple = (m: DOMMatrixPolyfill) =>
+ [m.a, m.b, m.c, m.d, m.e, m.f].map((n) => Number(n.toFixed(10)));
+
+// Expected values captured from `@napi-rs/canvas`'s DOMMatrix, so this suite
+// pins behavioural parity with the native implementation it replaced.
+describe('DOMMatrixPolyfill', () => {
+ it('constructs identity with no arguments', () => {
+ expect(tuple(new DOMMatrixPolyfill())).toEqual([1, 0, 0, 1, 0, 0]);
+ expect(new DOMMatrixPolyfill().isIdentity).toBe(true);
+ expect(new DOMMatrixPolyfill().is2D).toBe(true);
+ });
+
+ it('constructs from a 6-value array', () => {
+ expect(tuple(new DOMMatrixPolyfill([2, 0.5, -1, 3, 10, -20]))).toEqual([
+ 2, 0.5, -1, 3, 10, -20,
+ ]);
+ });
+
+ it('constructs from a typed array', () => {
+ expect(tuple(new DOMMatrixPolyfill(Float64Array.from([1, 2, 3, 4, 5, 6])))).toEqual([
+ 1, 2, 3, 4, 5, 6,
+ ]);
+ });
+
+ it('constructs from a 16-value 3D array by taking the 2D components', () => {
+ const values = [2, 3, 0, 0, 4, 5, 0, 0, 0, 0, 1, 0, 6, 7, 0, 1];
+ expect(tuple(new DOMMatrixPolyfill(values))).toEqual([2, 3, 4, 5, 6, 7]);
+ });
+
+ it('rejects an unsupported value count', () => {
+ expect(() => new DOMMatrixPolyfill([1, 2, 3])).toThrow(/Expected 6 or 16/);
+ });
+
+ it('exposes m11..m42 aliases', () => {
+ const m = new DOMMatrixPolyfill([1, 2, 3, 4, 5, 6]);
+ expect([m.m11, m.m12, m.m21, m.m22, m.m41, m.m42]).toEqual([1, 2, 3, 4, 5, 6]);
+ });
+
+ it('matches pdf.worker.mjs image-mask scaling', () => {
+ const m = new DOMMatrixPolyfill().scaleSelf(1 / 800, -1 / 600).translateSelf(0, -600);
+ expect(tuple(m)).toEqual([0.00125, 0, 0, -0.0016666667, 0, 1]);
+ });
+
+ it('matches pdf.mjs text-path composition', () => {
+ const m = new DOMMatrixPolyfill([1, 0, 0, 1, 3, 4])
+ .preMultiplySelf(new DOMMatrixPolyfill([2, 0, 0, 2, 1, 1]).invertSelf())
+ .translate(10, 20)
+ .scale(12, -12);
+ expect(tuple(m)).toEqual([6, 0, 0, -6, 6, 11.5]);
+ });
+
+ it('matches pdf.mjs pattern composition', () => {
+ const m = new DOMMatrixPolyfill([3, 1, 1, 3, 5, 5])
+ .invertSelf()
+ .multiplySelf(new DOMMatrixPolyfill([1, 0, 0, 1, 2, 2]));
+ expect(tuple(m)).toEqual([0.375, -0.125, -0.125, 0.375, -0.75, -0.75]);
+ });
+
+ it('translates and scales without mutating the receiver', () => {
+ const base = new DOMMatrixPolyfill([2, 0, 0, 3, 1, 1]);
+ expect(tuple(base.translate(5, 7))).toEqual([2, 0, 0, 3, 11, 22]);
+ expect(tuple(base.scale(0.5, 4))).toEqual([1, 0, 0, 12, 1, 1]);
+ expect(tuple(base)).toEqual([2, 0, 0, 3, 1, 1]);
+ });
+
+ it('inverts', () => {
+ expect(tuple(new DOMMatrixPolyfill([2, 0.5, -1, 3, 10, -20]).invertSelf())).toEqual([
+ 0.4615384615, -0.0769230769, 0.1538461538, 0.3076923077, -1.5384615385, 6.9230769231,
+ ]);
+ });
+
+ it('yields NaN components for a singular matrix', () => {
+ const m = new DOMMatrixPolyfill([1, 2, 2, 4, 0, 0]).invertSelf();
+ expect(tuple(m).every(Number.isNaN)).toBe(true);
+ });
+
+ it('multiplies in both directions', () => {
+ const other = new DOMMatrixPolyfill([1, 2, 3, 4, 5, 6]);
+ expect(tuple(new DOMMatrixPolyfill([2, 0.5, -1, 3, 10, -20]).multiplySelf(other))).toEqual([
+ 0, 6.5, 2, 13.5, 14, 0.5,
+ ]);
+ expect(tuple(new DOMMatrixPolyfill([2, 0.5, -1, 3, 10, -20]).preMultiplySelf(other))).toEqual([
+ 3.5, 6, 8, 10, -45, -54,
+ ]);
+ });
+
+ it('rotates', () => {
+ expect(tuple(new DOMMatrixPolyfill().rotateSelf(37))).toEqual([
+ 0.79863551, 0.6018150232, -0.6018150232, 0.79863551, 0, 0,
+ ]);
+ });
+
+ it('scales around an origin', () => {
+ expect(tuple(new DOMMatrixPolyfill([1, 0, 0, 1, 2, 3]).scaleSelf(2, 3, 1, 10, 20))).toEqual([
+ 2, 0, 0, 3, -8, -37,
+ ]);
+ });
+
+ it('transforms a point', () => {
+ const point = new DOMMatrixPolyfill([2, 0, 0, 3, 5, 5]).transformPoint({ x: 3, y: 4 });
+ expect([point.x, point.y]).toEqual([11, 17]);
+ });
+});
diff --git a/packages/file-loaders/src/loaders/pdf/domMatrix.ts b/packages/file-loaders/src/loaders/pdf/domMatrix.ts
new file mode 100644
index 00000000000..6f26cde9698
--- /dev/null
+++ b/packages/file-loaders/src/loaders/pdf/domMatrix.ts
@@ -0,0 +1,183 @@
+type Matrix2D = [number, number, number, number, number, number];
+
+type MatrixInit =
+ ArrayLike<number> | { a: number; b: number; c: number; d: number; e: number; f: number };
+
+const IDENTITY: Matrix2D = [1, 0, 0, 1, 0, 0];
+
+const readInit = (init?: MatrixInit | null): Matrix2D => {
+ if (init === undefined || init === null) return [...IDENTITY];
+
+ if (typeof init === 'string') {
+ throw new TypeError('DOMMatrix string initializers are not supported');
+ }
+
+ if (Array.isArray(init) || ArrayBuffer.isView(init)) {
+ const values = Array.from(init as ArrayLike<number>);
+ if (values.length === 6) return values as Matrix2D;
+ if (values.length === 16) {
+ return [values[0], values[1], values[4], values[5], values[12], values[13]];
+ }
+ throw new TypeError(`Expected 6 or 16 matrix values, received ${values.length}`);
+ }
+
+ const { a, b, c, d, e, f } = init as Exclude<MatrixInit, ArrayLike<number>>;
+ return [a, b, c, d, e, f];
+};
+
+const compose = (m: Matrix2D, n: Matrix2D): Matrix2D => [
+ m[0] * n[0] + m[2] * n[1],
+ m[1] * n[0] + m[3] * n[1],
+ m[0] * n[2] + m[2] * n[3],
+ m[1] * n[2] + m[3] * n[3],
+ m[0] * n[4] + m[2] * n[5] + m[4],
+ m[1] * n[4] + m[3] * n[5] + m[5],
+];
+
+/**
+ * Minimal 2D-only DOMMatrix. pdfjs-dist instantiates `new DOMMatrix()` at module
+ * scope (`SCALE_MATRIX`, pdf.mjs), so importing it in Node throws without a global.
+ * Upstream polyfills this from `@napi-rs/canvas` — a 25MB Skia binary whose canvas
+ * surface we never touch, because we only call `page.getTextContent()`.
+ */
+export class DOMMatrixPolyfill {
+ a: number;
+ b: number;
+ c: number;
+ d: number;
+ e: number;
+ f: number;
+
+ constructor(init?: MatrixInit | null) {
+ [this.a, this.b, this.c, this.d, this.e, this.f] = readInit(init);
+ }
+
+ get is2D(): boolean {
+ return true;
+ }
+
+ get isIdentity(): boolean {
+ return (
+ this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1 && this.e === 0 && this.f === 0
+ );
+ }
+
+ get m11(): number {
+ return this.a;
+ }
+
+ get m12(): number {
+ return this.b;
+ }
+
+ get m21(): number {
+ return this.c;
+ }
+
+ get m22(): number {
+ return this.d;
+ }
+
+ get m41(): number {
+ return this.e;
+ }
+
+ get m42(): number {
+ return this.f;
+ }
+
+ private tuple(): Matrix2D {
+ return [this.a, this.b, this.c, this.d, this.e, this.f];
+ }
+
+ private assign(values: Matrix2D): this {
+ [this.a, this.b, this.c, this.d, this.e, this.f] = values;
+ return this;
+ }
+
+ multiplySelf(other?: MatrixInit): this {
+ return this.assign(compose(this.tuple(), readInit(other)));
+ }
+
+ preMultiplySelf(other?: MatrixInit): this {
+ return this.assign(compose(readInit(other), this.tuple()));
+ }
+
+ translateSelf(tx = 0, ty = 0): this {
+ return this.assign(compose(this.tuple(), [1, 0, 0, 1, tx, ty]));
+ }
+
+ scaleSelf(sx = 1, sy = sx, _sz = 1, originX = 0, originY = 0): this {
+ let m = this.tuple();
+ if (originX || originY) m = compose(m, [1, 0, 0, 1, originX, originY]);
+ m = compose(m, [sx, 0, 0, sy, 0, 0]);
+ if (originX || originY) m = compose(m, [1, 0, 0, 1, -originX, -originY]);
+ return this.assign(m);
+ }
+
+ rotateSelf(degrees = 0): this {
+ const radians = (degrees * Math.PI) / 180;
+ const cos = Math.cos(radians);
+ const sin = Math.sin(radians);
+ return this.assign(compose(this.tuple(), [cos, sin, -sin, cos, 0, 0]));
+ }
+
+ invertSelf(): this {
+ const determinant = this.a * this.d - this.b * this.c;
+ if (!determinant || !Number.isFinite(determinant)) {
+ return this.assign([Number.NaN, Number.NaN, Number.NaN, Number.NaN, Number.NaN, Number.NaN]);
+ }
+
+ const { a, b, c, d, e, f } = this;
+ return this.assign([
+ d / determinant,
+ -b / determinant,
+ -c / determinant,
+ a / determinant,
+ (c * f - d * e) / determinant,
+ (b * e - a * f) / determinant,
+ ]);
+ }
+
+ multiply(other?: MatrixInit): DOMMatrixPolyfill {
+ return new DOMMatrixPolyfill(this).multiplySelf(other);
+ }
+
+ translate(tx?: number, ty?: number): DOMMatrixPolyfill {
+ return new DOMMatrixPolyfill(this).translateSelf(tx, ty);
+ }
+
+ scale(sx?: number, sy?: number, sz?: number, originX?: number, originY?: number) {
+ return new DOMMatrixPolyfill(this).scaleSelf(sx, sy, sz, originX, originY);
+ }
+
+ rotate(degrees?: number): DOMMatrixPolyfill {
+ return new DOMMatrixPolyfill(this).rotateSelf(degrees);
+ }
+
+ inverse(): DOMMatrixPolyfill {
+ return new DOMMatrixPolyfill(this).invertSelf();
+ }
+
+ transformPoint(point: { x?: number; y?: number } = {}) {
+ const { x = 0, y = 0 } = point;
+ return { w: 1, x: this.a * x + this.c * y + this.e, y: this.b * x + this.d * y + this.f, z: 0 };
+ }
+
+ toFloat64Array(): Float64Array {
+ return Float64Array.from(this.tuple());
+ }
+
+ toString(): string {
+ return `matrix(${this.tuple().join(', ')})`;
+ }
+}
+
+/**
+ * Must run before `pdfjs-dist` is evaluated — its module scope reads the global.
+ */
+export const installDomMatrixPolyfill = () => {
+ if (typeof globalThis.DOMMatrix === 'undefined') {
+ globalThis.DOMMatrix = DOMMatrixPolyfill as unknown as typeof globalThis.DOMMatrix;
+ }
+};
diff --git a/packages/file-loaders/src/loaders/pdf/index.ts b/packages/file-loaders/src/loaders/pdf/index.ts
index 3a5a043ed2c..85ecefeab40 100644
--- a/packages/file-loaders/src/loaders/pdf/index.ts
+++ b/packages/file-loaders/src/loaders/pdf/index.ts
@@ -2,26 +2,48 @@ import { readFile } from 'node:fs/promises';
import debug from 'debug';
import type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist';
-import { getDocument, version } from 'pdfjs-dist/legacy/build/pdf.mjs';
-// @ts-ignore
-import * as _pdfjsWorker from 'pdfjs-dist/legacy/build/pdf.worker.mjs';
+import type * as Pdfjs from 'pdfjs-dist/legacy/build/pdf.mjs';
import type { TextContent } from 'pdfjs-dist/types/src/display/api';
import type { DocumentPage, FileLoaderInterface } from '../../types';
+import { installDomMatrixPolyfill } from './domMatrix';
import { promptTemplate } from './prompt';
const log = debug('file-loaders:pdf');
+type PdfjsModule = typeof Pdfjs;
+
+let pdfjsPromise: Promise<PdfjsModule> | null = null;
+
+/**
+ * pdfjs-dist reads `globalThis.DOMMatrix` while its own module body evaluates, so
+ * the polyfill has to land first. A static import would hoist above any setup
+ * statement, hence the deferred import.
+ */
+const loadPdfjs = (): Promise<PdfjsModule> => {
+ pdfjsPromise ??= (async () => {
+ installDomMatrixPolyfill();
+
+ const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs');
+ // @ts-ignore
+ await import('pdfjs-dist/legacy/build/pdf.worker.mjs');
+
+ return pdfjs;
+ })();
+
+ return pdfjsPromise;
+};
+
/**
* Loads PDF files page by page using the official pdfjs-dist library.
*/
export class PdfLoader implements FileLoaderInterface {
private pdfInstance: PDFDocumentProxy | null = null;
- private pdfjsWorker = _pdfjsWorker;
private async getPDFFile(filePath: string) {
// GlobalWorkerOptions.workerSrc should have been set at the module level.
// We are now relying on pdfjs-dist to use this path when it creates a worker.
+ const { getDocument } = await loadPdfjs();
log('Reading PDF file:', filePath);
const dataBuffer = await readFile(filePath);
@@ -141,6 +163,7 @@ export class PdfLoader implements FileLoaderInterface {
async attachDocumentMetadata(filePath: string): Promise<any> {
log('Attaching document metadata for PDF:', filePath);
+ const { version } = await loadPdfjs();
const pdf: PDFDocumentProxy = await this.getPDFFile(filePath);
log('Getting PDF metadata');
diff --git a/packages/file-loaders/test/setup.ts b/packages/file-loaders/test/setup.ts
index 4c82dd69463..1cf1e9283dc 100644
--- a/packages/file-loaders/test/setup.ts
+++ b/packages/file-loaders/test/setup.ts
@@ -1,17 +1,30 @@
-// Polyfill DOMMatrix for pdfjs-dist in Node.js environment
-import { DOMMatrix } from '@napi-rs/canvas';
+import Module from 'node:module';
-if (typeof global.DOMMatrix === 'undefined') {
- // @ts-ignore
- global.DOMMatrix = DOMMatrix;
-}
+type ModuleLoad = (request: string, ...rest: unknown[]) => unknown;
+type ModuleInternals = { _load: ModuleLoad & { canvasBlocked?: boolean } };
-// Polyfill URL.createObjectURL and URL.revokeObjectURL for pdfjs-dist
-if (typeof global.URL.createObjectURL === 'undefined') {
- global.URL.createObjectURL = () => 'blob:http://localhost/fake-blob-url';
-}
-if (typeof global.URL.revokeObjectURL === 'undefined') {
- global.URL.revokeObjectURL = () => {
- /* no-op */
- };
+const CANVAS_PACKAGE = '@napi-rs/canvas';
+
+/**
+ * pdfjs-dist unconditionally `require()`s `@napi-rs/canvas` — a 25MB Skia binary
+ * that only its rendering paths need. We extract text, never render, and install a
+ * pure-JS DOMMatrix instead. Blocking resolution keeps the suite honest: if that
+ * polyfill ever regresses, PDF tests fail here rather than in a packaged app.
+ */
+const moduleInternals = Module as unknown as ModuleInternals;
+const originalLoad = moduleInternals._load;
+
+if (!originalLoad.canvasBlocked) {
+ function blockCanvas(this: unknown, request: string, ...rest: unknown[]) {
+ if (request === CANVAS_PACKAGE || request.startsWith(`${CANVAS_PACKAGE}/`)) {
+ const error: NodeJS.ErrnoException = new Error(`Cannot find module '${request}'`);
+ error.code = 'MODULE_NOT_FOUND';
+ throw error;
+ }
+
+ return originalLoad.call(this, request, ...rest);
+ }
+
+ blockCanvas.canvasBlocked = true;
+ moduleInternals._load = blockCanvas;
}
diff --git a/packages/file-loaders/vitest.config.mts b/packages/file-loaders/vitest.config.mts
index 1fc20151270..f9299b78f50 100644
--- a/packages/file-loaders/vitest.config.mts
+++ b/packages/file-loaders/vitest.config.mts
@@ -14,5 +14,6 @@ export default defineConfig({
reporter: ['text', 'json', 'lcov', 'text-summary'],
},
environment: 'happy-dom',
+ setupFiles: ['./test/setup.ts'],
},
});
diff --git a/src/libs/next/config/define-config.test.ts b/src/libs/next/config/define-config.test.ts
index 0bea171f07a..8e58164f24d 100644
--- a/src/libs/next/config/define-config.test.ts
+++ b/src/libs/next/config/define-config.test.ts
@@ -1,27 +1,9 @@
import { describe, expect, it } from 'vitest';
import { defineConfig } from './define-config';
-import { dockerCanvasTracingIncludes } from './dockerCanvasTracingIncludes';
describe('defineConfig', () => {
it('disables Next.js agent rule injection', () => {
expect(defineConfig({}).agentRules).toBe(false);
});
});
-
-describe('dockerCanvasTracingIncludes', () => {
- it('keeps Docker canvas tracing away from pnpm symlink directories', () => {
- expect(dockerCanvasTracingIncludes).toContain('node_modules/@napi-rs/canvas/**/*');
- expect(dockerCanvasTracingIncludes).toContain('node_modules/@napi-rs/canvas-*/package.json');
- expect(dockerCanvasTracingIncludes).toContain('node_modules/@napi-rs/canvas-*/*.node');
- expect(dockerCanvasTracingIncludes).toContain(
- 'node_modules/.pnpm/@napi-rs+canvas-*/node_modules/@napi-rs/canvas-*/package.json',
- );
- expect(dockerCanvasTracingIncludes).toContain(
- 'node_modules/.pnpm/@napi-rs+canvas-*/node_modules/@napi-rs/canvas-*/*.node',
- );
- expect(dockerCanvasTracingIncludes).not.toContain('node_modules/@napi-rs/canvas-*/**/*');
- expect(dockerCanvasTracingIncludes).not.toContain('node_modules/.pnpm/@napi-rs+canvas*/**/*');
- expect(dockerCanvasTracingIncludes).not.toContain('node_modules/.pnpm/@napi-rs+canvas-*/**/*');
- });
-});
diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.ts
index f420130d17f..d4281db5458 100644
--- a/src/libs/next/config/define-config.ts
+++ b/src/libs/next/config/define-config.ts
@@ -2,8 +2,6 @@ import { codeInspectorPlugin } from 'code-inspector-plugin';
import { type NextConfig } from 'next';
import { type Header, type Redirect } from 'next/dist/lib/load-custom-routes';
-import { dockerCanvasTracingIncludes } from './dockerCanvasTracingIncludes';
-
const LANDING_SITEMAP_URL = 'https://lobehub.com/sitemap.xml';
interface CustomNextConfig {
@@ -45,11 +43,6 @@ export function defineConfig(config: CustomNextConfig) {
'dist/mobile/**',
'packages/database/migrations/**',
-
- // Ensure native bindings are included in standalone output.
- // `@napi-rs/canvas` is loaded via dynamic `require()` (see packages/file-loaders),
- // which may not be picked up by Next.js output tracing.
- ...dockerCanvasTracingIncludes,
]
: []),
],
@@ -353,11 +346,8 @@ export function defineConfig(config: CustomNextConfig) {
...(config.redirects ?? []),
],
// when external packages in dev mode with turbopack, this config will lead to bundle error
- // @napi-rs/canvas is a native module that can't be bundled by Turbopack
- // pdfjs-dist uses @napi-rs/canvas for DOMMatrix polyfill in Node.js environment
serverExternalPackages: config.serverExternalPackages ?? [
'pdfkit',
- '@napi-rs/canvas',
'@lobehub/editor',
'discord.js',
'ffmpeg-static',
diff --git a/src/libs/next/config/dockerCanvasTracingIncludes.ts b/src/libs/next/config/dockerCanvasTracingIncludes.ts
deleted file mode 100644
index 9433bb4a639..00000000000
--- a/src/libs/next/config/dockerCanvasTracingIncludes.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export const dockerCanvasTracingIncludes = [
- 'node_modules/@napi-rs/canvas/**/*',
- 'node_modules/@napi-rs/canvas-*/package.json',
- 'node_modules/@napi-rs/canvas-*/*.node',
- // Broad pnpm globs also match the symlink directory
- // `.../@napi-rs/canvas-linux-x64-gnu`; Turbopack 16.3.0-preview.5
- // tries to hash that directory as a file during Docker output tracing.
- 'node_modules/.pnpm/@napi-rs+canvas-*/node_modules/@napi-rs/canvas-*/package.json',
- 'node_modules/.pnpm/@napi-rs+canvas-*/node_modules/@napi-rs/canvas-*/*.node',
-];