Compare commits

..
Author SHA1 Message Date
ShareVB fa01008dc8 fix: let user choice 'standard' vs 'aws'
Let the user choose between cron format (since help is different)
2024-09-22 12:27:49 +02:00
ShareVB 8754d626e1 Merge branch 'fix/crontab-enh' of https://github.com/sharevb/it-tools into fix/crontab-enh 2024-09-21 14:42:39 +02:00
ShareVB 605229f4ef fix: helpers dup % 2024-09-21 14:42:22 +02:00
sharevb 9fa58666e5 Merge branch 'main' into fix/crontab-enh 2024-09-21 14:38:42 +02:00
ShareVB c7154c36eb Merge remote-tracking branch 'origin/main' into fix/crontab-enh 2024-09-21 14:37:53 +02:00
ShareVB 0b4a261e06 Merge branch 'fix/crontab-enh' of https://github.com/sharevb/it-tools into fix/crontab-enh 2024-09-21 14:35:02 +02:00
sharevb 48b4904cf1 fix(Cron Parser): handle aws, next executions and TZ
Handle AWS Cron syntax and distinguishe from standard syntax (fix #855)
Add show crontab next 5 execution times (taken from #1283)
Add Timezone handling: fix #261
2024-09-21 14:33:13 +02:00
sharevb f1044b3e2b fix(Cron Parser): handle more patterns
Just use validation of cronstrue package
Fix #855
2024-05-01 23:40:37 +02:00
16 changed files with 326 additions and 858 deletions

No files matched your search

+3 -1
View File
@@ -135,6 +135,8 @@ declare module '@vue/runtime-core' {
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDivider: typeof import('naive-ui')['NDivider']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
@@ -144,6 +146,7 @@ declare module '@vue/runtime-core' {
NRadio: typeof import('naive-ui')['NRadio']
NRadioGroup: typeof import('naive-ui')['NRadioGroup']
NSpace: typeof import('naive-ui')['NSpace']
NSwitch: typeof import('naive-ui')['NSwitch']
NTable: typeof import('naive-ui')['NTable']
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
OtpCodeGeneratorAndValidator: typeof import('./src/tools/otp-code-generator-and-validator/otp-code-generator-and-validator.vue')['default']
@@ -166,7 +169,6 @@ declare module '@vue/runtime-core' {
SlugifyString: typeof import('./src/tools/slugify-string/slugify-string.vue')['default']
SpanCopyable: typeof import('./src/components/SpanCopyable.vue')['default']
SqlPrettify: typeof import('./src/tools/sql-prettify/sql-prettify.vue')['default']
StacktracePrettier: typeof import('./src/tools/stacktrace-prettier/stacktrace-prettier.vue')['default']
StringObfuscator: typeof import('./src/tools/string-obfuscator/string-obfuscator.vue')['default']
SvgPlaceholderGenerator: typeof import('./src/tools/svg-placeholder-generator/svg-placeholder-generator.vue')['default']
TemperatureConverter: typeof import('./src/tools/temperature-converter/temperature-converter.vue')['default']
+4 -5
View File
@@ -53,25 +53,26 @@
"change-case": "^4.1.2",
"colord": "^2.9.3",
"composerize-ts": "^0.6.2",
"countries-and-timezones": "^3.6.0",
"country-code-lookup": "^0.1.0",
"cron-parser": "^4.9.0",
"cron-validator": "^1.3.1",
"cronstrue": "^2.26.0",
"crypto-js": "^4.1.1",
"date-fns": "^2.29.3",
"dom-to-image-more": "^3.4.5",
"dompurify": "^3.0.6",
"email-normalizer": "^1.0.0",
"emojilib": "^3.0.10",
"event-cron-parser": "^1.0.34",
"figlet": "^1.7.0",
"figue": "^1.2.0",
"fuse.js": "^6.6.2",
"get-timezone-offset": "^1.0.5",
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"javastack.js": "^1.0.2",
"js-base64": "^3.7.6",
"json5": "^2.2.3",
"jsstack.js": "^2.0.0",
"jwt-decode": "^3.1.2",
"libphonenumber-js": "^1.10.28",
"lodash": "^4.17.21",
@@ -82,13 +83,11 @@
"monaco-editor": "^0.43.0",
"naive-ui": "^2.35.0",
"netmask": "^2.0.2",
"netstack.js": "^2.0.0",
"node-forge": "^1.3.1",
"oui-data": "^1.0.10",
"pdf-signature-reader": "^1.4.2",
"pinia": "^2.0.34",
"plausible-tracker": "^0.3.8",
"pythonstack.js": "^1.0.2",
"qrcode": "^1.5.1",
"randexp": "^0.5.3",
"sql-formatter": "^13.0.0",
+63 -658
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest';
import { getCronType, getLastExecutionTimes, isCronValid } from './crontab-generator.service';
describe('crontab-generator', () => {
describe('isCronValid', () => {
it('should return true for all valid formats', () => {
// standard format
expect(isCronValid('0 0 * * 1-5')).toBe(true);
expect(isCronValid('23 0-20/2 * * *')).toBe(true);
// AWS formats
expect(isCronValid('0 11-22 ? * MON-FRI *')).toBe(true);
expect(isCronValid('0 0 ? * 1 *')).toBe(true);
});
it('should check standard format', () => {
// standard format
expect(isCronValid('0 0 * * 1-5', 'standard')).toBe(true);
expect(isCronValid('23 0-20/2 * * *', 'standard')).toBe(true);
// AWS format
expect(isCronValid('0 11-22 ? * MON-FRI *', 'standard')).toBe(false);
expect(isCronValid('0 0 ? * 1 *', 'standard')).toBe(false);
});
it('should check aws format', () => {
// standard format
expect(isCronValid('0 0 * * 1-5', 'aws')).toBe(false);
expect(isCronValid('23 0-20/2 * * *', 'aws')).toBe(false);
// AWS format
expect(isCronValid('0 11-22 ? * MON-FRI *', 'aws')).toBe(true);
expect(isCronValid('0 0 ? * 1 *', 'aws')).toBe(true);
});
it('should return false for all invalid formats', () => {
expect(isCronValid('aert')).toBe(false);
expect(isCronValid('40 *')).toBe(false);
});
});
describe('getCronType', () => {
it('should return right type', () => {
expect(getCronType('0 0 * * 1-5')).toBe('standard');
expect(getCronType('23 0-20/2 * * *')).toBe('standard');
// AWS formats
expect(getCronType('0 11-22 ? * MON-FRI *')).toBe('aws');
expect(getCronType('0 0 ? * 1 *')).toBe('aws');
expect(getCronType('aert')).toBe(false);
expect(getCronType('40 *')).toBe(false);
});
});
describe('getLastExecutionTimes', () => {
it('should return next valid datetimes', () => {
expect(getLastExecutionTimes('0 0 * * 1-5')).toHaveLength(5);
expect(getLastExecutionTimes('23 0-20/2 * * *')).toHaveLength(5);
// AWS formats
expect(getLastExecutionTimes('0 11-22 ? * MON-FRI *')).toHaveLength(5);
expect(getLastExecutionTimes('0 0 ? * 1 *')).toHaveLength(5);
});
});
});
@@ -0,0 +1,47 @@
import { parseExpression } from 'cron-parser';
import EventCronParser from 'event-cron-parser';
export type CronType = 'standard' | 'aws';
export function getLastExecutionTimes(cronExpression: string, tz: string | undefined = undefined, count: number = 5) {
if (getCronType(cronExpression) === 'standard') {
const interval = parseExpression(cronExpression, { tz });
const times = [];
for (let i = 0; i < count; i++) {
times.push(interval.next().toJSON());
}
return times;
}
if (getCronType(cronExpression) === 'aws') {
const parsed = new EventCronParser(cronExpression);
const times = [];
for (let i = 0; i < count; i++) {
times.push(JSON.stringify(parsed.next()));
}
return times;
}
return [];
}
export function isCronValid(cronExpression: string, cronType: CronType | 'any' = 'any') {
const expressionCronType = getCronType(cronExpression);
return cronType === 'any' ? !!expressionCronType : expressionCronType === cronType;
}
export function getCronType(cronExpression: string) {
try {
parseExpression(cronExpression);
return 'standard';
}
catch (_) {
try {
const parsed = new EventCronParser(cronExpression);
parsed.validate();
return 'aws';
}
catch (_) {
}
}
return false;
}
+142 -10
View File
@@ -1,11 +1,10 @@
<script setup lang="ts">
import cronstrue from 'cronstrue';
import { isValidCron } from 'cron-validator';
import ctz from 'countries-and-timezones';
import getTimezoneOffset from 'get-timezone-offset';
import { type CronType, getLastExecutionTimes, isCronValid } from './crontab-generator.service';
import { useStyleStore } from '@/stores/style.store';
function isCronValid(v: string) {
return isValidCron(v, { allowBlankDay: true, alias: true, seconds: true });
}
import { useQueryParamOrStorage } from '@/composable/queryParams';
const styleStore = useStyleStore();
@@ -15,9 +14,25 @@ const cronstrueConfig = reactive({
dayOfWeekStartIndexZero: true,
use24HourTimeFormat: true,
throwExceptionOnParseError: true,
monthStartIndexZero: false,
tzOffset: (new Date()).getTimezoneOffset() / 60,
});
const helpers = [
// getTimezoneOffset(tz.name, now) / 60
const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const allTimezones = Object.values(ctz.getAllTimezones()).map((tz) => {
const timezoneUTCDSTOffset = tz.utcOffset === tz.dstOffset ? tz.utcOffsetStr : `${tz.utcOffsetStr}/${tz.dstOffsetStr}`;
return {
value: tz.name,
label: `${tz.name === browserTimezone ? 'Browser TZ - ' : ''}${tz.name} (${timezoneUTCDSTOffset})`,
};
});
const currentTimezone = useQueryParamOrStorage({ name: 'tz', storageName: 'crongen:tz', defaultValue: browserTimezone });
watchEffect(() => {
cronstrueConfig.tzOffset = -getTimezoneOffset(currentTimezone.value, new Date()) / 60;
});
const commonHelpers = [
{
symbol: '*',
meaning: 'Any value',
@@ -42,6 +57,10 @@ const helpers = [
example: '*/10 * * *',
equivalent: 'Every 10 minutes',
},
];
const standardHelpers = [
...commonHelpers,
{
symbol: '@yearly',
meaning: 'Once every year at midnight of 1 January',
@@ -92,6 +111,59 @@ const helpers = [
},
];
const awsHelpers = [
...commonHelpers,
{
symbol: '?',
meaning: 'One or another. In the Day-of-month field you could enter 7, and if you didn\'t care what day of the week the seventh was, you could enter ? in the Day-of-week field',
example: '9 * 7,9,11 5 ? 2021',
equivalent: 'At 9 minutes past the hour, every hour, on day 7, 9, and 11 of the month, only in May, only in 2021',
},
{
symbol: 'L',
meaning: 'The L wildcard in the Day-of-month or Day-of-week fields specifies the last day of the month or week.',
example: '9 * L 5 ? 2019,2020',
equivalent: 'At 9 minutes past the hour, every hour, on the last day of the month, only in May, only in 2019 and 2020',
},
{
symbol: 'W',
meaning: 'The W wildcard in the Day-of-month field specifies a weekday. In the Day-of-month field, 3W specifies the day closest to the third weekday of the month.',
example: '19 4 3W 9 ? 2019,2020',
equivalent: 'At 04:19 AM, on the weekday nearest day 3 of the month, only in September, only in 2019 and 2020',
},
{
symbol: '#',
meaning: 'The # wildcard in the Day-of-week field specifies the nieth weekday of the month. 3#5 specifies the fifth Wednesday of the month',
example: '9 8-20 ? 12 3#5 2019,2020',
equivalent: 'At 9 minutes past the hour, between 08:00 AM and 08:59 PM, on the fifth Wednesday of the month, only in December, only in 2019 and 2020',
},
];
const defaultAWSCronExpression = '0 0 ? * 1 *';
const defaultStandardCronExpression = '40 * * * *';
const cronType = ref<CronType>('standard');
watch(cronType,
(newCronType) => {
if (newCronType === 'aws') {
if (!cron.value || cron.value === defaultStandardCronExpression) {
cron.value = defaultAWSCronExpression;
}
}
else if (newCronType === 'standard') {
if (!cron.value || cron.value === defaultAWSCronExpression) {
cron.value = defaultStandardCronExpression;
}
}
},
);
const getHelpers = computed(() => {
if (cronType.value === 'aws') {
return awsHelpers;
}
return standardHelpers;
});
const cronString = computed(() => {
if (isCronValid(cron.value)) {
return cronstrue.toString(cron.value, cronstrueConfig);
@@ -101,10 +173,24 @@ const cronString = computed(() => {
const cronValidationRules = [
{
validator: (value: string) => isCronValid(value),
validator: (value: string) => isCronValid(value, cronType.value),
message: 'This cron is invalid',
},
];
const executionTimesString = computed(() => {
if (isCronValid(cron.value)) {
try {
const lastExecutionTimes = getLastExecutionTimes(cron.value, currentTimezone.value);
const executionTimesString = lastExecutionTimes.join('\n');
return `Next 5 execution times:\n${executionTimesString}`;
}
catch (e: any) {
return e.toString();
}
}
return ' ';
});
</script>
<template>
@@ -119,10 +205,27 @@ const cronValidationRules = [
/>
</div>
<n-radio-group v-model:value="cronType" name="radiogroup" mb-2 flex justify-center>
<n-space>
<n-radio
value="standard"
label="Unix standard"
/>
<n-radio
value="aws"
label="AWS"
/>
</n-space>
</n-radio-group>
<div class="cron-string">
{{ cronString }}
</div>
<div class="cron-execution-string">
{{ executionTimesString }}
</div>
<n-divider />
<div flex justify-center>
@@ -136,11 +239,21 @@ const cronValidationRules = [
<n-form-item label="Days start at 0">
<n-switch v-model:value="cronstrueConfig.dayOfWeekStartIndexZero" />
</n-form-item>
<n-form-item label="Months start at 0">
<n-switch v-model:value="cronstrueConfig.monthStartIndexZero" />
</n-form-item>
<c-select
v-model:value="currentTimezone"
searchable
label="Timezone:"
:options="allTimezones"
/>
</n-form>
</div>
</c-card>
<c-card>
<pre>
<pre v-if="cronType === 'standard'">
-- Standard CRON Syntax --
┌──────────── [optional] seconds (0 - 59)
| ┌────────── minute (0 - 59)
| | ┌──────── hour (0 - 23)
@@ -150,8 +263,19 @@ const cronValidationRules = [
| | | | | |
* * * * * * command</pre>
<pre v-if="cronType === 'aws'">
-- AWS CRON Syntax --
┌──────────── minute (0 - 59)
| ┌────────── hour (0 - 23)
| | ┌──────── day of month (1 - 31) OR ? OR L OR W
| | | ┌────── month (1 - 12) OR jan,feb,mar,apr ...
| | | | ┌──── day of week (0 - 6, sunday=0) OR sun,mon OR L ...
| | | | | ┌── year
| | | | | |
* * * * * *</pre>
<div v-if="styleStore.isSmallScreen">
<c-card v-for="{ symbol, meaning, example, equivalent } in helpers" :key="symbol" mb-3 important:border-none>
<c-card v-for="{ symbol, meaning, example, equivalent } in getHelpers" :key="symbol" mb-3 important:border-none>
<div>
Symbol: <strong>{{ symbol }}</strong>
</div>
@@ -168,7 +292,7 @@ const cronValidationRules = [
</c-card>
</div>
<c-table v-else :data="helpers" />
<c-table v-else :data="getHelpers" />
</c-card>
</template>
@@ -191,4 +315,12 @@ pre {
overflow: auto;
padding: 10px 0;
}
.cron-execution-string{
text-align: center;
font-size: 14px;
opacity: 0.8;
margin: 5px 0 15px;
white-space: pre-wrap;
}
</style>
+3
View File
@@ -0,0 +1,3 @@
declare module "get-timezone-offset" {
export default function(timeZoneName: string, date: Date);
}
+1
View File
@@ -20,6 +20,7 @@ export const tool = defineTool({
'day',
'minute',
'second',
'aws',
],
component: () => import('./crontab-generator.vue'),
icon: Alarm,
-2
View File
@@ -2,7 +2,6 @@ import { tool as base64FileConverter } from './base64-file-converter';
import { tool as base64StringConverter } from './base64-string-converter';
import { tool as basicAuthGenerator } from './basic-auth-generator';
import { tool as emailNormalizer } from './email-normalizer';
import { tool as stacktracePrettier } from './stacktrace-prettier';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
@@ -161,7 +160,6 @@ export const toolsByCategory: ToolCategory[] = [
emailNormalizer,
regexTester,
regexMemo,
stacktracePrettier,
],
},
{
-3
View File
@@ -1,3 +0,0 @@
declare module "dom-to-image-more" {
export function toPng(el: HTMLElement | undefined, options?: { bgcolor: string }) : Promise<string>;
}
-12
View File
@@ -1,12 +0,0 @@
import { Stack } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Stacktrace prettier',
path: '/stacktrace-prettier',
description: 'Highlight .Net and JS stacktraces',
keywords: ['stacktrace', 'prettier', 'highlighter'],
component: () => import('./stacktrace-prettier.vue'),
icon: Stack,
createdAt: new Date('2024-08-15'),
});
-3
View File
@@ -1,3 +0,0 @@
declare module "javastack.js" {
export default function javastack(selector: string, options: { prettyprint: boolean }) : void;
}
-3
View File
@@ -1,3 +0,0 @@
declare module "jsstack.js" {
export default function jsstack(selector: string) : void;
}
-5
View File
@@ -1,5 +0,0 @@
declare module "netstack.js" {
export default class netstack {
constructor(el: HTMLElement | undefined, options: { prettyprint: boolean })
}
}
-3
View File
@@ -1,3 +0,0 @@
declare module "pythonstack.js" {
export default function pythonstack(selector: string, options: { prettyprint: boolean }) : void;
}
@@ -1,153 +0,0 @@
<script setup lang="ts">
import JSStack from 'jsstack.js';
import JavaStack from 'javastack.js';
import PythonStack from 'pythonstack.js';
import NetStack from 'netstack.js';
import domtoimage from 'dom-to-image-more';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { useStyleStore } from '@/stores/style.store';
import { useCopy } from '@/composable/copy';
const styleStore = useStyleStore();
const stackType = useQueryParamOrStorage<'net' | 'js' | 'java' | 'python'>({ name: 'type', storageName: 'stackfmt:type', defaultValue: 'net' });
const stackTrace = ref('');
const formatedStackTrace = ref<HTMLElement>();
const stackTraceText = ref('');
watchEffect(() => {
if (!formatedStackTrace.value) {
return;
}
let cleanedStackTrace;
try {
cleanedStackTrace = JSON.parse(stackTrace.value);
}
catch (_) {
cleanedStackTrace = stackTrace.value.replace(/(\\r)?\\n/g, '\n').replace(/(?:^['"])|(?:['"]$)/, '');
};
try {
if (stackType.value === 'js') {
formatedStackTrace.value.textContent = cleanedStackTrace;
JSStack('.stacktrace');
}
else if (stackType.value === 'java') {
formatedStackTrace.value.textContent = cleanedStackTrace;
JavaStack('.stacktrace', { prettyprint: true });
}
else if (stackType.value === 'python') {
formatedStackTrace.value.textContent = cleanedStackTrace;
PythonStack('.stacktrace', { prettyprint: true });
}
else if (stackType.value === 'net') {
formatedStackTrace.value.innerText = cleanedStackTrace;
const _ = new NetStack(formatedStackTrace.value, { prettyprint: true });
}
stackTraceText.value = formatedStackTrace.value.innerText;
}
catch {}
});
const stackTraceMarkdown = computed(() => {
let lang;
if (stackType.value === 'net') {
lang = 'csharp';
}
else if (stackType.value === 'js') {
lang = 'javascript';
}
else if (stackType.value === 'java') {
lang = 'java';
}
else if (stackType.value === 'python') {
lang = 'python';
}
return `\`\`\`${lang}\n${formatedStackTrace.value?.innerText}\n\`\`\``;
});
const { copy: copyText } = useCopy({ source: stackTraceText, text: 'Formatted stacktrace copied to the clipboard' });
const { copy: copyMarkdown } = useCopy({ source: stackTraceMarkdown, text: 'Markdown Formatted stacktrace copied to the clipboard' });
async function downloadAsPNG() {
const dataUrl = await domtoimage.toPng(formatedStackTrace.value, { bgcolor: styleStore.isDarkTheme ? '#333' : '#fff' });
const link = document.createElement('a');
link.download = 'stacktrace.png';
link.href = dataUrl;
link.click();
}
const wrap = ref(true);
</script>
<template>
<div max-w-600px>
<n-radio-group v-model:value="stackType" name="radiogroup" mb-2 flex justify-center>
<n-space>
<n-radio
value="net"
label=".Net"
/>
<n-radio
value="js"
label="Javascript"
/>
<n-radio
value="python"
label="Python"
/>
<n-radio
value="java"
label="Java"
/>
</n-space>
</n-radio-group>
<div mb-2 flex justify-center>
<n-checkbox v-model:checked="wrap">
Wrap lines?
</n-checkbox>
</div>
<c-input-text
v-model:value="stackTrace"
label="Stacktrace"
placeholder="Paste your stacktrace here.."
multiline
rows="5"
/>
<n-divider />
<pre ref="formatedStackTrace" class="stacktrace" :style="{ padding: '20px', whiteSpace: wrap ? 'pre-wrap' : 'pre', overflowX: 'auto', wordBreak: 'break-all' }" />
<div v-if="stackTraceText" flex justify-center gap-1>
<c-button @click="copyText()">
Copy Formatted (Text)
</c-button>
<c-button @click="copyMarkdown()">
Copy Formatted (Markdown)
</c-button>
<c-button @click="downloadAsPNG()">
Download as PNG
</c-button>
</div>
</div>
</template>
<style lang="less" scoped>
::v-deep(.stacktrace) {
pre, code {background-color:#333 !important; color: #fff !important;}
.st-type {color: #0a8472; font-weight: bolder;}
.st-method {color: #70c9ba; font-weight: bolder;}
.st-frame-params {color: #ffffff; font-weight: normal;}
.st-param-type {color: #0a8472;}
.st-param-name {color: #ffffff;}
.st-file {color:#f8b068;}
.st-line {color:#ff4f68;}
.st-methodName {color: #70c9ba;font-weight: bolder;}
.st-column {color: #f8b068;}
.st-lineNumber {color: #ff4f68;}
.st-fileName {color: #85dbff;}
.st-intro {color: #0044dd;}
.st-exception {color: #e40000;}
}
</style>