/* Name: bgn.go.id - Cek Mbg Type: Scraper By: Nakano Code Saluran : https://whatsapp.com/channel/0029VbDytkmBqbrF0rFKr12w Base Url: https://bgn.go.id/radar-mbg */ const { writeFile } = require('node:fs/promises'); const { resolve } = require('node:path'); const readline = require('node:readline/promises'); const { stdin: input, stdout: output } = require('node:process'); const ORIGIN = 'https://bgn.go.id'; const APP = `${ORIGIN}/radar-mbg`; const REGION = `${APP}/api/region/v1`; const PAGE_SIZE = 100; const USER_AGENT = 'Mozilla/5.0 (compatible; RadarMBGResearchScraper/1.0)'; let args = process.argv.slice(2); const has = (flag) => args.includes(flag); function arg(...names) { for (const name of names) { const i = args.indexOf(name); if (i >= 0 && args[i + 1] && !args[i + 1].startsWith('--')) return args[i + 1]; } return null; } function outFile(fallback) { return resolve(arg('--out') || fallback); } function delay(ms) { return new Promise(r => setTimeout(r, ms)); } async function fetchJson(url) { let response; for (let attempt = 0; attempt < 3; attempt++) { try { response = await fetch(url, { signal: AbortSignal.timeout(30000), headers: { 'user-agent': USER_AGENT, accept: 'application/json, text/plain, */*', referer: `${APP}/`, }, }); break; } catch (error) { if (attempt === 2) throw error; await delay(500 * (attempt + 1)); } } const text = await response.text(); let body; try { body = JSON.parse(text); } catch { body = { raw: text.slice(0, 500) }; } if (!response.ok) { const error = new Error(body?.message || `HTTP ${response.status} for ${url}`); error.status = response.status; error.body = body; throw error; } return body; } async function regionList(p, key) { const body = await fetchJson(`${REGION}/${p}?page_size=${PAGE_SIZE}`); const list = (key && body.data?.[key]?.data) ?? body.data ?? []; if (!Array.isArray(list)) throw new Error(`Format respons wilayah tidak dikenali (${p}).`); return list; } function nameOf(item, level) { const fields = { provinsi: 'provinsi', kabko: 'kabko', kecamatan: 'kecamatan', kelurahan: 'kelurahan' }; return String(item?.[fields[level]] ?? ''); } function codeOf(item, level) { const fields = { provinsi: 'kode_prov_dagri', kabko: 'kode_kabko_dagri', kecamatan: 'kode_kec_dagri', kelurahan: 'kode_kel_dagri', }; return String(item?.[fields[level]] ?? ''); } async function choose(rl, label, items, level, supplied) { if (!items.length) throw new Error(`Daftar ${label} kosong dari API wilayah.`); if (supplied) { const q = supplied.trim().toLocaleLowerCase('id-ID'); const match = items.find(x => codeOf(x, level) === supplied || nameOf(x, level).toLocaleLowerCase('id-ID') === q) ?? items.find(x => nameOf(x, level).toLocaleLowerCase('id-ID').includes(q)); if (!match) throw new Error(`Pilihan ${label} "${supplied}" tidak ditemukan di daftar.`); console.log(`${label}: ${nameOf(match, level)} [${codeOf(match, level)}]`); return match; } console.log(`\n${label} — pilih nomor, nama, atau kode:`); items.forEach((item, i) => console.log(`${String(i + 1).padStart(3)}. ${nameOf(item, level)} [${codeOf(item, level)}]`)); while (true) { const answer = (await rl.question('Pilihan: ')).trim(); const q = answer.toLocaleLowerCase('id-ID'); const exact = items.find(x => codeOf(x, level) === answer || nameOf(x, level).toLocaleLowerCase('id-ID') === q); if (exact) return exact; const n = Number(answer); if (Number.isInteger(n) && n >= 1 && n <= items.length) return items[n - 1]; const partial = items.filter(x => nameOf(x, level).toLocaleLowerCase('id-ID').includes(q)); if (partial.length === 1) return partial[0]; if (partial.length > 1) { console.log('Nama cocok dengan beberapa pilihan; masukkan nomor/kode:'); partial.forEach(x => console.log(`- ${nameOf(x, level)} [${codeOf(x, level)}]`)); } else console.log('Pilihan tidak ditemukan; coba lagi.'); } } async function getSelectedArea(rl) { const provinces = await regionList('provinsi', ''); const province = await choose(rl, 'Provinsi', provinces, 'provinsi', arg('--provinsi', '--province')); const kabkos = await regionList(`provinsi/dagri/${encodeURIComponent(codeOf(province, 'provinsi'))}`, 'kabupaten_kota'); const kabko = await choose(rl, 'Kabupaten/kota', kabkos, 'kabko', arg('--kabko', '--kabupaten-kota')); const kecamatans = await regionList(`kabupaten-kota/dagri/${encodeURIComponent(codeOf(kabko, 'kabko'))}`, 'kecamatan'); const kecamatan = await choose(rl, 'Kecamatan', kecamatans, 'kecamatan', arg('--kecamatan')); const kelurahans = await regionList(`kecamatan/dagri/${encodeURIComponent(codeOf(kecamatan, 'kecamatan'))}`, 'kelurahan'); const kelurahan = await choose(rl, 'Kelurahan/desa', kelurahans, 'kelurahan', arg('--kelurahan')); return { province, kabko, kecamatan, kelurahan }; } function areaRecord(area) { const pack = (item, level) => ({ code: codeOf(item, level), name: nameOf(item, level) }); return { provinsi: pack(area.province, 'provinsi'), kabupaten_kota: pack(area.kabko, 'kabko'), kecamatan: pack(area.kecamatan, 'kecamatan'), kelurahan_desa: pack(area.kelurahan, 'kelurahan'), }; } function makeAreaUrl(area) { const params = new URLSearchParams({ provinsi: codeOf(area.province, 'provinsi'), kabko: codeOf(area.kabko, 'kabko'), kecamatan: codeOf(area.kecamatan, 'kecamatan'), kelurahan: codeOf(area.kelurahan, 'kelurahan'), }); return `${APP}/?${params.toString()}`; } function normalizeName(value) { return String(value).toLocaleLowerCase('id-ID').replace(/\s+/g, ' ').trim(); } async function selectAreaThroughUI(page, area) { await page.goto(`${APP}/`, { waitUntil: 'domcontentloaded', timeout: 60000 }); await page.locator('main').waitFor({ state: 'visible', timeout: 60000 }); const selected = [area.province, area.kabko, area.kecamatan, area.kelurahan]; const placeholders = [ /^Pilih Provinsi$/i, /^Pilih Kota\s*\/\s*Kabupaten$/i, /^Pilih Kecamatan$/i, /^Pilih Kelurahan\s*\/\s*Desa$/i, ]; for (let level = 0; level < selected.length; level++) { const selector = page.getByRole('button', { name: placeholders[level] }).first(); await selector.waitFor({ state: 'visible', timeout: 60000 }); await page.waitForFunction((pattern) => { const re = new RegExp(pattern, 'i'); return [...document.querySelectorAll('main button')].some(button => re.test((button.innerText || '').trim()) && !button.disabled && !/memuat/i.test(button.innerText || '') ); }, placeholders[level].source, { timeout: 90000 }); await selector.click(); const options = page.getByRole('option'); await options.first().waitFor({ state: 'visible', timeout: 30000 }); const optionNames = (await options.allInnerTexts()).map(s => s.trim()); const target = normalizeName(nameOf(selected[level], ['provinsi', 'kabko', 'kecamatan', 'kelurahan'][level])); const optionIndex = optionNames.findIndex(name => normalizeName(name) === target); if (optionIndex < 0) throw new Error(`Pilihan ${target} tidak ditemukan di daftar resmi browser.`); await options.nth(optionIndex).click(); await page.waitForTimeout(300); } return page.url(); } async function waitForInstitutionButton(page, rl) { console.log('\nMembuka halaman Radar MBG resmi. Jika browser menampilkan verifikasi Cloudflare, selesaikan di jendela tersebut.'); const ready = page.waitForFunction(() => { const buttons = [...document.querySelectorAll('button')].map(b => (b.innerText || '').trim()); return buttons.some(t => /Pilih instansi|Belum ada instansi terdaftar/i.test(t)); }, null, { timeout: 90000 }).then(() => true).catch(() => false); const ok = await ready; if (!ok) { console.log('Pilihan instansi belum muncul. Selesaikan verifikasi/ tunggu halaman selesai di browser, lalu tekan Enter di terminal.'); await rl.question('Tekan Enter untuk mencoba lagi (Ctrl+C untuk berhenti): '); await page.waitForFunction(() => { const buttons = [...document.querySelectorAll('button')].map(b => (b.innerText || '').trim()); return buttons.some(t => /Pilih instansi|Belum ada instansi terdaftar/i.test(t)); }, null, { timeout: 90000 }); } const bodyText = await page.locator('body').innerText().catch(() => ''); if (/Belum ada instansi terdaftar/i.test(bodyText)) return { none: true, options: [] }; const button = page.getByRole('button', { name: /Pilih instansi/i }).first(); await button.waitFor({ state: 'visible', timeout: 30000 }); await button.click(); const options = page.getByRole('option'); await options.first().waitFor({ state: 'visible', timeout: 30000 }); const names = (await options.allInnerTexts()).map(s => s.trim()).filter(Boolean); return { none: names.length === 0, options: names }; } async function readInstitutionPage(page, area, index, rl) { if (index > 0 || !page.url().startsWith(`${APP}/?`)) { await selectAreaThroughUI(page, area); const reopened = await waitForInstitutionButton(page, rl); if (reopened.none) throw new Error('Tidak ada instansi terdaftar pada lokasi terpilih.'); } await page.getByRole('option').nth(index).click(); await page.waitForURL(url => /\/radar-mbg\/instansi\/[^/]+/.test(url.toString()), { timeout: 60000 }); await page.locator('main').waitFor({ state: 'visible', timeout: 60000 }); const detailReady = () => page.waitForFunction(() => { const text = document.querySelector('main')?.innerText || ''; return /SPPG Penyedia/i.test(text) && !/Memverifikasi keamanan/i.test(text); }, null, { timeout: 60000 }).then(() => true).catch(() => false); if (!(await detailReady())) { console.log('Data instansi belum terlihat. Selesaikan verifikasi di browser (atau muat ulang halaman jika diminta), lalu tekan Enter.'); await rl.question('Tekan Enter setelah halaman siap (Ctrl+C untuk berhenti): '); await page.waitForFunction(() => /SPPG Penyedia/i.test(document.querySelector('main')?.innerText || ''), null, { timeout: 90000 }); } const title = await page.title(); const url = page.url(); const text = (await page.locator('main').innerText()).trim(); const headings = await page.locator('main h1, main h2, main h3').allInnerTexts().catch(() => []); const match = url.match(/\/instansi\/([^/?#]+)/); const sppgStatus = text.includes('Belum Terlayani SPPG') ? 'Belum Terlayani SPPG' : text.includes('belum melaporkan menu hari ini') ? 'SPPG belum melaporkan menu hari ini' : text.includes('SPPG Penyedia') ? 'SPPG tersedia/tercantum' : null; return { institution_id: match?.[1] ?? null, title, page_url: url, headings: headings.map(s => s.trim()).filter(Boolean), sppg_status: sppgStatus, page_text: text, }; } async function lookupMode() { let chromium; const rl = readline.createInterface({ input, output }); let browser; try { const area = await getSelectedArea(rl); const location = areaRecord(area); const areaUrl = makeAreaUrl(area); console.log(`\nWilayah terpilih: ${location.kelurahan_desa.name}, ${location.kecamatan.name}, ${location.kabupaten_kota.name}, ${location.provinsi.name}`); if (has('--area-only')) { const result = { success: true, scraped_at: new Date().toISOString(), source: areaUrl, area: location, status: 'area_selected', note: 'Daftar wilayah berasal dari API region publik. Untuk mengambil instansi/menu/SPPG, jalankan lagi tanpa --area-only agar halaman resmi dapat dibuka di browser.', }; const file = outFile(`radar_mbg_${codeOf(area.kelurahan, 'kelurahan')}_area.json`); await writeFile(file, `${JSON.stringify(result, null, 2)}\n`); console.log(JSON.stringify({ ...result, output_file: file }, null, 2)); return { ...result, output_file: file }; } try { ({ chromium } = await import('playwright')); } catch { throw new Error('Lookup instansi/menu memerlukan Playwright. Instal sekali dengan: npm install playwright && npx playwright install chromium'); } const headless = has('--headless') || process.env.HEADLESS === '1'; const launchOptions = { headless }; if (process.env.CHROMIUM_PATH) launchOptions.executablePath = process.env.CHROMIUM_PATH; browser = await chromium.launch(launchOptions); const context = await browser.newContext({ locale: 'id-ID' }); const page = await context.newPage(); await selectAreaThroughUI(page, area); const choices = await waitForInstitutionButton(page, rl); if (choices.none) { const empty = { success: true, scraped_at: new Date().toISOString(), source: areaUrl, area: location, institutions_available: [], institutions: [], status: 'empty', note: 'Halaman resmi menyatakan belum ada instansi terdaftar untuk kelurahan/desa ini.', }; const file = outFile(`radar_mbg_${codeOf(area.kelurahan, 'kelurahan')}.json`); await writeFile(file, `${JSON.stringify(empty, null, 2)}\n`); console.log(JSON.stringify({ ...empty, output_file: file }, null, 2)); return { ...empty, output_file: file }; } console.log('\nInstansi tersedia:'); choices.options.forEach((name, i) => console.log(`${i + 1}. ${name}`)); let selectedIndexes; if (has('--all-institutions')) selectedIndexes = choices.options.map((_, i) => i); else { const supplied = arg('--instansi', '--institution'); if (supplied) { const q = supplied.toLocaleLowerCase('id-ID'); let i = choices.options.findIndex(n => n.toLocaleLowerCase('id-ID') === q); if (i < 0) i = choices.options.findIndex(n => n.toLocaleLowerCase('id-ID').includes(q)); if (i < 0) throw new Error(`Instansi "${supplied}" tidak ditemukan pada daftar kelurahan terpilih.`); selectedIndexes = [i]; } else { const answer = (await rl.question('\nPilih nomor instansi (atau ketik "semua" untuk mengambil seluruh halaman instansi): ')).trim(); if (/^(semua|all)$/i.test(answer)) selectedIndexes = choices.options.map((_, i) => i); else { const n = Number(answer); if (!Number.isInteger(n) || n < 1 || n > choices.options.length) throw new Error('Nomor instansi tidak valid.'); selectedIndexes = [n - 1]; } } } const institutions = []; for (let n = 0; n < selectedIndexes.length; n++) { const idx = selectedIndexes[n]; console.log(`Mengambil ${n + 1}/${selectedIndexes.length}: ${choices.options[idx]}`); const detail = await readInstitutionPage(page, area, idx, rl); institutions.push({ name: choices.options[idx], ...detail }); if (n + 1 < selectedIndexes.length) await delay(500); } const result = { success: true, scraped_at: new Date().toISOString(), source: areaUrl, area: location, institutions_available: choices.options, institutions, note: 'Data diambil dari tampilan halaman resmi Radar MBG. Jika menu/SPPG tidak tampil pada halaman, tidak diasumsikan ada data tersembunyi.', }; const file = outFile(`radar_mbg_${codeOf(area.kelurahan, 'kelurahan')}.json`); await writeFile(file, `${JSON.stringify(result, null, 2)}\n`); console.log(JSON.stringify({ ...result, output_file: file }, null, 2)); return { ...result, output_file: file }; } finally { if (browser) await browser.close().catch(() => {}); rl.close(); } } async function snapshotMode() { const pageResponse = await fetch(`${APP}/`, { headers: { 'user-agent': USER_AGENT } }); const html = await pageResponse.text(); const decode = (s = '') => s.replaceAll('&', '&').replaceAll('"', '"').replaceAll(''', "'").replaceAll('<', '<').replaceAll('>', '>'); const title = decode(html.match(/