Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(install): apply the whatsapp-web.js backport on a Windows checkout (#987)

Yudhi Armyndharis176f847803bf
diff --git a/.gitattributes b/.gitattributes
index 86634432a..1c6dff616 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,3 +1,6 @@
# Force LF line endings for files that must run inside Linux containers
*.sh text eol=lf
Dockerfile* text eol=lf
+# A unified diff must keep LF: a CRLF context line is not a marker any applier accepts, so a Windows
+# checkout would hand `git apply`/`patch` a diff both call corrupt (#889).
+*.patch text eol=lf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e479308b5..4ccb3671c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **`npm install` from source no longer fails on native Windows, and the whatsapp-web.js backport
+ actually applies there** (#889). A unified diff's lines must begin with a space, `+`, `-` or `@`, so
+ neither applier accepts one whose lines end CRLF — both stop at this patch's first empty context
+ line (`git apply`: "corrupt patch at line 7"; `patch`: "malformed patch at line 7"). Windows checks
+ the file out exactly that way whenever `core.autocrlf` is on, which is its default, so the `git
+ apply` fallback introduced for Windows could never run on Windows, and its failure was additionally
+ misread as a half-written tree — which turned a skippable warning into a hard install failure.
+ Three changes: the patch is normalized to LF before either applier sees it, which also repairs
+ clones already on disk with CRLF; a `.gitattributes` rule keeps fresh clones on LF; and a refusal to
+ parse the patch is now correctly treated as "nothing was written", so `--best-effort` degrades
+ instead of aborting the install. Only source installs on Windows were affected — the published
+ Docker image and every platform with the `patch` binary applied the backport normally.
+
- **Native Windows and npm 12 source installs no longer fail during dependency setup.** The
whatsapp-web.js backport now normalizes reject-file paths before comparing them, so Windows'
`src\structures\Contact.js.rej` is recognized as the same expected, harmless reject as the POSIX
diff --git a/scripts/patch-wwebjs-201832.js b/scripts/patch-wwebjs-201832.js
index 201171de5..6ba8158ea 100644
--- a/scripts/patch-wwebjs-201832.js
+++ b/scripts/patch-wwebjs-201832.js
@@ -29,6 +29,7 @@
'use strict';
const fs = require('fs');
+const os = require('os');
const path = require('path');
const { execFileSync } = require('child_process');
@@ -119,6 +120,33 @@ function findArtifacts(root, dir = root) {
* apply unchanged. core.autocrlf is forced off because a Windows global config would otherwise
* rewrite line endings in the files it touches, producing a tree no other platform generates.
*/
+/**
+ * Hand the appliers a patch with LF line endings, copying to a temp file only when the checked-out one
+ * has CRLF.
+ *
+ * Neither applier accepts CRLF: a unified diff line must start with ' ', '+', '-' or '@', and a bare
+ * \r is none of those, so both stop at line 7 of this patch — its first empty context line (`git
+ * apply`: "corrupt patch at line 7"; `patch`: "malformed patch at line 7"). Windows checks the file out
+ * that way whenever `core.autocrlf` is on, which is its default, so the git fallback added for Windows
+ * could never actually run there and took `npm install` down with it (#889).
+ *
+ * The `.gitattributes` rule keeps fresh clones on LF; this repairs the ones already on disk, which that
+ * rule cannot reach. Everywhere else the file is already LF and this is a single read with no temp file.
+ */
+function withLfPatch(patchFile, run) {
+ const raw = fs.readFileSync(patchFile, 'utf8');
+ if (!raw.includes('\r\n')) return run(patchFile);
+
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwebjs-201832-'));
+ try {
+ const lf = path.join(dir, path.basename(patchFile));
+ fs.writeFileSync(lf, raw.replace(/\r\n/g, '\n'));
+ return run(lf);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+
function applyWithGit(wwjsDir, patchFile) {
try {
execFileSync('git', ['-c', 'core.autocrlf=false', 'apply', '-p1', '--reject', '--ignore-whitespace', patchFile], {
@@ -131,8 +159,10 @@ function applyWithGit(wwjsDir, patchFile) {
if (e.status === 1) return;
const detail = e.stderr ? String(e.stderr).trim() : e.message;
const err = new Error(`neither \`patch\` nor \`git apply\` could run (${e.code ?? `exit ${e.status}`}): ${detail}`);
- // ENOENT means git never executed either, so the tree is untouched and degrading is still safe.
- throw e.code === 'ENOENT' ? err : partialTree(err);
+ // Neither of these touched a file, so the tree is untouched and degrading is still safe: ENOENT
+ // means git never executed, and 128 means it refused the input (bad usage, or a diff it could not
+ // parse) before applying anything. A partial write shows up as exit 1, which returned above.
+ throw e.code === 'ENOENT' || e.status === 128 ? err : partialTree(err);
}
}
@@ -187,24 +217,26 @@ function applyBackport(wwjsDir = DEFAULT_WWJS, patchFile = DEFAULT_PATCH) {
// rather than be skipped silently.
// With these, GNU and BSD patch produce byte-identical trees, so a local macOS run faithfully
// reproduces the Debian image build.
- try {
- execFileSync(
- 'patch',
- ['-p1', '-d', wwjsDir, '--no-backup-if-mismatch', '-N', '-f', '-F0', '--ignore-whitespace', '-i', patchFile],
- { stdio: 'pipe' },
- );
- } catch (e) {
- // `patch` exits 1 when hunks reject — expected here (Contact.js hunk #2), and the reject set is
- // verified below. ENOENT means the binary is absent: apply with git instead of leaving the dep
- // unpatched. Anything else (2 = serious trouble) is a real failure: rethrow it rather than let
- // the assertions below misreport it as version skew.
- if (e.code === 'ENOENT') {
- applyWithGit(wwjsDir, patchFile);
- } else if (e.status !== 1) {
- const detail = e.stderr ? String(e.stderr).trim() : e.message;
- throw partialTree(new Error(`\`patch\` failed (${e.code ?? `exit ${e.status}`}): ${detail}`));
+ withLfPatch(patchFile, lfPatch => {
+ try {
+ execFileSync(
+ 'patch',
+ ['-p1', '-d', wwjsDir, '--no-backup-if-mismatch', '-N', '-f', '-F0', '--ignore-whitespace', '-i', lfPatch],
+ { stdio: 'pipe' },
+ );
+ } catch (e) {
+ // `patch` exits 1 when hunks reject — expected here (Contact.js hunk #2), and the reject set is
+ // verified below. ENOENT means the binary is absent: apply with git instead of leaving the dep
+ // unpatched. Anything else (2 = serious trouble) is a real failure: rethrow it rather than let
+ // the assertions below misreport it as version skew.
+ if (e.code === 'ENOENT') {
+ applyWithGit(wwjsDir, lfPatch);
+ } else if (e.status !== 1) {
+ const detail = e.stderr ? String(e.stderr).trim() : e.message;
+ throw partialTree(new Error(`\`patch\` failed (${e.code ?? `exit ${e.status}`}): ${detail}`));
+ }
}
- }
+ });
const artifacts = findArtifacts(wwjsDir);
const unexpected = artifacts.filter(a => !EXPECTED_REJECTS.has(a));
diff --git a/src/engine/adapters/wwebjs-backport-201832.spec.ts b/src/engine/adapters/wwebjs-backport-201832.spec.ts
index 7383c2b29..1551234e4 100644
--- a/src/engine/adapters/wwebjs-backport-201832.spec.ts
+++ b/src/engine/adapters/wwebjs-backport-201832.spec.ts
@@ -269,4 +269,66 @@ describe('patch-wwebjs-201832 (build-time backport of upstream #201832)', () =>
expect(fs.readFileSync(path.join(dir, 'src', 'structures', 'Message.js'), 'utf8')).toContain('this.id = data.id');
});
});
+
+ describe('a Windows checkout of the patch file', () => {
+ /** A PATH holding git and nothing else — the Windows shape: git.exe present, patch.exe absent. */
+ function gitOnlyPath(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-gitonly-'));
+ tmpDirs.push(dir);
+ fs.symlinkSync(execFileSync('which', ['git'], { encoding: 'utf8' }).trim(), path.join(dir, 'git'));
+ return dir;
+ }
+
+ /**
+ * A standalone copy of the patcher beside a patch file of our choosing. DEFAULT_PATCH is resolved
+ * as the script's sibling, so this is exactly how the patcher sees a working tree — including one
+ * git checked out with CRLF. The script pulls in nothing but stdlib, so the copy runs unmodified.
+ */
+ function stageScriptWith(patchContents: string): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-scripts-'));
+ tmpDirs.push(dir);
+ fs.copyFileSync(SCRIPT, path.join(dir, 'patch-wwebjs-201832.js'));
+ fs.writeFileSync(path.join(dir, 'wwebjs-201832.patch'), patchContents);
+ return path.join(dir, 'patch-wwebjs-201832.js');
+ }
+
+ // #889: both appliers reject a patch whose lines end CRLF — a bare \r is not one of the
+ // ' '/'+'/'-'/'@' markers a unified diff allows, and line 7 of this patch is an empty context line,
+ // so both fail exactly there. On Windows core.autocrlf=true checks the file out that way, so the
+ // git fallback added FOR Windows could never run there and `npm install` died on the attempt.
+ it('applies even when the patch file was checked out with CRLF line endings', () => {
+ const dir = copyWwjs();
+ const script = stageScriptWith(fs.readFileSync(PATCH_FILE, 'utf8').replace(/\r?\n/g, '\r\n'));
+
+ const res = spawnSync(process.execPath, [script, dir], {
+ encoding: 'utf8',
+ env: { ...process.env, PATH: gitOnlyPath() },
+ });
+
+ expect(res.stderr).toBe('');
+ expect(res.status).toBe(0);
+ expect(applyBackport(dir)).toEqual({
+ skipped: true,
+ reason: 'installed whatsapp-web.js already normalizes message ids',
+ });
+ });
+
+ // A patch the applier refuses to parse fails BEFORE writing anything, so the tree is pristine and
+ // `--best-effort` must still degrade. Treating that as a half-patched tree is what turned a skippable
+ // install warning into a hard `npm install` failure on every native Windows source install.
+ it('degrades on an unparseable patch instead of failing the install', () => {
+ const dir = copyWwjs();
+ const script = stageScriptWith('this is not a diff\n');
+
+ const res = spawnSync(process.execPath, [script, '--best-effort', dir], {
+ encoding: 'utf8',
+ env: { ...process.env, PATH: gitOnlyPath() },
+ });
+
+ expect(res.status).toBe(0);
+ expect(res.stderr).toMatch(/skipped/);
+ // Nothing was written, which is what makes degrading safe.
+ expect(fs.readFileSync(path.join(dir, 'src', 'structures', 'Message.js'), 'utf8')).toContain('this.id = data.id');
+ });
+ });
});