Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

feat: support Plausible custom date and timestamp ranges

Rudy Celekli1df3bec445ac
diff --git a/tests/plausible-dates.test.cjs b/tests/plausible-dates.test.cjs
new file mode 100644
index 0000000..f454809
--- /dev/null
+++ b/tests/plausible-dates.test.cjs
@@ -0,0 +1,40 @@
+const {test} = require('node:test')
+const assert = require('node:assert/strict')
+const {spawnSync} = require('node:child_process')
+const path = require('node:path')
+const cli = path.resolve(__dirname, '../tools/clis/plausible.js')
+function run(args, oracle='') {
+ const code = `global.fetch = async (url, options) => {
+ const assert = require('node:assert/strict'); const parsed = new URL(url);
+ const body = options.body ? JSON.parse(options.body) : null;
+ ${oracle}
+ return new Response(JSON.stringify({accepted:true,url,body}), {status:200});
+ }; process.argv = ['node',${JSON.stringify(cli)},...${JSON.stringify(args)}]; require(${JSON.stringify(cli)});`
+ return spawnSync(process.execPath,['-e',code], {encoding:'utf8',timeout:10000,env:{...process.env, PLAUSIBLE_API_KEY:'test-only-key'}})
+}
+function output(r) { assert.equal(r.status,0,r.stderr); return JSON.parse(r.stdout) }
+function localError(r, pattern) { const text = r.status === 0 ? r.stdout : r.stderr; assert.match(JSON.parse(text).error,pattern) }
+for (const sub of ['aggregate','timeseries','pages','sources','countries','devices','utm','query']) test(`${sub} sends a custom range as a JSON array`, () => {
+ const range=['2026-09-01','2026-09-30']
+ const p=output(run(['stats',sub,'--site-id','example.com','--metrics','visitors','--date-range',JSON.stringify(range)], "assert.deepEqual(body.date_range,['2026-09-01','2026-09-30']); assert.equal(options.method,'POST');")); assert.equal(p.accepted,true)
+})
+test('custom timestamp offsets are preserved exactly', () => {
+ const range=['2026-09-01T12:00:00+02:00','2026-09-01T15:59:59+02:00']
+ const p=output(run(['stats','aggregate','--site-id','example.com','--date-range',JSON.stringify(range)])); assert.deepEqual(p.body.date_range,range)
+})
+test('malformed arrays and non-string boundaries are rejected before HTTP', () => {
+ for (const range of ['[bad','[]','["2026-09-01"]','["a","b","c"]','[1,"2026-09-30"]','["","2026-09-30"]']) localError(run(['stats','aggregate','--site-id','example.com','--date-range',range], "throw new Error('unexpected query')"),/date-range/)
+})
+test('presets and the default retain their original request type', () => {
+ assert.equal(output(run(['stats','aggregate','--site-id','example.com','--date-range','7d'])).body.date_range,'7d')
+ assert.equal(output(run(['stats','aggregate','--site-id','example.com'])).body.date_range,'30d')
+})
+test('unrelated site routes are not gated by statistics range parsing', () => {
+ const p=output(run(['sites','list','--date-range','[bad'], "assert.equal(parsed.pathname,'/api/v1/sites'); assert.equal(options.method,'GET');")); assert.equal(p.accepted,true)
+})
+test('realtime visitor route is not gated by a range it does not use', () => {
+ const p=output(run(['stats','realtime','--site-id','example.com','--date-range','[bad'], "assert.equal(parsed.pathname,'/api/v1/stats/realtime/visitors');")); assert.equal(p.accepted,true)
+})
+test('custom range preview shows its array and masks authorization', () => {
+ const p=output(run(['stats','aggregate','--site-id','example.com','--date-range','["2026-09-01","2026-09-30"]','--dry-run'], "throw new Error('unexpected query')")); assert.deepEqual(p.body.date_range,['2026-09-01','2026-09-30']); assert.equal(p.headers.Authorization,'***')
+})
diff --git a/tools/clis/plausible.js b/tools/clis/plausible.js
index 62f4111..4a07efc 100755
--- a/tools/clis/plausible.js
+++ b/tools/clis/plausible.js
@@ -52,15 +52,29 @@ function parseArgs(args) {
const args = parseArgs(process.argv.slice(2))
const [cmd, sub, ...rest] = args._
+function statsDateRange(value) {
+ if (value === undefined) return '30d'
+ if (typeof value !== 'string') throw new Error('--date-range requires a preset or a JSON array of two date strings')
+ if (!value.trim().startsWith('[')) return value
+ let range
+ try { range = JSON.parse(value) } catch {
+ throw new Error('--date-range must be a valid JSON array of two date strings')
+ }
+ if (!Array.isArray(range) || range.length !== 2 || !range.every(date => typeof date === 'string' && date.trim())) {
+ throw new Error('--date-range must be a JSON array of two nonempty date strings')
+ }
+ return range
+}
+
async function main() {
let result
const siteId = args['site-id']
- const dateRange = args['date-range'] || '30d'
const limit = args.limit ? Number(args.limit) : 100
switch (cmd) {
case 'stats':
if (!siteId) { result = { error: '--site-id required (your domain, e.g. example.com)' }; break }
+ const dateRange = sub === 'realtime' ? undefined : statsDateRange(args['date-range'])
switch (sub) {
case 'aggregate': {
const metrics = args.metrics?.split(',') || ['visitors', 'pageviews', 'bounce_rate', 'visit_duration']
@@ -234,7 +248,7 @@ async function main() {
},
sites: 'sites [list | get --site-id <domain> | create --domain <domain> | delete --site-id <domain>]',
goals: 'goals [list | create --goal-type <event|page> --event-name <name> | delete --goal-id <id>] --site-id <domain>',
- options: '--date-range <day|7d|30d|month|6mo|12mo|year> --limit <n>',
+ options: '--date-range <preset|JSON array [start,end]> --limit <n>',
env: 'PLAUSIBLE_BASE_URL for self-hosted instances (default: https://plausible.io)',
}
}
diff --git a/tools/integrations/plausible.md b/tools/integrations/plausible.md
index 4d2f31a..3361b0a 100644
--- a/tools/integrations/plausible.md
+++ b/tools/integrations/plausible.md
@@ -175,3 +175,20 @@ GET https://plausible.io/api/v1/sites
- programmatic-seo
- cro
- utm-tracking
+
+## Custom date ranges in the CLI
+
+Pass custom boundaries as a JSON array of two strings. For example:
+
+```bash
+node tools/clis/plausible.js stats aggregate --site-id example.com \
+ --date-range '["2026-09-01","2026-09-30"]'
+```
+
+ISO8601 timestamps are also supported, including their timezone offsets:
+`--date-range '["2026-09-01T12:00:00+02:00","2026-09-01T15:59:59+02:00"]'`.
+The CLI sends these values as an array without converting them to UTC. Existing
+presets (such as `7d`) and the default `30d` remain strings. Malformed arrays or
+arrays without exactly two nonempty strings fail before the stats request;
+Plausible validates the date values. See the
+[Stats API date_range contract](https://plausible.io/docs/stats-api).