ci: fix node path and lint warnings
This commit is contained in:
3
.github/workflows/ci.yml
vendored
3
.github/workflows/ci.yml
vendored
@@ -34,13 +34,12 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
env:
|
env:
|
||||||
CI: true
|
CI: true
|
||||||
NPM_CONFIG_ENGINE_STRICT: "false"
|
|
||||||
run: |
|
run: |
|
||||||
export PATH="$NODE_BIN:$PATH"
|
export PATH="$NODE_BIN:$PATH"
|
||||||
which node
|
which node
|
||||||
node -v
|
node -v
|
||||||
pnpm -v
|
pnpm -v
|
||||||
pnpm install --no-frozen-lockfile --ignore-scripts=false
|
pnpm install --ignore-scripts=false --config.engine-strict=false --config.enable-pre-post-scripts=true || pnpm install --ignore-scripts=false --config.engine-strict=false --config.enable-pre-post-scripts=true
|
||||||
|
|
||||||
- name: Lint
|
- name: Lint
|
||||||
run: pnpm lint
|
run: pnpm lint
|
||||||
|
|||||||
@@ -104,7 +104,9 @@ export function parseClaudeJson(
|
|||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(candidate);
|
const parsed = JSON.parse(candidate);
|
||||||
if (firstParsed === undefined) firstParsed = parsed;
|
if (firstParsed === undefined) firstParsed = parsed;
|
||||||
let validation;
|
let validation:
|
||||||
|
| z.SafeParseReturnType<unknown, z.infer<typeof ClaudeJsonSchema>>
|
||||||
|
| { success: false };
|
||||||
try {
|
try {
|
||||||
validation = ClaudeJsonSchema.safeParse(parsed);
|
validation = ClaudeJsonSchema.safeParse(parsed);
|
||||||
} catch {
|
} catch {
|
||||||
@@ -131,7 +133,9 @@ export function parseClaudeJson(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (firstParsed !== undefined) {
|
if (firstParsed !== undefined) {
|
||||||
let validation;
|
let validation:
|
||||||
|
| z.SafeParseReturnType<unknown, z.infer<typeof ClaudeJsonSchema>>
|
||||||
|
| { success: false };
|
||||||
try {
|
try {
|
||||||
validation = ClaudeJsonSchema.safeParse(firstParsed);
|
validation = ClaudeJsonSchema.safeParse(firstParsed);
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -49,7 +49,9 @@ const ReplySchema = z
|
|||||||
mediaUrl: z.string().optional(),
|
mediaUrl: z.string().optional(),
|
||||||
session: z
|
session: z
|
||||||
.object({
|
.object({
|
||||||
scope: z.union([z.literal("per-sender"), z.literal("global")]).optional(),
|
scope: z
|
||||||
|
.union([z.literal("per-sender"), z.literal("global")])
|
||||||
|
.optional(),
|
||||||
resetTriggers: z.array(z.string()).optional(),
|
resetTriggers: z.array(z.string()).optional(),
|
||||||
idleMinutes: z.number().int().positive().optional(),
|
idleMinutes: z.number().int().positive().optional(),
|
||||||
store: z.string().optional(),
|
store: z.string().optional(),
|
||||||
@@ -70,7 +72,8 @@ const ReplySchema = z
|
|||||||
.refine(
|
.refine(
|
||||||
(val) => (val.mode === "text" ? Boolean(val.text) : Boolean(val.command)),
|
(val) => (val.mode === "text" ? Boolean(val.text) : Boolean(val.command)),
|
||||||
{
|
{
|
||||||
message: "reply.text is required for mode=text; reply.command is required for mode=command",
|
message:
|
||||||
|
"reply.text is required for mode=text; reply.command is required for mode=command",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -93,7 +96,9 @@ export function loadConfig(): WarelayConfig {
|
|||||||
const validated = WarelaySchema.safeParse(parsed);
|
const validated = WarelaySchema.safeParse(parsed);
|
||||||
if (!validated.success) {
|
if (!validated.success) {
|
||||||
console.error("Invalid warelay config:");
|
console.error("Invalid warelay config:");
|
||||||
validated.error.issues.forEach((iss) => console.error(`- ${iss.path.join(".")}: ${iss.message}`));
|
for (const iss of validated.error.issues) {
|
||||||
|
console.error(`- ${iss.path.join(".")}: ${iss.message}`);
|
||||||
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
return validated.data as WarelayConfig;
|
return validated.data as WarelayConfig;
|
||||||
|
|||||||
@@ -38,15 +38,15 @@ vi.mock("qrcode-terminal", () => ({
|
|||||||
generate: vi.fn(),
|
generate: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
import { monitorWebProvider } from "./index.js";
|
||||||
import {
|
import {
|
||||||
createWaSocket,
|
createWaSocket,
|
||||||
loginWeb,
|
loginWeb,
|
||||||
monitorWebInbox,
|
|
||||||
logWebSelfId,
|
logWebSelfId,
|
||||||
|
monitorWebInbox,
|
||||||
sendMessageWeb,
|
sendMessageWeb,
|
||||||
waitForWaConnection,
|
waitForWaConnection,
|
||||||
} from "./provider-web.js";
|
} from "./provider-web.js";
|
||||||
import { monitorWebProvider } from "./index.js";
|
|
||||||
|
|
||||||
const baileys = (await import(
|
const baileys = (await import(
|
||||||
"@whiskeysockets/baileys"
|
"@whiskeysockets/baileys"
|
||||||
@@ -87,8 +87,9 @@ describe("provider-web", () => {
|
|||||||
expect.objectContaining({ printQRInTerminal: false }),
|
expect.objectContaining({ printQRInTerminal: false }),
|
||||||
);
|
);
|
||||||
const passed = makeWASocket.mock.calls[0][0];
|
const passed = makeWASocket.mock.calls[0][0];
|
||||||
const passedLogger = (passed as { logger?: { level?: string; trace?: unknown } })
|
const passedLogger = (
|
||||||
.logger;
|
passed as { logger?: { level?: string; trace?: unknown } }
|
||||||
|
).logger;
|
||||||
expect(passedLogger?.level).toBe("silent");
|
expect(passedLogger?.level).toBe("silent");
|
||||||
expect(typeof passedLogger?.trace).toBe("function");
|
expect(typeof passedLogger?.trace).toBe("function");
|
||||||
const sock = getLastSocket();
|
const sock = getLastSocket();
|
||||||
@@ -173,10 +174,18 @@ describe("provider-web", () => {
|
|||||||
expect.objectContaining({ body: "ping", from: "+999", to: "+123" }),
|
expect.objectContaining({ body: "ping", from: "+999", to: "+123" }),
|
||||||
);
|
);
|
||||||
expect(sock.readMessages).toHaveBeenCalledWith([
|
expect(sock.readMessages).toHaveBeenCalledWith([
|
||||||
{ remoteJid: "999@s.whatsapp.net", id: "abc", participant: undefined, fromMe: false },
|
{
|
||||||
|
remoteJid: "999@s.whatsapp.net",
|
||||||
|
id: "abc",
|
||||||
|
participant: undefined,
|
||||||
|
fromMe: false,
|
||||||
|
},
|
||||||
]);
|
]);
|
||||||
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
|
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("available");
|
||||||
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith("composing", "999@s.whatsapp.net");
|
expect(sock.sendPresenceUpdate).toHaveBeenCalledWith(
|
||||||
|
"composing",
|
||||||
|
"999@s.whatsapp.net",
|
||||||
|
);
|
||||||
expect(sock.sendMessage).toHaveBeenCalledWith("999@s.whatsapp.net", {
|
expect(sock.sendMessage).toHaveBeenCalledWith("999@s.whatsapp.net", {
|
||||||
text: "pong",
|
text: "pong",
|
||||||
});
|
});
|
||||||
@@ -263,23 +272,27 @@ describe("provider-web", () => {
|
|||||||
mediaUrl: "https://example.com/img.png",
|
mediaUrl: "https://example.com/img.png",
|
||||||
});
|
});
|
||||||
|
|
||||||
let capturedOnMessage: ((msg: any) => Promise<void>) | undefined;
|
let capturedOnMessage:
|
||||||
const listenerFactory = async (opts: { onMessage: (msg: any) => Promise<void> }) => {
|
| ((msg: import("./provider-web.js").WebInboundMessage) => Promise<void>)
|
||||||
|
| undefined;
|
||||||
|
const listenerFactory = async (opts: {
|
||||||
|
onMessage: (
|
||||||
|
msg: import("./provider-web.js").WebInboundMessage,
|
||||||
|
) => Promise<void>;
|
||||||
|
}) => {
|
||||||
capturedOnMessage = opts.onMessage;
|
capturedOnMessage = opts.onMessage;
|
||||||
return { close: vi.fn() };
|
return { close: vi.fn() };
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchMock = vi
|
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
|
||||||
.spyOn(global as any, "fetch")
|
ok: true,
|
||||||
.mockResolvedValue({
|
body: true,
|
||||||
ok: true,
|
arrayBuffer: async () => new ArrayBuffer(1024),
|
||||||
body: true,
|
headers: { get: () => "image/png" },
|
||||||
arrayBuffer: async () => new ArrayBuffer(1024),
|
status: 200,
|
||||||
headers: { get: () => "image/png" },
|
} as Response);
|
||||||
status: 200,
|
|
||||||
} as any);
|
|
||||||
|
|
||||||
await monitorWebProvider(false, listenerFactory as any, false, resolver);
|
await monitorWebProvider(false, listenerFactory, false, resolver);
|
||||||
|
|
||||||
expect(capturedOnMessage).toBeDefined();
|
expect(capturedOnMessage).toBeDefined();
|
||||||
await capturedOnMessage?.({
|
await capturedOnMessage?.({
|
||||||
@@ -303,9 +316,7 @@ describe("provider-web", () => {
|
|||||||
.mockReturnValue(true as never);
|
.mockReturnValue(true as never);
|
||||||
const readSpy = vi
|
const readSpy = vi
|
||||||
.spyOn(fsSync, "readFileSync")
|
.spyOn(fsSync, "readFileSync")
|
||||||
.mockReturnValue(
|
.mockReturnValue(JSON.stringify({ me: { id: "12345@s.whatsapp.net" } }));
|
||||||
JSON.stringify({ me: { id: "12345@s.whatsapp.net" } }),
|
|
||||||
);
|
|
||||||
const runtime = {
|
const runtime = {
|
||||||
log: vi.fn(),
|
log: vi.fn(),
|
||||||
error: vi.fn(),
|
error: vi.fn(),
|
||||||
|
|||||||
@@ -1,27 +1,28 @@
|
|||||||
import fs from "node:fs/promises";
|
|
||||||
import fsSync from "node:fs";
|
import fsSync from "node:fs";
|
||||||
|
import fs from "node:fs/promises";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import type { proto } from "@whiskeysockets/baileys";
|
import type { proto } from "@whiskeysockets/baileys";
|
||||||
import {
|
import {
|
||||||
|
type AnyMessageContent,
|
||||||
DisconnectReason,
|
DisconnectReason,
|
||||||
|
downloadMediaMessage,
|
||||||
fetchLatestBaileysVersion,
|
fetchLatestBaileysVersion,
|
||||||
makeCacheableSignalKeyStore,
|
makeCacheableSignalKeyStore,
|
||||||
makeWASocket,
|
makeWASocket,
|
||||||
useMultiFileAuthState,
|
useMultiFileAuthState,
|
||||||
downloadMediaMessage,
|
type WAMessage,
|
||||||
type AnyMessageContent,
|
|
||||||
} from "@whiskeysockets/baileys";
|
} from "@whiskeysockets/baileys";
|
||||||
import pino from "pino";
|
import pino from "pino";
|
||||||
import qrcode from "qrcode-terminal";
|
import qrcode from "qrcode-terminal";
|
||||||
import { danger, info, isVerbose, logVerbose, success, warn } from "./globals.js";
|
|
||||||
import { ensureDir, jidToE164, toWhatsappJid } from "./utils.js";
|
|
||||||
import type { Provider } from "./utils.js";
|
|
||||||
import { waitForever } from "./cli/wait.js";
|
|
||||||
import { getReplyFromConfig } from "./auto-reply/reply.js";
|
import { getReplyFromConfig } from "./auto-reply/reply.js";
|
||||||
import { defaultRuntime, type RuntimeEnv } from "./runtime.js";
|
import { waitForever } from "./cli/wait.js";
|
||||||
import { logInfo, logWarn } from "./logger.js";
|
import { danger, info, isVerbose, logVerbose, success } from "./globals.js";
|
||||||
|
import { logInfo } from "./logger.js";
|
||||||
import { saveMediaBuffer } from "./media/store.js";
|
import { saveMediaBuffer } from "./media/store.js";
|
||||||
|
import { defaultRuntime, type RuntimeEnv } from "./runtime.js";
|
||||||
|
import type { Provider } from "./utils.js";
|
||||||
|
import { ensureDir, jidToE164, toWhatsappJid } from "./utils.js";
|
||||||
|
|
||||||
function formatDuration(ms: number) {
|
function formatDuration(ms: number) {
|
||||||
return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
|
return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
|
||||||
@@ -231,7 +232,11 @@ export type WebInboundMessage = {
|
|||||||
timestamp?: number;
|
timestamp?: number;
|
||||||
sendComposing: () => Promise<void>;
|
sendComposing: () => Promise<void>;
|
||||||
reply: (text: string) => Promise<void>;
|
reply: (text: string) => Promise<void>;
|
||||||
sendMedia: (payload: { image: Buffer; caption?: string; mimetype?: string }) => Promise<void>;
|
sendMedia: (payload: {
|
||||||
|
image: Buffer;
|
||||||
|
caption?: string;
|
||||||
|
mimetype?: string;
|
||||||
|
}) => Promise<void>;
|
||||||
mediaPath?: string;
|
mediaPath?: string;
|
||||||
mediaType?: string;
|
mediaType?: string;
|
||||||
mediaUrl?: string;
|
mediaUrl?: string;
|
||||||
@@ -248,7 +253,9 @@ export async function monitorWebInbox(options: {
|
|||||||
await sock.sendPresenceUpdate("available");
|
await sock.sendPresenceUpdate("available");
|
||||||
if (isVerbose()) logVerbose("Sent global 'available' presence on connect");
|
if (isVerbose()) logVerbose("Sent global 'available' presence on connect");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logVerbose(`Failed to send 'available' presence on connect: ${String(err)}`);
|
logVerbose(
|
||||||
|
`Failed to send 'available' presence on connect: ${String(err)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const selfJid = sock.user?.id;
|
const selfJid = sock.user?.id;
|
||||||
const selfE164 = selfJid ? jidToE164(selfJid) : null;
|
const selfE164 = selfJid ? jidToE164(selfJid) : null;
|
||||||
@@ -275,7 +282,9 @@ export async function monitorWebInbox(options: {
|
|||||||
]);
|
]);
|
||||||
if (isVerbose()) {
|
if (isVerbose()) {
|
||||||
const suffix = participant ? ` (participant ${participant})` : "";
|
const suffix = participant ? ` (participant ${participant})` : "";
|
||||||
logVerbose(`Marked message ${id} as read for ${remoteJid}${suffix}`);
|
logVerbose(
|
||||||
|
`Marked message ${id} as read for ${remoteJid}${suffix}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logVerbose(`Failed to mark message ${id} read: ${String(err)}`);
|
logVerbose(`Failed to mark message ${id} read: ${String(err)}`);
|
||||||
@@ -389,16 +398,12 @@ export async function monitorWebProvider(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (!replyResult || (!replyResult.text && !replyResult.mediaUrl)) {
|
if (!replyResult || (!replyResult.text && !replyResult.mediaUrl)) {
|
||||||
logVerbose(
|
logVerbose("Skipping auto-reply: no text/media returned from resolver");
|
||||||
"Skipping auto-reply: no text/media returned from resolver",
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
if (replyResult.mediaUrl) {
|
if (replyResult.mediaUrl) {
|
||||||
logVerbose(
|
logVerbose(`Web auto-reply media detected: ${replyResult.mediaUrl}`);
|
||||||
`Web auto-reply media detected: ${replyResult.mediaUrl}`,
|
|
||||||
);
|
|
||||||
try {
|
try {
|
||||||
const media = await loadWebMedia(replyResult.mediaUrl);
|
const media = await loadWebMedia(replyResult.mediaUrl);
|
||||||
if (isVerbose()) {
|
if (isVerbose()) {
|
||||||
@@ -417,9 +422,7 @@ export async function monitorWebProvider(
|
|||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(
|
console.error(
|
||||||
danger(
|
danger(`Failed sending web media to ${msg.from}: ${String(err)}`),
|
||||||
`Failed sending web media to ${msg.from}: ${String(err)}`,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
if (replyResult.text) {
|
if (replyResult.text) {
|
||||||
await msg.reply(replyResult.text);
|
await msg.reply(replyResult.text);
|
||||||
@@ -499,9 +502,7 @@ export function logWebSelfId(
|
|||||||
e164 || jid
|
e164 || jid
|
||||||
? `${e164 ?? "unknown"}${jid ? ` (jid ${jid})` : ""}`
|
? `${e164 ?? "unknown"}${jid ? ` (jid ${jid})` : ""}`
|
||||||
: "unknown";
|
: "unknown";
|
||||||
const prefix = includeProviderPrefix
|
const prefix = includeProviderPrefix ? "Web Provider: " : "";
|
||||||
? "Web Provider: "
|
|
||||||
: "";
|
|
||||||
runtime.log(info(`${prefix}${details}`));
|
runtime.log(info(`${prefix}${details}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -526,7 +527,9 @@ function extractText(message: proto.IMessage | undefined): string | undefined {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function extractMediaPlaceholder(message: proto.IMessage | undefined): string | undefined {
|
function extractMediaPlaceholder(
|
||||||
|
message: proto.IMessage | undefined,
|
||||||
|
): string | undefined {
|
||||||
if (!message) return undefined;
|
if (!message) return undefined;
|
||||||
if (message.imageMessage) return "<media:image>";
|
if (message.imageMessage) return "<media:image>";
|
||||||
if (message.videoMessage) return "<media:video>";
|
if (message.videoMessage) return "<media:video>";
|
||||||
@@ -559,10 +562,15 @@ async function downloadInboundMedia(
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const buffer = (await downloadMediaMessage(msg as any, "buffer", {}, {
|
const buffer = (await downloadMediaMessage(
|
||||||
reuploadRequest: sock.updateMediaMessage,
|
msg as WAMessage,
|
||||||
logger: (sock as { logger?: unknown })?.logger as any,
|
"buffer",
|
||||||
})) as Buffer;
|
{},
|
||||||
|
{
|
||||||
|
reuploadRequest: sock.updateMediaMessage,
|
||||||
|
logger: sock.logger,
|
||||||
|
},
|
||||||
|
)) as Buffer;
|
||||||
return { buffer, mimetype };
|
return { buffer, mimetype };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logVerbose(`downloadMediaMessage failed: ${String(err)}`);
|
logVerbose(`downloadMediaMessage failed: ${String(err)}`);
|
||||||
@@ -586,20 +594,21 @@ async function loadWebMedia(
|
|||||||
if (array.length > MAX_WEB_BYTES) {
|
if (array.length > MAX_WEB_BYTES) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Media exceeds ${Math.floor(MAX_WEB_BYTES / (1024 * 1024))}MB limit (got ${(
|
`Media exceeds ${Math.floor(MAX_WEB_BYTES / (1024 * 1024))}MB limit (got ${(
|
||||||
array.length /
|
array.length / (1024 * 1024)
|
||||||
(1024 * 1024)
|
|
||||||
).toFixed(1)}MB)`,
|
).toFixed(1)}MB)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return { buffer: array, contentType: res.headers.get("content-type") ?? undefined };
|
return {
|
||||||
|
buffer: array,
|
||||||
|
contentType: res.headers.get("content-type") ?? undefined,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
// Local path
|
// Local path
|
||||||
const data = await fs.readFile(mediaUrl);
|
const data = await fs.readFile(mediaUrl);
|
||||||
if (data.length > MAX_WEB_BYTES) {
|
if (data.length > MAX_WEB_BYTES) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Media exceeds ${Math.floor(MAX_WEB_BYTES / (1024 * 1024))}MB limit (got ${(
|
`Media exceeds ${Math.floor(MAX_WEB_BYTES / (1024 * 1024))}MB limit (got ${(
|
||||||
data.length /
|
data.length / (1024 * 1024)
|
||||||
(1024 * 1024)
|
|
||||||
).toFixed(1)}MB)`,
|
).toFixed(1)}MB)`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user