ZZZ Digital Lab

Back to Google Sheets CRM repair

lib/mock.cjs

'use strict';
// Minimal in-repo mock, not a Google Apps Script emulator.
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
function csv(text) {
  const rows = []; let row = [], cell = '', quoted = false;
  for (let i = 0; i < text.length; i++) {
    const ch = text[i];
    if (ch === '"' && (quoted || cell === '')) {
      if (quoted && text[i + 1] === '"') { cell += '"'; i++; } else quoted = !quoted;
    } else if (ch === ',' && !quoted) { row.push(cell); cell = ''; }
    else if (ch === '\n' && !quoted) { row.push(cell.replace(/\r$/, '')); rows.push(row); row = []; cell = ''; }
    else cell += ch;
  }
  if (cell || row.length) { row.push(cell.replace(/\r$/, '')); rows.push(row); }
  if (quoted) throw new Error('CSV_UNCLOSED_QUOTE');
  return rows;
}
function formatDate(date, tz, pattern) {
  const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', {
    timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23'
  }).formatToParts(date).filter(p => p.type !== 'literal').map(p => [p.type, p.value]));
  if (pattern === "yyyy-MM-dd'T'HH:mm:ss'Z'") return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`;
  if (pattern === 'yyyy-MM-dd HH:mm:ss') return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}:${parts.second}`;
  throw new Error('MOCK_UNSUPPORTED_FORMAT');
}
function createHarness(options = {}) {
  const root = path.join(__dirname, '..');
  const metrics = {reads: 0, writes: 0, flushes: 0, sleeps: 0, propertyWrites: 0, releases: 0};
  const logs = [], properties = {...(options.properties || {})};
  let held = Boolean(options.locked), failWrites = options.failWrites || 0, failProperties = options.failProperties || 0;
  class Sheet {
    constructor(name, data) { this.name = name; this.data = structuredClone(data); }
    getName() { return this.name; }
    getLastRow() { return this.data.length; }
    getDataRange() { return this.getRange(1, 1, Math.max(1, this.data.length), Math.max(...this.data.map(r => r.length))); }
    getRange(r, c, nr, nc) {
      if (![r,c,nr,nc].every(n => Number.isInteger(n) && n > 0)) throw new Error('INVALID_RANGE');
      return {
        getValues: () => { metrics.reads++; return Array.from({length: nr}, (_,i) => Array.from({length: nc}, (_,j) => this.data[r-1+i]?.[c-1+j] ?? '')); },
        setValues: values => {
          if (values.length !== nr || values.some(row => row.length !== nc)) throw new Error('SHAPE_MISMATCH');
          if (failWrites-- > 0 || metrics.writes >= (options.writeQuota ?? Infinity)) throw new Error('SERVICE_QUOTA');
          if (options.onWrite) options.onWrite();
          metrics.writes++;
          values.forEach((row,i) => row.forEach((v,j) => { (this.data[r-1+i] ||= [])[c-1+j] = v; }));
        }
      };
    }
    appendRow(row) { this.getRange(this.getLastRow() + 1, 1, 1, row.length).setValues([row]); }
  }
  const sheets = {
    Inbox: new Sheet('Inbox', options.inbox || csv(fs.readFileSync(path.join(root, 'fixtures/inbox.csv'), 'utf8'))),
    Leads: new Sheet('Leads', options.leads || csv(fs.readFileSync(path.join(root, 'fixtures/leads.csv'), 'utf8')))
  };
  const sandbox = {
    console: {log: line => logs.push(JSON.parse(line))},
    SpreadsheetApp: {getActiveSpreadsheet: () => ({getSheetByName: name => sheets[name] || null}), flush: () => { metrics.flushes++; }},
    LockService: {getScriptLock: () => ({tryLock: () => { if (held) return false; held = true; return true; }, releaseLock: () => { held = false; metrics.releases++; }})},
    PropertiesService: {getScriptProperties: () => ({
      getProperty: key => properties[key] ?? null,
      setProperty: (key,value) => { if (failProperties-- > 0) throw new Error('PROPERTY_QUOTA'); metrics.propertyWrites++; properties[key] = String(value); }
    })},
    Utilities: {formatDate, parseDate: (text,tz,pattern) => {
      if (pattern !== 'yyyy-MM-dd HH:mm:ss' || !['UTC','Asia/Singapore'].includes(tz)) throw new Error('MOCK_UNSUPPORTED_TIMEZONE');
      return new Date(text.replace(' ', 'T') + (tz === 'UTC' ? 'Z' : '+08:00'));
    }, sleep: () => { metrics.sleeps++; }}
  };
  if (options.clockStepMs) {
    let tick = 0; class ClockDate extends Date { static now() { return (tick++) * options.clockStepMs; } }
    sandbox.Date = ClockDate;
  }
  vm.createContext(sandbox);
  vm.runInContext(fs.readFileSync(path.join(root, options.before ? 'before/Code.gs' : 'after/Code.gs'), 'utf8'), sandbox, {filename: options.before ? 'before/Code.gs' : 'after/Code.gs'});
  return {run: opts => sandbox.repairCrm(opts), broken: () => sandbox.brokenCrm(), sheets, metrics, logs, properties, context: sandbox};
}
module.exports = {createHarness, csv};