Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(scripts): replace patched dependency files atomically
Yudhi Armyndharis5ee04b26c53d
diff --git a/Dockerfile b/Dockerfileindex d42a6b1a6..1759c5716 100644--- a/Dockerfile+++ b/Dockerfile@@ -191,7 +191,7 @@ COPY package*.json ./# scripts/postinstall.js rides along so a bare local `npm ci` keeps working, but the# --ignore-scripts install below skips the hook here: the explicit fatal run right# after is the sole (and stricter) applier for the image.-COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js scripts/patch-wwebjs-ready-sync.js scripts/patch-wwebjs-participant-arity.js scripts/patch-wwebjs-block.js scripts/patch-wwebjs-group-description.js scripts/patch-wwebjs-media-id.js scripts/patch-wwebjs-send-error.js scripts/patch-wwebjs-puppeteer.js scripts/patch-baileys-appstate.js scripts/patch-baileys-newsletter-create.js scripts/patch-baileys-pairing.js ./scripts/+COPY scripts/postinstall.js scripts/atomic-write.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js scripts/patch-wwebjs-ready-sync.js scripts/patch-wwebjs-participant-arity.js scripts/patch-wwebjs-block.js scripts/patch-wwebjs-group-description.js scripts/patch-wwebjs-media-id.js scripts/patch-wwebjs-send-error.js scripts/patch-wwebjs-puppeteer.js scripts/patch-baileys-appstate.js scripts/patch-baileys-newsletter-create.js scripts/patch-baileys-pairing.js ./scripts/# Install production dependencies only, then apply the backports. The status patcher runs after# the two patchers it depends on: its transforms were written against the tree they leave behind.diff --git a/scripts/atomic-write.js b/scripts/atomic-write.jsnew file mode 100644index 000000000..a3f637484--- /dev/null+++ b/scripts/atomic-write.js@@ -0,0 +1,55 @@+'use strict';++const fs = require('fs');+const path = require('path');++/**+ * How the dependency patchers replace a file.+ *+ * fs.writeFileSync opens its target and truncates it before it writes, so a write that fails part-way+ * (a full disk, an I/O error) leaves a dependency file cut off, and a later run reads the damage as an+ * unknown upstream shape and skips it. The text goes to a temporary file in the same directory instead+ * and is renamed over the target, which replaces it whole or not at all. Every failure up to and+ * including the rename leaves the target as it was, so a patcher may treat any write error as "this+ * tree was not patched" and `--best-effort` may skip it.+ *+ * A patch that spans several files stages all of them before it replaces the first. If a rename then+ * fails after an earlier one succeeded, the tree is half patched; that error is marked `partial` and+ * `--best-effort` must not skip it.+ */+function writeFilesAtomic(entries) {+ const staged = [];+ try {+ for (const [file, text] of entries) {+ // The real file: a link would otherwise be replaced by a regular file.+ const target = fs.realpathSync(file);+ const temp = path.join(path.dirname(target), `${path.basename(target)}.${process.pid}.tmp`);+ staged.push({ target, temp });+ fs.writeFileSync(temp, text, 'utf8');+ fs.chmodSync(temp, fs.statSync(target).mode & 0o7777);+ }+ staged.forEach(({ target, temp }, replaced) => {+ try {+ fs.renameSync(temp, target);+ } catch (error) {+ error.partial = replaced > 0;+ throw error;+ }+ });+ } finally {+ // A renamed temp is gone already; a failed one must not outlive the run. Never mask the error.+ for (const { temp } of staged) {+ try {+ fs.rmSync(temp, { force: true });+ } catch {+ // nothing more can be done about a temp file that cannot be removed+ }+ }+ }+}++function writeFileAtomic(file, text) {+ writeFilesAtomic([[file, text]]);+}++module.exports = { writeFileAtomic, writeFilesAtomic };diff --git a/scripts/dockerfile-patchers.spec.js b/scripts/dockerfile-patchers.spec.jsindex 270f16b70..46f901abd 100644--- a/scripts/dockerfile-patchers.spec.js+++ b/scripts/dockerfile-patchers.spec.js@@ -52,6 +52,21 @@ test('every patcher is COPIED into the production stage', () => {assert.deepEqual(missing, [], `not copied into the image: ${missing.join(', ')}`);});+test('every sibling module a patcher requires is COPIED into the production stage', () => {+ // A patcher that needs ./atomic-write.js fails with MODULE_NOT_FOUND in the image build when only the+ // patcher itself was copied. Derive the modules from the patchers' own require calls.+ const needed = new Set(+ patchers.flatMap(p =>+ [...fs.readFileSync(path.join(__dirname, p), 'utf8').matchAll(/require\('\.\/([\w-]+)(?:\.js)?'\)/g)].map(+ match => `scripts/${match[1]}.js`,+ ),+ ),+ );+ assert.ok(needed.has('scripts/atomic-write.js'), 'the fixture did not find the shared write helper');+ const missing = [...needed].filter(file => !copied.includes(file));+ assert.deepEqual(missing, [], `required by a patcher but not copied into the image: ${missing.join(', ')}`);+});+test('every patcher is RUN fatally after npm ci', () => {// The postinstall hook runs them --best-effort; the explicit run is the real gate, so a shape// change fails the image build instead of shipping unpatched.diff --git a/scripts/patch-baileys-appstate.js b/scripts/patch-baileys-appstate.jsindex fdb2355c8..e1005b523 100644--- a/scripts/patch-baileys-appstate.js+++ b/scripts/patch-baileys-appstate.js@@ -26,6 +26,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_BAILEYS = path.join(__dirname, '..', 'node_modules', '@whiskeysockets', 'baileys');const CHATS_PATH = path.join('lib', 'Socket', 'chats.js');@@ -66,14 +67,7 @@ function applyAppStatePatch(baileysDir = DEFAULT_BAILEYS) {'the upstream shape changed; re-check whether the loop is still unbounded before removing this patcher',);}- try {- fs.writeFileSync(file, source.replace(LOOP_FIND, LOOP_REPLACE), 'utf8');- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(file, source.replace(LOOP_FIND, LOOP_REPLACE));return { note: 'bounded the app-state resync loop on an empty decode' };}@@ -83,7 +77,7 @@ function run() {const result = applyAppStatePatch();console.log(`patch-baileys-appstate: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-baileys-appstate: skipped — ${error.message}`);return;}diff --git a/scripts/patch-baileys-newsletter-create.js b/scripts/patch-baileys-newsletter-create.jsindex 5d464f397..9d1ed9da8 100644--- a/scripts/patch-baileys-newsletter-create.js+++ b/scripts/patch-baileys-newsletter-create.js@@ -36,6 +36,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_BAILEYS = path.join(__dirname, '..', 'node_modules', '@whiskeysockets', 'baileys');const NEWSLETTER_PATH = path.join('lib', 'Socket', 'newsletter.js');@@ -95,14 +96,7 @@ function applyNewsletterCreatePatch(baileysDir = DEFAULT_BAILEYS) {'before removing this patcher',);}- try {- fs.writeFileSync(file, source.replace(PARSE_FIND, PARSE_REPLACE), 'utf8');- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(file, source.replace(PARSE_FIND, PARSE_REPLACE));return { note: 'made the newsletter-create parse tolerate an absent picture, keeping the new channel id' };}@@ -112,7 +106,7 @@ function run() {const result = applyNewsletterCreatePatch();console.log(`patch-baileys-newsletter-create: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-baileys-newsletter-create: skipped — ${error.message}`);return;}diff --git a/scripts/patch-baileys-pairing.js b/scripts/patch-baileys-pairing.jsindex 3e4170eb4..c7dcf1083 100644--- a/scripts/patch-baileys-pairing.js+++ b/scripts/patch-baileys-pairing.js@@ -15,6 +15,7 @@'use strict';const fs = require('fs');const path = require('path');+const { writeFilesAtomic } = require('./atomic-write');const DEFAULT_BAILEYS = path.join(__dirname, '..', 'node_modules', '@whiskeysockets', 'baileys');const QR_FIND = String.raw` // QR genws.on('CB:iq,type:set,pair-device', async (stanza) => {@@ -147,13 +148,9 @@ function applyPairingPatch(dir = DEFAULT_BAILEYS) {error.partial = items.some(item => item.state === 'applied');throw error;}- try {- for (const item of items) fs.writeFileSync(item.file, item.source.replace(item.find, item.replace));- } catch (error) {- // A failed write may have left part of either file; best-effort cannot accept that tree.- error.partial = true;- throw error;- }+ // Both files are staged before the first is replaced, so a failed write leaves the tree as it was. Only+ // a rename that fails after the first one went through leaves half a patch, and is marked partial.+ writeFilesAtomic(items.map(item => [item.file, item.source.replace(item.find, item.replace)]));return { skipped: false };}function run(dir = DEFAULT_BAILEYS, bestEffort = process.argv.includes('--best-effort')) {diff --git a/scripts/patch-baileys-pairing.spec.js b/scripts/patch-baileys-pairing.spec.jsindex d784d5363..230e612d9 100644--- a/scripts/patch-baileys-pairing.spec.js+++ b/scripts/patch-baileys-pairing.spec.js@@ -66,13 +66,25 @@ test('best-effort skips unknown shapes but refuses partial patches', t => {fs.writeFileSync(file, ACK_REPLACE);assert.equal(run(dir, true), 1);});-test('best-effort still fails if a validated patch cannot finish writing', t => {+test('best-effort skips and changes nothing when a validated patch cannot be written', t => {const dir = fixture(t);const write = fs.writeFileSync;t.mock.method(fs, 'writeFileSync', (file, data) => {- if (file.endsWith('messages-recv.js')) throw new Error('write failed');+ if (file.includes('messages-recv.js')) throw new Error('write failed');return write(file, data);});+ assert.equal(run(dir, true), 0);+ assert.equal(run(dir, false), 1);+ assert.equal(isApplied(dir), false);+ assert.ok(fs.readFileSync(path.join(dir, 'lib/Socket/socket.js'), 'utf8').includes(QR_FIND));+});+test('best-effort still fails if only part of a validated patch was written', t => {+ const dir = fixture(t);+ const rename = fs.renameSync;+ t.mock.method(fs, 'renameSync', (from, to) => {+ if (to.endsWith('messages-recv.js')) throw new Error('rename failed');+ return rename(from, to);+ });assert.equal(run(dir, true), 1);assert.equal(isApplied(dir), false);});diff --git a/scripts/patch-write-failure.spec.js b/scripts/patch-write-failure.spec.jsindex 1dfd847a8..2d5d395e4 100644--- a/scripts/patch-write-failure.spec.js+++ b/scripts/patch-write-failure.spec.js@@ -8,10 +8,11 @@ const path = require('node:path');const { spawnSync } = require('node:child_process');/**- * `--best-effort` lets a source install carry on without a patch it cannot place. A write that fails- * part-way is not that case: fs.writeFileSync has already truncated the target, so the dependency is- * left broken and no later run can tell. Each patcher must exit non-zero then. An open that is refused- * writes nothing, and is skipped like any other tree the patcher cannot change.+ * `--best-effort` lets a source install carry on without a patch it cannot place. The patchers replace a+ * file by writing a temporary file beside it and renaming that over the target, so whatever fails on the+ * way (a full disk, an I/O error, a refused or busy open, a refused rename) leaves the target as it was,+ * and the patcher skips under --best-effort and fails without it. Only a patch over several files can be+ * left half done, when a rename fails after an earlier one went through; that one fails the install.*/// realpath: os.tmpdir() is a symlink on macOS and the patcher resolves its own location through it,@@ -22,22 +23,34 @@ test.after(() => fs.rmSync(WORK, { recursive: true, force: true }));const PREFIX_BYTES = 64;const MARKER = 'FIXTURE_WRITE_FAULT';const PRELOAD = path.join(WORK, 'write-fault.cjs');+// Fails one write ('write': the temporary file beside FIXTURE_FAULT_FILE, or the file itself) or one+// rename ('rename': onto FIXTURE_FAULT_FILE). A full disk or an I/O error lands a prefix first; a refused+// or busy open writes nothing.fs.writeFileSync(PRELOAD,`'use strict';const fs = require('node:fs');const path = require('node:path');const write = fs.writeFileSync;-const target = path.resolve(process.env.FIXTURE_WRITE_TARGET);-const code = process.env.FIXTURE_WRITE_FAULT;-fs.writeFileSync = function (file, data, ...args) {- if (typeof file !== 'number' && path.resolve(String(file)) === target) {- // A refused open writes nothing; any other failure lands a prefix first, as a full disk does.- if (code !== 'EACCES') write.call(fs, file, Buffer.from(String(data)).subarray(0, ${PREFIX_BYTES}));- process.stderr.write('${MARKER}\\n');- throw Object.assign(new Error('fixture write failure'), { code });+const rename = fs.renameSync;+const op = process.env.FIXTURE_FAULT_OP;+const file = path.resolve(process.env.FIXTURE_FAULT_FILE);+const code = process.env.FIXTURE_FAULT_CODE;+const fail = () => {+ process.stderr.write('${MARKER}\\n');+ throw Object.assign(new Error('fixture failure'), { code });+};+fs.writeFileSync = function (target, data, ...args) {+ const resolved = typeof target === 'number' ? '' : path.resolve(String(target));+ if (op === 'write' && (resolved === file || resolved.startsWith(file + '.'))) {+ if (['ENOSPC', 'EIO'].includes(code)) write.call(fs, target, Buffer.from(String(data)).subarray(0, ${PREFIX_BYTES}));+ fail();}- return write.call(fs, file, data, ...args);+ return write.call(fs, target, data, ...args);+};+fs.renameSync = function (from, to) {+ if (op === 'rename' && path.resolve(String(to)) === file) fail();+ return rename.call(fs, from, to);};`,);@@ -68,56 +81,161 @@ const PATCHERS = [],];-function fixture(name, relative, content) {+function fixture(name, files) {const root = fs.mkdtempSync(path.join(WORK, 'tree-'));const script = path.join(root, 'scripts', name);- const target = path.join(root, 'node_modules', relative);fs.mkdirSync(path.dirname(script), { recursive: true });- fs.mkdirSync(path.dirname(target), { recursive: true });fs.copyFileSync(path.join(__dirname, name), script);- fs.writeFileSync(target, content);- return { root, script, target };+ // The shared write helper sits beside the patchers (the image copies it with them).+ fs.copyFileSync(path.join(__dirname, 'atomic-write.js'), path.join(root, 'scripts', 'atomic-write.js'));+ const targets = {};+ for (const [relative, content] of Object.entries(files)) {+ const target = path.join(root, 'node_modules', relative);+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(target, content, { mode: 0o640 });+ targets[relative] = target;+ }+ return { root, script, targets };}-function patch({ root, script, target }, fault) {- const result = spawnSync(process.execPath, [...(fault ? ['--require', PRELOAD] : []), script, '--best-effort'], {- cwd: root,- env: { PATH: process.env.PATH, FIXTURE_WRITE_TARGET: target, FIXTURE_WRITE_FAULT: fault },- encoding: 'utf8',- timeout: 10000,- });+// fault: { op: 'write' | 'rename', file: absolute path, code }.+function patch({ root, script }, { fault, bestEffort = true } = {}) {+ const result = spawnSync(+ process.execPath,+ [...(fault ? ['--require', PRELOAD] : []), script, ...(bestEffort ? ['--best-effort'] : [])],+ {+ cwd: root,+ env: {+ PATH: process.env.PATH,+ ...(fault && {+ FIXTURE_FAULT_OP: fault.op,+ FIXTURE_FAULT_FILE: fault.file,+ FIXTURE_FAULT_CODE: fault.code,+ }),+ },+ encoding: 'utf8',+ timeout: 10000,+ },+ );assert.equal(result.error, undefined);return result;}+const leftovers = tree =>+ Object.values(tree.targets).flatMap(target =>+ fs.readdirSync(path.dirname(target)).filter(entry => entry.endsWith('.tmp')),+ );++// A failure at any step of the replacement; every one leaves the target as it was.+const FAULTS = [+ ['a full disk while writing', 'write', 'ENOSPC'],+ ['an open that is busy', 'write', 'EBUSY'],+ ['a refused rename', 'rename', 'EACCES'],+];+for (const [name, relative, shapeOf] of PATCHERS) {const shape = `// fixture\n${shapeOf(require(`./${name}`))}\n`;- test(`${name} patches a recognised tree`, () => {- const tree = fixture(name, relative, shape);+ test(`${name} patches a recognised tree, keeps its mode and leaves no temporary file`, () => {+ const tree = fixture(name, { [relative]: shape });+ const target = tree.targets[relative];assert.equal(patch(tree).status, 0);- assert.notEqual(fs.readFileSync(tree.target, 'utf8'), shape);+ assert.notEqual(fs.readFileSync(target, 'utf8'), shape);+ assert.equal(fs.statSync(target).mode & 0o777, 0o640);+ assert.deepEqual(leftovers(tree), []);});test(`${name} skips an unrecognised tree under --best-effort`, () => {- const tree = fixture(name, relative, 'unknown source shape\n');+ const tree = fixture(name, { [relative]: 'unknown source shape\n' });assert.equal(patch(tree).status, 0);- assert.equal(fs.readFileSync(tree.target, 'utf8'), 'unknown source shape\n');+ assert.equal(fs.readFileSync(tree.targets[relative], 'utf8'), 'unknown source shape\n');});- test(`${name} fails when the write breaks part-way, even under --best-effort`, () => {- const tree = fixture(name, relative, shape);- const result = patch(tree, 'ENOSPC');- assert.match(result.stderr, new RegExp(MARKER), 'the injected fault did not fire');- assert.equal(fs.statSync(tree.target).size, PREFIX_BYTES, 'the target keeps only the written prefix');- assert.notEqual(result.status, 0);- });+ for (const [label, op, code] of FAULTS) {+ test(`${name} skips under --best-effort and fails without it on ${label}, leaving the file as it was`, () => {+ for (const bestEffort of [true, false]) {+ const tree = fixture(name, { [relative]: shape });+ const fault = { op, code, file: tree.targets[relative] };+ const result = patch(tree, { fault, bestEffort });+ assert.match(result.stderr, new RegExp(MARKER), 'the injected fault did not fire');+ assert.equal(fs.readFileSync(tree.targets[relative], 'utf8'), shape);+ assert.deepEqual(leftovers(tree), []);+ assert.equal(result.status, bestEffort ? 0 : 1, result.stderr);+ if (bestEffort) assert.match(result.stderr, /skipped/);+ }+ });+ }+}- test(`${name} skips a file it is not permitted to write under --best-effort`, () => {- const tree = fixture(name, relative, shape);- const result = patch(tree, 'EACCES');- assert.match(result.stderr, new RegExp(MARKER), 'the injected fault did not fire');- assert.equal(fs.readFileSync(tree.target, 'utf8'), shape);- assert.equal(result.status, 0);+// The Baileys pairing patch spans two files: staged together, replaced one after the other.+const pairing = require('./patch-baileys-pairing.js');+const SOCKET = '@whiskeysockets/baileys/lib/Socket/socket.js';+const RECV = '@whiskeysockets/baileys/lib/Socket/messages-recv.js';+const pairingTree = () =>+ fixture('patch-baileys-pairing.js', {+ [SOCKET]: `// fixture\n${pairing.QR_FIND}\n`,+ [RECV]: `// fixture\n${pairing.ACK_FIND}\n`,});++test('patch-baileys-pairing.js patches both files and leaves no temporary file', () => {+ const tree = pairingTree();+ assert.equal(patch(tree).status, 0);+ assert.ok(fs.readFileSync(tree.targets[SOCKET], 'utf8').includes(pairing.QR_REPLACE));+ assert.ok(fs.readFileSync(tree.targets[RECV], 'utf8').includes(pairing.ACK_REPLACE));+ assert.deepEqual(leftovers(tree), []);+});++for (const [label, op, code] of FAULTS) {+ for (const faulty of [SOCKET, RECV]) {+ // Whichever file the failure hits before anything is replaced, both stay as they were.+ if (op === 'rename' && faulty === RECV) continue;+ test(`patch-baileys-pairing.js skips under --best-effort on ${label} for ${path.basename(faulty)}`, () => {+ for (const bestEffort of [true, false]) {+ const tree = pairingTree();+ const before = Object.values(tree.targets).map(file => fs.readFileSync(file, 'utf8'));+ const result = patch(tree, { fault: { op, code, file: tree.targets[faulty] }, bestEffort });+ assert.match(result.stderr, new RegExp(MARKER), 'the injected fault did not fire');+ assert.deepEqual(+ Object.values(tree.targets).map(file => fs.readFileSync(file, 'utf8')),+ before,+ );+ assert.deepEqual(leftovers(tree), []);+ assert.equal(result.status, bestEffort ? 0 : 1, result.stderr);+ }+ });+ }}++test('patch-baileys-pairing.js fails even under --best-effort when only the first file was replaced', () => {+ const tree = pairingTree();+ const result = patch(tree, { fault: { op: 'rename', code: 'EBUSY', file: tree.targets[RECV] } });+ assert.match(result.stderr, new RegExp(MARKER), 'the injected fault did not fire');+ assert.ok(fs.readFileSync(tree.targets[SOCKET], 'utf8').includes(pairing.QR_REPLACE), 'the first file is patched');+ assert.ok(fs.readFileSync(tree.targets[RECV], 'utf8').includes(pairing.ACK_FIND), 'the second file is not');+ assert.deepEqual(leftovers(tree), []);+ assert.equal(result.status, 1);+});++// The Puppeteer patch has no --best-effort mode: any failure is fatal, and leaves the file untouched.+const puppeteer = require('./patch-wwebjs-puppeteer.js');+test('patch-wwebjs-puppeteer.js fails on a write error and leaves Client.js as it was', () => {+ const relative = 'whatsapp-web.js/src/Client.js';+ const shape = `// fixture\n${puppeteer.REPLACEMENTS.map(([before]) => before).join('\n')}\n`;+ const tree = fixture('patch-wwebjs-puppeteer.js', { [relative]: shape });+ const result = patch(tree, { fault: { op: 'write', code: 'ENOSPC', file: tree.targets[relative] } });+ assert.match(result.stderr, new RegExp(MARKER), 'the injected fault did not fire');+ assert.equal(fs.readFileSync(tree.targets[relative], 'utf8'), shape);+ assert.deepEqual(leftovers(tree), []);+ assert.equal(result.status, 1);+});++test('a link is written through, not replaced', () => {+ const { writeFileAtomic } = require('./atomic-write.js');+ const real = path.join(WORK, 'real.txt');+ const link = path.join(WORK, 'link.txt');+ fs.writeFileSync(real, 'old');+ fs.symlinkSync(real, link);+ writeFileAtomic(link, 'new');+ assert.ok(fs.lstatSync(link).isSymbolicLink());+ assert.equal(fs.readFileSync(real, 'utf8'), 'new');+});diff --git a/scripts/patch-wwebjs-block.js b/scripts/patch-wwebjs-block.jsindex 6120a8da0..bcd37bdb6 100644--- a/scripts/patch-wwebjs-block.js+++ b/scripts/patch-wwebjs-block.js@@ -46,6 +46,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const CONTACT_PATH = path.join('src', 'structures', 'Contact.js');@@ -181,14 +182,7 @@ function applyBlockPatches({ wwjsDir = DEFAULT_WWJS } = {}) {}if (applied.length > 0) {- try {- fs.writeFileSync(contactFile, source);- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(contactFile, source);}return { applied, skipped };}@@ -203,7 +197,7 @@ function run() {].join('; ');console.log(`patch-wwebjs-block: ${report}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-block: skipped, ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-group-description.js b/scripts/patch-wwebjs-group-description.jsindex 1b20382c7..4cbdb8c66 100644--- a/scripts/patch-wwebjs-group-description.js+++ b/scripts/patch-wwebjs-group-description.js@@ -33,6 +33,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const GROUP_CHAT_PATH = path.join('src', 'structures', 'GroupChat.js');@@ -97,14 +98,7 @@ function applyGroupDescriptionFix(wwjsDir = DEFAULT_WWJS) {);}- try {- fs.writeFileSync(groupChatFile, source.replace(POSITIONAL_CALL, OPTIONS_CALL));- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(groupChatFile, source.replace(POSITIONAL_CALL, OPTIONS_CALL));return { skipped: false, note: 'group description job called with an options object' };}@@ -114,7 +108,7 @@ function run() {const result = applyGroupDescriptionFix();console.log(`patch-wwebjs-group-description: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-group-description: skipped — ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-media-id.js b/scripts/patch-wwebjs-media-id.jsindex 586d2dce7..3b990dd70 100644--- a/scripts/patch-wwebjs-media-id.js+++ b/scripts/patch-wwebjs-media-id.js@@ -17,6 +17,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const UTILS_PATH = path.join('src', 'util', 'Injected', 'Utils.js');@@ -51,14 +52,7 @@ function applyBackport(wwjsDir = DEFAULT_WWJS) {);}- try {- fs.writeFileSync(utilsFile, source.replace(ANCHOR, FIX + ANCHOR));- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(utilsFile, source.replace(ANCHOR, FIX + ANCHOR));return { skipped: false, note: 'media model id stripped from outgoing messages' };}@@ -81,7 +75,7 @@ function run() {const result = applyBackport();console.log(`patch-wwebjs-media-id: ${result.skipped ? `skipped: ${result.reason}` : result.note}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-media-id: skipped: ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-newsletter-preview.js b/scripts/patch-wwebjs-newsletter-preview.jsindex c031a8ec4..22da9fd5b 100644--- a/scripts/patch-wwebjs-newsletter-preview.js+++ b/scripts/patch-wwebjs-newsletter-preview.js@@ -12,6 +12,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const UTILS_PATH = path.join('src', 'util', 'Injected', 'Utils.js');@@ -47,14 +48,7 @@ function applyBackport(wwjsDir = DEFAULT_WWJS) {);}- try {- fs.writeFileSync(utilsFile, source.replace(LEGACY_CALL, CONTEXT_CALL));- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(utilsFile, source.replace(LEGACY_CALL, CONTEXT_CALL));return { skipped: false, note: 'destination chat context added to link previews' };}@@ -79,7 +73,7 @@ function run() {`patch-wwebjs-newsletter-preview: ${result.skipped ? `skipped — ${result.reason}` : result.note}`,);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-newsletter-preview: skipped — ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-participant-arity.js b/scripts/patch-wwebjs-participant-arity.jsindex 1b00ba6d7..461c8e05b 100644--- a/scripts/patch-wwebjs-participant-arity.js+++ b/scripts/patch-wwebjs-participant-arity.js@@ -31,6 +31,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const GROUP_CHAT_PATH = path.join('src', 'structures', 'GroupChat.js');@@ -176,14 +177,7 @@ function applyParticipantArityPatches(wwjsDir = DEFAULT_WWJS) {}if (applied.length) {- try {- fs.writeFileSync(groupChatFile, source);- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(groupChatFile, source);}return { applied, skipped };}@@ -198,7 +192,7 @@ function run() {].join('; ');console.log(`patch-wwebjs-participant-arity: ${report}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-participant-arity: skipped — ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-puppeteer.js b/scripts/patch-wwebjs-puppeteer.jsindex a8e6221c3..c99bf3527 100644--- a/scripts/patch-wwebjs-puppeteer.js+++ b/scripts/patch-wwebjs-puppeteer.js@@ -3,6 +3,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const REPLACEMENTS = [@@ -26,7 +27,7 @@ function applyPatch(wwjsDir = DEFAULT_WWJS) {throw new Error('unsupported Client.js shape; recheck Puppeteer browser teardown compatibility');}for (const [before, after] of REPLACEMENTS) source = source.replace(before, after);- fs.writeFileSync(file, source);+ writeFileAtomic(file, source);return { skipped: false };}diff --git a/scripts/patch-wwebjs-ready-sync.js b/scripts/patch-wwebjs-ready-sync.jsindex 339ad455d..374c70bad 100644--- a/scripts/patch-wwebjs-ready-sync.js+++ b/scripts/patch-wwebjs-ready-sync.js@@ -29,6 +29,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const CLIENT_PATH = path.join('src', 'Client.js');@@ -115,14 +116,7 @@ function applyReadySyncPatch(wwjsDir = DEFAULT_WWJS) {for (const edit of EDITS) {source = source.replace(edit.find, edit.replace);}- try {- fs.writeFileSync(clientFile, source);- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(clientFile, source);return { skipped: false, note: 'readiness marker and hasSynced level-check applied' };}throw new Error(@@ -137,7 +131,7 @@ function run() {const result = applyReadySyncPatch();console.log(`patch-wwebjs-ready-sync: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-ready-sync: skipped — ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-ready-sync.spec.js b/scripts/patch-wwebjs-ready-sync.spec.jsindex 166d15328..7896e1cec 100644--- a/scripts/patch-wwebjs-ready-sync.spec.js+++ b/scripts/patch-wwebjs-ready-sync.spec.js@@ -96,6 +96,7 @@ test('CLI: unrecognised tree exits 1 bare and 0 under --best-effort', () => {fs.mkdirSync(path.join(root, 'scripts'));const script = path.join(root, 'scripts', 'patch-wwebjs-ready-sync.js');fs.copyFileSync(path.join(__dirname, 'patch-wwebjs-ready-sync.js'), script);+ fs.copyFileSync(path.join(__dirname, 'atomic-write.js'), path.join(path.dirname(script), 'atomic-write.js'));const clientDir = path.join(root, 'node_modules', 'whatsapp-web.js', 'src');fs.mkdirSync(clientDir, { recursive: true });fs.writeFileSync(path.join(clientDir, 'Client.js'), 'class Client {}\n');diff --git a/scripts/patch-wwebjs-send-error.js b/scripts/patch-wwebjs-send-error.jsindex 40b9fbc39..1a05d4901 100644--- a/scripts/patch-wwebjs-send-error.js+++ b/scripts/patch-wwebjs-send-error.js@@ -33,6 +33,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const CLIENT_PATH = path.join('src', 'Client.js');@@ -157,14 +158,7 @@ function applyBackport(wwjsDir = DEFAULT_WWJS) {);}- try {- fs.writeFileSync(clientFile, source.replace(ANCHOR, FIX));- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(clientFile, source.replace(ANCHOR, FIX));return { skipped: false, note: 'page-side send errors now carry what the page threw' };}@@ -187,7 +181,7 @@ function run() {const result = applyBackport();console.log(`patch-wwebjs-send-error: ${result.skipped ? `skipped: ${result.reason}` : result.note}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-send-error: skipped: ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-send-error.spec.js b/scripts/patch-wwebjs-send-error.spec.jsindex 20c658e07..133434a55 100644--- a/scripts/patch-wwebjs-send-error.spec.js+++ b/scripts/patch-wwebjs-send-error.spec.js@@ -102,6 +102,7 @@ test('fails the CLI on an unknown shape without --best-effort, and only warns wiconst script = path.join(root, 'scripts', 'patch-wwebjs-send-error.js');fs.mkdirSync(path.dirname(script));fs.copyFileSync(path.join(__dirname, 'patch-wwebjs-send-error.js'), script);+ fs.copyFileSync(path.join(__dirname, 'atomic-write.js'), path.join(path.dirname(script), 'atomic-write.js'));const client = path.join(root, 'node_modules', 'whatsapp-web.js', 'src', 'Client.js');fs.mkdirSync(path.dirname(client), { recursive: true });fs.writeFileSync(client, 'not the shape\n');diff --git a/scripts/patch-wwebjs-status.js b/scripts/patch-wwebjs-status.jsindex 57fabc411..424ab4be5 100644--- a/scripts/patch-wwebjs-status.js+++ b/scripts/patch-wwebjs-status.js@@ -31,6 +31,7 @@const fs = require('fs');const path = require('path');+const { writeFileAtomic } = require('./atomic-write');const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');const UTILS_PATH = path.join('src', 'util', 'Injected', 'Utils.js');@@ -170,14 +171,7 @@ function applyStatusPatches(wwjsDir = DEFAULT_WWJS) {}if (applied.length) {- try {- fs.writeFileSync(utilsFile, source);- } catch (error) {- // The write truncates before it writes, so a failure after the open leaves a partial file, which- // --best-effort must not skip. A refused open leaves the tree as it was.- error.partial = !['EACCES', 'EPERM', 'EROFS'].includes(error.code);- throw error;- }+ writeFileAtomic(utilsFile, source);}return { applied, skipped };}@@ -192,7 +186,7 @@ function run() {].join('; ');console.log(`patch-wwebjs-status: ${report}`);} catch (error) {- if (bestEffort && !error.partial) {+ if (bestEffort) {console.warn(`patch-wwebjs-status: skipped — ${error.message}`);return;}diff --git a/scripts/patch-wwebjs-status.spec.js b/scripts/patch-wwebjs-status.spec.jsindex 97dff2d9e..76840fd24 100644--- a/scripts/patch-wwebjs-status.spec.js+++ b/scripts/patch-wwebjs-status.spec.js@@ -165,6 +165,7 @@ test('CLI: unrecognised tree exits 1 bare and 0 under --best-effort', () => {fs.mkdirSync(path.join(root, 'scripts'));const script = path.join(root, 'scripts', 'patch-wwebjs-status.js');fs.copyFileSync(path.join(__dirname, 'patch-wwebjs-status.js'), script);+ fs.copyFileSync(path.join(__dirname, 'atomic-write.js'), path.join(path.dirname(script), 'atomic-write.js'));const utilsDir = path.join(root, 'node_modules', 'whatsapp-web.js', 'src', 'util', 'Injected');fs.mkdirSync(utilsDir, { recursive: true });fs.writeFileSync(path.join(utilsDir, 'Utils.js'), 'exports.x = () => {};\n');