Kod örnekleri

Örnek dosyaları indir (ZIP)

build-workflow.cjs
const fs = require('node:fs');
const path = require('node:path');
const read = name => fs.readFileSync(path.join(__dirname, name), 'utf8');
const fn = read('dedup.js');
const batches = JSON.parse(read('sample-batches.json'));
const nodes = [];
const connections = {};
const node = (name, type, typeVersion, position, parameters, extra = {}) => nodes.push({
  id: `b9041000-0baa-4000-8000-${String(nodes.length + 1).padStart(12, '0')}`,
  name, type: `n8n-nodes-base.${type}`, typeVersion, position, parameters, ...extra,
});
const connect = (from, to) => { connections[from] = { main: [[{ node: to, type: 'main', index: 0 }]] }; };
node('Elle dene', 'manualTrigger', 1, [0, 0], {});
node('Kurgusal RSS partileri', 'code', 2, [240, 0], { jsCode: `return [{ json: { batches: ${JSON.stringify(batches)} } }];` });
node('İki tur prova', 'code', 2, [480, 0], { jsCode: `${fn}
let seen = [];
return $input.first().json.batches.map((rows, i) => {
  const { seen: next, accepted, duplicate, skipped, deferred } = select(rows, seen, { source: 'kurgu' });
  seen = next;
  return { json: { round: i + 1, accepted, duplicate, skipped, deferred } };
});` });
connect('Elle dene', 'Kurgusal RSS partileri');
connect('Kurgusal RSS partileri', 'İki tur prova');
node('Her gün 10.00 (kapalı)', 'scheduleTrigger', 1.2, [0, 260], { rule: { interval: [{ field: 'days', daysInterval: 1, triggerAtHour: 10, triggerAtMinute: 0 }] } }, { disabled: true });
node('RSS oku (örnek URL)', 'rssFeedRead', 1.2, [240, 260], { url: 'https://bulten.example/rss.xml', options: {} }, { retryOnFail: true, maxTries: 3, waitBetweenTries: 5000 });
node('Filtrele ve biçimle', 'code', 2, [480, 260], { jsCode: `${fn}
// Önizleme geçmişe yazmaz. Yalnızca Telegram bağlandığında bilinçli olarak değiştirin.
const previewOnly = true;
const state = previewOnly ? {} : $getWorkflowStaticData('node');
const seen = Array.isArray(state.seen) ? state.seen : [];
const result = select($input.all().map(item => item.json), seen, { source: 'bulten-1' });
if (!previewOnly && result.accepted.length) state.seen = result.seen;
return result.accepted.map(json => ({ json }));` });
connect('Her gün 10.00 (kapalı)', 'RSS oku (örnek URL)');
connect('RSS oku (örnek URL)', 'Filtrele ve biçimle');
node('Telegram (bağlı değil)', 'telegram', 1.2, [760, 260], {
  resource: 'message', operation: 'sendMessage', chatId: '',
  text: '={{ $json.text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") }}',
  additionalFields: { appendAttribution: false, disable_web_page_preview: true, parse_mode: 'HTML' },
}, { disabled: true });
const workflow = { name: 'BAA | RSS → Telegram (ağsız prova)', active: false, nodes, connections,
  settings: { executionOrder: 'v1', timezone: 'Europe/Istanbul' }, pinData: {} };
fs.writeFileSync(path.join(__dirname, 'workflow.json'), `${JSON.stringify(workflow, null, 2)}\n`);
dedup.js
// n8n Code v2 ve ağsız Node.js testi aynı işlevi kullanır.
function select(rows, seen, { source, cap = 20, keep = 500 } = {}) {
  const known = new Set(seen);
  const next = seen.slice();
  const out = [];
  let duplicate = 0, skipped = 0, deferred = 0;
  for (const row of rows) {
    const title = typeof row.title === 'string' ? row.title.replace(/\s+/gu, ' ').trim().slice(0, 200) : '';
    const link = typeof row.link === 'string' ? row.link.trim().split('#')[0] : '';
    // Dar demo politikası: HTTPS, ASCII hostname, kullanıcı bilgisi ve port yok.
    if (!title || link.length > 1800 || !/^https:\/\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?:[/?][!-~]*)?$/iu.test(link) || link.includes('\\')) {
      skipped++;
      continue;
    }
    const guid = typeof row.guid === 'string' ? row.guid.trim() : '';
    const key = JSON.stringify([source, guid && guid.length <= 512 ? 'guid' : 'link', guid && guid.length <= 512 ? guid : link]);
    if (known.has(key)) { duplicate++; continue; }
    if (out.length >= cap) { deferred++; continue; }
    known.add(key);
    next.push(key);
    out.push({ key, title, link, text: `${title}\n${link}` });
  }
  return { accepted: out, seen: next.slice(-keep), duplicate, skipped, deferred };
}
sample-batches.json
[
  [
    {"guid":"demo-101","title":"Depo notları: ilk sürüm","link":"https://bulten.example/yazi/101","pubDate":"Fri, 20 Nov 2026 08:00:00 GMT"},
    {"guid":"demo-101","title":"Aynı yazı, yeni başlık","link":"https://bulten.example/yazi/101?edition=2"},
    {"title":"Okuma listesi","link":"https://bulten.example/yazi/liste#ilk"},
    {"title":"Geçersiz bağlantı","link":"javascript:demo"}
  ],
  [
    {"title":"Okuma listesi","link":"https://bulten.example/yazi/liste#ikinci"},
    {"guid":"demo-101","title":"Depo notları: düzeltme","link":"https://bulten.example/yazi/101"},
    {"guid":"demo-102","title":"Saat dilimi kontrolü","link":"https://bulten.example/yazi/102"}
  ]
]
workflow.json
{
  "name": "BAA | RSS → Telegram (ağsız prova)",
  "active": false,
  "nodes": [
    {
      "id": "b9041000-0baa-4000-8000-000000000001",
      "name": "Elle dene",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "b9041000-0baa-4000-8000-000000000002",
      "name": "Kurgusal RSS partileri",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        0
      ],
      "parameters": {
        "jsCode": "return [{ json: { batches: [[{\"guid\":\"demo-101\",\"title\":\"Depo notları: ilk sürüm\",\"link\":\"https://bulten.example/yazi/101\",\"pubDate\":\"Fri, 20 Nov 2026 08:00:00 GMT\"},{\"guid\":\"demo-101\",\"title\":\"Aynı yazı, yeni başlık\",\"link\":\"https://bulten.example/yazi/101?edition=2\"},{\"title\":\"Okuma listesi\",\"link\":\"https://bulten.example/yazi/liste#ilk\"},{\"title\":\"Geçersiz bağlantı\",\"link\":\"javascript:demo\"}],[{\"title\":\"Okuma listesi\",\"link\":\"https://bulten.example/yazi/liste#ikinci\"},{\"guid\":\"demo-101\",\"title\":\"Depo notları: düzeltme\",\"link\":\"https://bulten.example/yazi/101\"},{\"guid\":\"demo-102\",\"title\":\"Saat dilimi kontrolü\",\"link\":\"https://bulten.example/yazi/102\"}]] } }];"
      }
    },
    {
      "id": "b9041000-0baa-4000-8000-000000000003",
      "name": "İki tur prova",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        0
      ],
      "parameters": {
        "jsCode": "// n8n Code v2 ve ağsız Node.js testi aynı işlevi kullanır.\nfunction select(rows, seen, { source, cap = 20, keep = 500 } = {}) {\n  const known = new Set(seen);\n  const next = seen.slice();\n  const out = [];\n  let duplicate = 0, skipped = 0, deferred = 0;\n  for (const row of rows) {\n    const title = typeof row.title === 'string' ? row.title.replace(/\\s+/gu, ' ').trim().slice(0, 200) : '';\n    const link = typeof row.link === 'string' ? row.link.trim().split('#')[0] : '';\n    // Dar demo politikası: HTTPS, ASCII hostname, kullanıcı bilgisi ve port yok.\n    if (!title || link.length > 1800 || !/^https:\\/\\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?:[/?][!-~]*)?$/iu.test(link) || link.includes('\\\\')) {\n      skipped++;\n      continue;\n    }\n    const guid = typeof row.guid === 'string' ? row.guid.trim() : '';\n    const key = JSON.stringify([source, guid && guid.length <= 512 ? 'guid' : 'link', guid && guid.length <= 512 ? guid : link]);\n    if (known.has(key)) { duplicate++; continue; }\n    if (out.length >= cap) { deferred++; continue; }\n    known.add(key);\n    next.push(key);\n    out.push({ key, title, link, text: `${title}\\n${link}` });\n  }\n  return { accepted: out, seen: next.slice(-keep), duplicate, skipped, deferred };\n}\n\nlet seen = [];\nreturn $input.first().json.batches.map((rows, i) => {\n  const { seen: next, accepted, duplicate, skipped, deferred } = select(rows, seen, { source: 'kurgu' });\n  seen = next;\n  return { json: { round: i + 1, accepted, duplicate, skipped, deferred } };\n});"
      }
    },
    {
      "id": "b9041000-0baa-4000-8000-000000000004",
      "name": "Her gün 10.00 (kapalı)",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        260
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 10,
              "triggerAtMinute": 0
            }
          ]
        }
      },
      "disabled": true
    },
    {
      "id": "b9041000-0baa-4000-8000-000000000005",
      "name": "RSS oku (örnek URL)",
      "type": "n8n-nodes-base.rssFeedRead",
      "typeVersion": 1.2,
      "position": [
        240,
        260
      ],
      "parameters": {
        "url": "https://bulten.example/rss.xml",
        "options": {}
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "id": "b9041000-0baa-4000-8000-000000000006",
      "name": "Filtrele ve biçimle",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        260
      ],
      "parameters": {
        "jsCode": "// n8n Code v2 ve ağsız Node.js testi aynı işlevi kullanır.\nfunction select(rows, seen, { source, cap = 20, keep = 500 } = {}) {\n  const known = new Set(seen);\n  const next = seen.slice();\n  const out = [];\n  let duplicate = 0, skipped = 0, deferred = 0;\n  for (const row of rows) {\n    const title = typeof row.title === 'string' ? row.title.replace(/\\s+/gu, ' ').trim().slice(0, 200) : '';\n    const link = typeof row.link === 'string' ? row.link.trim().split('#')[0] : '';\n    // Dar demo politikası: HTTPS, ASCII hostname, kullanıcı bilgisi ve port yok.\n    if (!title || link.length > 1800 || !/^https:\\/\\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?:[/?][!-~]*)?$/iu.test(link) || link.includes('\\\\')) {\n      skipped++;\n      continue;\n    }\n    const guid = typeof row.guid === 'string' ? row.guid.trim() : '';\n    const key = JSON.stringify([source, guid && guid.length <= 512 ? 'guid' : 'link', guid && guid.length <= 512 ? guid : link]);\n    if (known.has(key)) { duplicate++; continue; }\n    if (out.length >= cap) { deferred++; continue; }\n    known.add(key);\n    next.push(key);\n    out.push({ key, title, link, text: `${title}\\n${link}` });\n  }\n  return { accepted: out, seen: next.slice(-keep), duplicate, skipped, deferred };\n}\n\n// Önizleme geçmişe yazmaz. Yalnızca Telegram bağlandığında bilinçli olarak değiştirin.\nconst previewOnly = true;\nconst state = previewOnly ? {} : $getWorkflowStaticData('node');\nconst seen = Array.isArray(state.seen) ? state.seen : [];\nconst result = select($input.all().map(item => item.json), seen, { source: 'bulten-1' });\nif (!previewOnly && result.accepted.length) state.seen = result.seen;\nreturn result.accepted.map(json => ({ json }));"
      }
    },
    {
      "id": "b9041000-0baa-4000-8000-000000000007",
      "name": "Telegram (bağlı değil)",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        760,
        260
      ],
      "parameters": {
        "resource": "message",
        "operation": "sendMessage",
        "chatId": "",
        "text": "={{ $json.text.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\") }}",
        "additionalFields": {
          "appendAttribution": false,
          "disable_web_page_preview": true,
          "parse_mode": "HTML"
        }
      },
      "disabled": true
    }
  ],
  "connections": {
    "Elle dene": {
      "main": [
        [
          {
            "node": "Kurgusal RSS partileri",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Kurgusal RSS partileri": {
      "main": [
        [
          {
            "node": "İki tur prova",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Her gün 10.00 (kapalı)": {
      "main": [
        [
          {
            "node": "RSS oku (örnek URL)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "RSS oku (örnek URL)": {
      "main": [
        [
          {
            "node": "Filtrele ve biçimle",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Istanbul"
  },
  "pinData": {}
}
workflow.test.cjs
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const read = file => fs.readFileSync(path.join(__dirname, file), 'utf8');
const w = JSON.parse(read('workflow.json'));
const byName = name => w.nodes.find(n => n.name === name);
const invoke = (name, bindings = {}) => new Function(...Object.keys(bindings), byName(name).parameters.jsCode)(...Object.values(bindings));
const select = new Function(`${read('dedup.js')}\nreturn select;`)();

test('içe aktarma grafiği: kapalı workflow, kapalı saat, Telegram bağlantısız ve credentials yok', () => {
  assert.equal(w.active, false);
  assert.equal(w.settings.timezone, 'Europe/Istanbul');
  assert.equal(w.nodes.length, 7);
  for (const [from, targets] of Object.entries(w.connections)) {
    assert.ok(byName(from));
    for (const target of targets.main.flat()) {
      assert.ok(byName(target.node));
      assert.notEqual(target.node, 'Telegram (bağlı değil)');
    }
  }
  assert.equal(byName('Her gün 10.00 (kapalı)').disabled, true);
  const rss = byName('RSS oku (örnek URL)');
  assert.deepEqual([rss.retryOnFail, rss.maxTries, rss.waitBetweenTries], [true, 3, 5000]);
  const telegram = byName('Telegram (bağlı değil)');
  assert.equal(telegram.disabled, true);
  assert.equal(telegram.parameters.chatId, '');
  assert.ok(w.nodes.every(n => !n.credentials));
});

test('workflow içindeki gerçek Code metni, iki kurgusal partiyi ağsız işler', () => {
  const [fixture] = invoke('Kurgusal RSS partileri');
  assert.deepEqual(fixture.json.batches, JSON.parse(read('sample-batches.json')));
  const results = invoke('İki tur prova', { $input: { first: () => fixture } });
  assert.deepEqual(results.map(({json: {accepted, duplicate, skipped, deferred}}) => [accepted.length, duplicate, skipped, deferred]), [[2, 1, 1, 0], [1, 2, 0, 0]]);
  assert.equal(results[0].json.accepted[1].link, 'https://bulten.example/yazi/liste');
  assert.equal(results[1].json.accepted[0].text, 'Saat dilimi kontrolü\nhttps://bulten.example/yazi/102');
});

test('RSS filtresi önizlemede depolama çağırmaz', () => {
  const [first] = JSON.parse(read('sample-batches.json'));
  const result = invoke('Filtrele ve biçimle', { $input: { all: () => first.map(json => ({json})) }, $getWorkflowStaticData: () => { throw Error('unexpected'); } });
  assert.equal(result.length, 2);
});

test('mesaj üst sınırında bekleyen öğe görülmüş sayılmaz', () => {
  const rows = ['a', 'b'].map(guid => ({guid, title: guid, link: `https://bulten.example/${guid}`}));
  const first = select(rows, [], { source: 'feed-a', cap: 1 });
  assert.equal(first.deferred, 1);
  assert.equal(first.seen.length, 1);
  const second = select(rows, first.seen, { source: 'feed-a', cap: 1 });
  assert.equal(second.accepted[0].title, 'b');
});

test('GUID akışa özgüdür, görülen geçmiş sınırlıdır', () => {
  const rows = ['a', 'b'].map(guid => ({guid, title: guid, link: `https://bulten.example/${guid}`}));
  const a = select(rows, [], { source: 'feed-a', keep: 1 });
  assert.equal(a.seen.length, 1);
  assert.equal(select([rows[1]], a.seen, { source: 'feed-b' }).accepted.length, 1);
});

test('güvensiz veya hatalı bağlantılar mesaj olmaz', () => {
  const rows = ['http://bulten.example/x', 'https://[email protected]/x', 'https://bulten.example/a\\b', 'https://bulten.example/a b'].map(link => ({title: 'yazı', link}));
  assert.equal(select(rows, [], { source: 'feed-a' }).skipped, rows.length);
});