mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-20 21:23:08 +03:00
feat(json-viewer, yaml-viewer, currency-converter, geo-coordinates-converter): support intranet mirrors
Add json-schemas.catalog-url, currency-converter.url and geo-coordinates-converter.tile-url. Offline without a mirror, schema validation offers custom schemas only, the map is not shown and the currency converter is hidden. Show the external-access badge on the YAML viewer and the coordinates converter. Refs sharevb/it-tools#571 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
81c12017ce
commit
3af8e4a4cd
15 files changed
+183
-49
No files matched your search
@@ -1,9 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { code, countries, country } from 'currency-codes-ts';
|
||||
import converter from 'currency-exchanger-js';
|
||||
import { DEFAULT_CURRENCY_API_URL, convertWithRates, fetchCurrencyRates } from './currency-rates';
|
||||
import moneysData from './moneys.json';
|
||||
import { useQueryParam, useQueryParamOrStorage } from '@/composable/queryParams';
|
||||
import { getToolsSettingString, toolsSettings } from '@/tools-settings';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
@@ -21,21 +22,19 @@ const currentCurrency = useQueryParamOrStorage<string>({
|
||||
const amount = useQueryParam({ tool: 'currency-conv', name: 'amount', defaultValue: 1 });
|
||||
const currentDatetime = ref(Date.now());
|
||||
|
||||
// An intranet mirror of the currency-api files, configured in tools-settings.json
|
||||
const currencyApiUrl = getToolsSettingString(toolsSettings, 'currency-converter', 'url') || DEFAULT_CURRENCY_API_URL;
|
||||
|
||||
const convertedCurrencies = computedAsync<Record<string, number>>(async () => {
|
||||
const currentCurrencyValue = currentCurrency.value;
|
||||
const currentDatetimeValue = currentDatetime.value;
|
||||
const amountValue = amount.value;
|
||||
const otherCurrenciesValues = otherCurrencies.value;
|
||||
|
||||
// Always the latest rates: currency-exchanger-js, used before, ignored the date too. One fetch covers all targets.
|
||||
const rates = await fetchCurrencyRates(currencyApiUrl, currentCurrencyValue);
|
||||
let result = {};
|
||||
for (const targetCurrency of otherCurrenciesValues) {
|
||||
const value = await converter.convertOnDate(
|
||||
amountValue,
|
||||
currentCurrencyValue,
|
||||
targetCurrency.name,
|
||||
new Date(currentDatetimeValue),
|
||||
);
|
||||
result = { ...result, [targetCurrency.name]: value };
|
||||
result = { ...result, [targetCurrency.name]: convertWithRates(rates, amountValue, targetCurrency.name) };
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { DEFAULT_CURRENCY_API_URL, convertWithRates, currencyRatesUrl, fetchCurrencyRates } from './currency-rates';
|
||||
|
||||
describe('currency-rates', () => {
|
||||
it('builds the jsDelivr URL by default', () => {
|
||||
expect(currencyRatesUrl(DEFAULT_CURRENCY_API_URL, ' EUR ')).to.equal(
|
||||
'https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json',
|
||||
);
|
||||
});
|
||||
|
||||
it('builds mirror URLs with or without a trailing slash', () => {
|
||||
expect(currencyRatesUrl('https://intranet.example/currency-api/', 'usd')).to.equal(
|
||||
'https://intranet.example/currency-api/v1/currencies/usd.json',
|
||||
);
|
||||
expect(currencyRatesUrl('https://intranet.example/currency-api', 'usd')).to.equal(
|
||||
'https://intranet.example/currency-api/v1/currencies/usd.json',
|
||||
);
|
||||
});
|
||||
|
||||
it('fetches the rates of the base currency and converts with them', async () => {
|
||||
const fetchFn = vi.fn<(url: string) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ date: '2026-10-04', eur: { usd: 1.1, sek: 11.5 } })),
|
||||
);
|
||||
|
||||
const rates = await fetchCurrencyRates('https://intranet.example/currency-api/', 'EUR', fetchFn);
|
||||
|
||||
expect(fetchFn).toHaveBeenCalledWith('https://intranet.example/currency-api/v1/currencies/eur.json');
|
||||
expect(convertWithRates(rates, 2, 'USD')).to.equal(2.2);
|
||||
expect(convertWithRates(rates, 2, 'xyz')).toBeNaN();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
// Exchange rates from https://github.com/fawazahmed0/exchange-api, read the way currency-exchanger-js did, but from a
|
||||
// configurable base URL so an intranet mirror of the package's file layout can be used instead of jsDelivr.
|
||||
|
||||
/** Root of the @fawazahmed0/currency-api package; it serves `v1/currencies/<code>.json` with the latest rates */
|
||||
export const DEFAULT_CURRENCY_API_URL = 'https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/';
|
||||
|
||||
export function currencyRatesUrl(baseUrl: string, currency: string) {
|
||||
const base = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
|
||||
return `${base}v1/currencies/${currency.trim().toLowerCase()}.json`;
|
||||
}
|
||||
|
||||
/** Rates of one unit of `currency` in every other currency, keyed by lowercase currency code */
|
||||
export async function fetchCurrencyRates(
|
||||
baseUrl: string,
|
||||
currency: string,
|
||||
fetchFn: (url: string) => Promise<Response> = fetch,
|
||||
): Promise<Record<string, number>> {
|
||||
const response = await fetchFn(currencyRatesUrl(baseUrl, currency));
|
||||
const data = await response.json();
|
||||
return data[currency.trim().toLowerCase()];
|
||||
}
|
||||
|
||||
/** `amount` of the base currency converted with `rates` (NaN when the target currency is unknown, like before) */
|
||||
export function convertWithRates(rates: Record<string, number>, amount: number, toCurrency: string) {
|
||||
return amount * rates[toCurrency.trim().toLowerCase()];
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defineTool } from '../tool';
|
||||
import { getToolsSettingString } from '@/utils/tools-settings';
|
||||
import { translate as t } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
@@ -11,4 +12,5 @@ export const tool = defineTool({
|
||||
createdAt: new Date('2024-08-15'),
|
||||
category: 'Data',
|
||||
externAccessDescription: t('tools.currency-converter.externalAccess'),
|
||||
requiresInternet: (settings) => !getToolsSettingString(settings, 'currency-converter', 'url'),
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { flatten } from 'flatten-anything';
|
||||
import { convertFrom } from './geo-coordinates-converter.service';
|
||||
import { objectArrayToData } from '@/utils/objectarray.export';
|
||||
import { useQueryParam, useQueryParamOrStorage } from '@/composable/queryParams';
|
||||
import { getToolsSettingString, isOfflineMode, toolsSettings } from '@/tools-settings';
|
||||
import proj4 from 'proj4';
|
||||
|
||||
import L from 'leaflet';
|
||||
@@ -150,10 +151,16 @@ const utm = reactive({
|
||||
northing: 5411932,
|
||||
});
|
||||
|
||||
// Map tiles come from tools-settings.json `"geo-coordinates-converter": { "tile-url": "..." }` (an intranet tile
|
||||
// server) or OpenStreetMap; offline without a tile server there is no map at all, the conversions still work.
|
||||
const tileUrl = getToolsSettingString(toolsSettings, 'geo-coordinates-converter', 'tile-url');
|
||||
const tileAttribution = getToolsSettingString(toolsSettings, 'geo-coordinates-converter', 'tile-attribution');
|
||||
const showMap = !isOfflineMode || tileUrl !== '';
|
||||
|
||||
const mapRef = ref<HTMLElement | null>(null);
|
||||
watch(mapRef, () => initMap());
|
||||
let map: L.Map;
|
||||
let marker: L.Marker;
|
||||
let map: L.Map | undefined;
|
||||
let marker: L.Marker | undefined;
|
||||
|
||||
// -----------------------------
|
||||
// HELPERS
|
||||
@@ -238,16 +245,20 @@ function initMap() {
|
||||
}
|
||||
map = L.map(mapRef.value).setView([decimal.lat, decimal.lng], 13);
|
||||
|
||||
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||||
L.tileLayer(tileUrl || 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: tileUrl
|
||||
? tileAttribution
|
||||
: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||||
referrerPolicy: 'strict-origin-when-cross-origin',
|
||||
crossOrigin: true,
|
||||
// CORS-mode tile requests would fail against an intranet tile server that sends no CORS headers
|
||||
crossOrigin: !tileUrl,
|
||||
}).addTo(map);
|
||||
|
||||
marker = L.marker([decimal.lat, decimal.lng], { draggable: true }).addTo(map);
|
||||
const mapMarker = L.marker([decimal.lat, decimal.lng], { draggable: true }).addTo(map);
|
||||
marker = mapMarker;
|
||||
|
||||
marker.on('dragend', () => {
|
||||
const pos = marker.getLatLng();
|
||||
mapMarker.on('dragend', () => {
|
||||
const pos = mapMarker.getLatLng();
|
||||
decimal.lat = Number.parseFloat(pos.lat.toFixed(6));
|
||||
decimal.lng = Number.parseFloat(pos.lng.toFixed(6));
|
||||
decimal.latDir = pos.lat >= 0 ? 'N' : 'S';
|
||||
@@ -270,8 +281,8 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
function updateMarker() {
|
||||
marker.setLatLng([decimal.lat, decimal.lng]);
|
||||
map.setView([decimal.lat, decimal.lng]);
|
||||
marker?.setLatLng([decimal.lat, decimal.lng]);
|
||||
map?.setView([decimal.lat, decimal.lng]);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -359,7 +370,7 @@ function updateMarker() {
|
||||
</n-form>
|
||||
</n-card>
|
||||
|
||||
<div ref="mapRef" style="height: 400px; width: 100%; border-radius: 8px; overflow: hidden" />
|
||||
<div v-if="showMap" ref="mapRef" style="height: 400px; width: 100%; border-radius: 8px; overflow: hidden" />
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="proj" :tab="t('tools.geo-coordinates-converter.texts.decimal-projections')">
|
||||
<n-radio-group v-model:value="sourceSystem" mb-2>
|
||||
|
||||
@@ -10,5 +10,5 @@ export const tool = defineTool({
|
||||
icon: defineAsyncComponent(() => import('@tabler/icons-vue/dist/esm/icons/IconWorldPin.mjs')),
|
||||
createdAt: new Date('2026-01-09'),
|
||||
category: 'Converters',
|
||||
externAccessDescription: 'This tool access OpenStreetMap to display the World map using the Leaflet library.',
|
||||
externAccessDescription: t('tools.geo-coordinates-converter.externalAccess'),
|
||||
});
|
||||
@@ -54,7 +54,11 @@ const schemaUrl = useQueryParamOrStorage<string>({
|
||||
storageName: 'json-editor:schema',
|
||||
defaultValue: '',
|
||||
});
|
||||
const { schemas, errors: validationErrors } = useJsonSchemaValidation({ json: jsonText, schemaUrl, schemaData });
|
||||
const {
|
||||
schemas,
|
||||
errors: validationErrors,
|
||||
catalogAvailable,
|
||||
} = useJsonSchemaValidation({ json: jsonText, schemaUrl, schemaData });
|
||||
|
||||
function tryAutoRepair() {
|
||||
try {
|
||||
@@ -128,6 +132,7 @@ const formattedJson = computed(() => {
|
||||
...schemas.map((s) => ({ label: `${s.name} / ${s.description}`, value: s.url })),
|
||||
]"
|
||||
filterable
|
||||
:tag="!catalogAvailable"
|
||||
mb-4
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
@@ -37,7 +37,11 @@ const schemaUrl = useQueryParamOrStorage<string>({
|
||||
storageName: 'json-linter:schema',
|
||||
defaultValue: '',
|
||||
});
|
||||
const { schemas, errors: validationErrors } = useJsonSchemaValidation({ json: jsonContent, schemaUrl, schemaData });
|
||||
const {
|
||||
schemas,
|
||||
errors: validationErrors,
|
||||
catalogAvailable,
|
||||
} = useJsonSchemaValidation({ json: jsonContent, schemaUrl, schemaData });
|
||||
|
||||
const indentSize = useITStorage('json-linter:indent-size', 3);
|
||||
const autoRepair = useITStorage('json-linter:repair', true);
|
||||
@@ -88,6 +92,7 @@ const cleanJson = computed(() => {
|
||||
...schemas.map((s) => ({ label: `${s.name} / ${s.description}`, value: s.url })),
|
||||
]"
|
||||
filterable
|
||||
:tag="!catalogAvailable"
|
||||
mb-4
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
@@ -50,7 +50,11 @@ const schemaUrl = useQueryParamOrStorage<string>({
|
||||
storageName: 'json-prettify:schema',
|
||||
defaultValue: '',
|
||||
});
|
||||
const { schemas, errors: validationErrors } = useJsonSchemaValidation({ json: rawJson, schemaUrl, schemaData });
|
||||
const {
|
||||
schemas,
|
||||
errors: validationErrors,
|
||||
catalogAvailable,
|
||||
} = useJsonSchemaValidation({ json: rawJson, schemaUrl, schemaData });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -95,6 +99,7 @@ const { schemas, errors: validationErrors } = useJsonSchemaValidation({ json: ra
|
||||
...schemas.map((s) => ({ label: `${s.name} / ${s.description}`, value: s.url })),
|
||||
]"
|
||||
filterable
|
||||
:tag="!catalogAvailable"
|
||||
mb-4
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { DEFAULT_SCHEMA_CATALOG_URL, fetchSchemaCatalog, resolveSchemaCatalogUrl } from './schema-catalog';
|
||||
|
||||
describe('schema-catalog', () => {
|
||||
const mirror = { 'json-schemas': { 'catalog-url': ' https://intranet.example/schemastore/catalog.json ' } };
|
||||
|
||||
it('uses schemastore.org online and no catalog offline when no mirror is configured', () => {
|
||||
expect(resolveSchemaCatalogUrl({}, false)).to.equal(DEFAULT_SCHEMA_CATALOG_URL);
|
||||
expect(resolveSchemaCatalogUrl({}, true)).to.equal('');
|
||||
});
|
||||
|
||||
it('uses the configured mirror online and offline', () => {
|
||||
expect(resolveSchemaCatalogUrl(mirror, false)).to.equal('https://intranet.example/schemastore/catalog.json');
|
||||
expect(resolveSchemaCatalogUrl(mirror, true)).to.equal('https://intranet.example/schemastore/catalog.json');
|
||||
});
|
||||
|
||||
it('does not fetch without a catalog URL', async () => {
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch');
|
||||
expect(await fetchSchemaCatalog('')).to.deep.equal([]);
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
fetchSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { type ToolsSettings, getToolsSettingString } from '@/utils/tools-settings';
|
||||
|
||||
export interface SchemaStore {
|
||||
name: string;
|
||||
description: string;
|
||||
url: string;
|
||||
fileMatch: string[];
|
||||
versions?: string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_SCHEMA_CATALOG_URL = 'https://www.schemastore.org/api/json/catalog.json';
|
||||
|
||||
/**
|
||||
* The schema catalog to list in the schema picker: `"json-schemas": { "catalog-url": "..." }` from tools-settings.json
|
||||
* (e.g. an intranet mirror of schemastore.org), else schemastore.org itself, except in offline mode where there is
|
||||
* no catalog ('') and only custom or user-entered schemas are available.
|
||||
*/
|
||||
export function resolveSchemaCatalogUrl(settings: ToolsSettings, offline: boolean): string {
|
||||
return getToolsSettingString(settings, 'json-schemas', 'catalog-url') || (offline ? '' : DEFAULT_SCHEMA_CATALOG_URL);
|
||||
}
|
||||
|
||||
export async function fetchSchemaCatalog(catalogUrl: string): Promise<SchemaStore[]> {
|
||||
if (!catalogUrl) {
|
||||
return [];
|
||||
}
|
||||
const catalog = await fetch(catalogUrl);
|
||||
const catalogJson: { $schemaUrl: string; schemas: SchemaStore[]; version: number } = await catalog.json();
|
||||
return catalogJson.schemas;
|
||||
}
|
||||
@@ -1,14 +1,8 @@
|
||||
import { type Schema, Validator } from 'jsonschema';
|
||||
import { isRef, onBeforeMount, ref, watch } from 'vue';
|
||||
import { type MaybeRef, get } from '@vueuse/core';
|
||||
|
||||
export interface SchemaStore {
|
||||
name: string;
|
||||
description: string;
|
||||
url: string;
|
||||
fileMatch: string[];
|
||||
versions?: string[];
|
||||
}
|
||||
import { type SchemaStore, fetchSchemaCatalog, resolveSchemaCatalogUrl } from './schema-catalog';
|
||||
import { isOfflineMode, toolsSettings } from '@/tools-settings';
|
||||
|
||||
export function useJsonSchemaValidation({
|
||||
json,
|
||||
@@ -23,10 +17,12 @@ export function useJsonSchemaValidation({
|
||||
const schema = ref<Schema | null>(null);
|
||||
const errors = ref<string[]>([]);
|
||||
|
||||
// Offline without a configured catalog mirror there is no catalog to pick from: only custom or user-entered schemas
|
||||
const catalogUrl = resolveSchemaCatalogUrl(toolsSettings, isOfflineMode);
|
||||
const catalogAvailable = catalogUrl !== '';
|
||||
|
||||
onBeforeMount(async () => {
|
||||
const catalog = await fetch('https://www.schemastore.org/api/json/catalog.json');
|
||||
const catalogJson: { $schemaUrl: string; schemas: SchemaStore[]; version: number } = await catalog.json();
|
||||
schemas.value = catalogJson.schemas;
|
||||
schemas.value = await fetchSchemaCatalog(catalogUrl);
|
||||
});
|
||||
|
||||
watch(
|
||||
@@ -81,5 +77,5 @@ export function useJsonSchemaValidation({
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
return { schemas, errors };
|
||||
return { schemas, errors, catalogAvailable };
|
||||
}
|
||||
@@ -11,4 +11,5 @@ export const tool = defineTool({
|
||||
createdAt: new Date('2024-01-31'),
|
||||
npmPackages: ['yaml'],
|
||||
category: 'YAML',
|
||||
externAccessDescription: t('tools.yaml-prettify.externalAccess'),
|
||||
});
|
||||
@@ -5,14 +5,8 @@ import YAML from 'yaml';
|
||||
import Ajv from 'ajv';
|
||||
import AjvErrors from 'ajv-errors';
|
||||
import { yamlParse } from 'composeverter';
|
||||
|
||||
export interface SchemaStore {
|
||||
name: string;
|
||||
description: string;
|
||||
url: string;
|
||||
fileMatch: string[];
|
||||
versions?: string[];
|
||||
}
|
||||
import { type SchemaStore, fetchSchemaCatalog, resolveSchemaCatalogUrl } from '../json-viewer/schema-catalog';
|
||||
import { isOfflineMode, toolsSettings } from '@/tools-settings';
|
||||
|
||||
interface NodeWithRange {
|
||||
range?: number[];
|
||||
@@ -31,10 +25,12 @@ export function useYamlSchemaValidation({
|
||||
const schema = ref<Schema | null>(null);
|
||||
const errors = ref<string[]>([]);
|
||||
|
||||
// Offline without a configured catalog mirror there is no catalog to pick from: only custom or user-entered schemas
|
||||
const catalogUrl = resolveSchemaCatalogUrl(toolsSettings, isOfflineMode);
|
||||
const catalogAvailable = catalogUrl !== '';
|
||||
|
||||
onBeforeMount(async () => {
|
||||
const catalog = await fetch('https://www.schemastore.org/api/json/catalog.json');
|
||||
const catalogJson: { $schemaUrl: string; schemas: SchemaStore[]; version: number } = await catalog.json();
|
||||
schemas.value = catalogJson.schemas;
|
||||
schemas.value = await fetchSchemaCatalog(catalogUrl);
|
||||
});
|
||||
|
||||
watch(
|
||||
@@ -113,5 +109,5 @@ export function useYamlSchemaValidation({
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
return { schemas, errors };
|
||||
return { schemas, errors, catalogAvailable };
|
||||
}
|
||||
@@ -31,7 +31,11 @@ const MONACO_EDITOR_OPTIONS = {
|
||||
};
|
||||
|
||||
const schemaUrl = useQueryParamOrStorage({ name: 'schema', storageName: 'yaml-prettify:schema', defaultValue: '' });
|
||||
const { schemas, errors: validationErrors } = useYamlSchemaValidation({ yaml: rawYaml, schemaUrl, schemaData });
|
||||
const {
|
||||
schemas,
|
||||
errors: validationErrors,
|
||||
catalogAvailable,
|
||||
} = useYamlSchemaValidation({ yaml: rawYaml, schemaUrl, schemaData });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -66,6 +70,7 @@ const { schemas, errors: validationErrors } = useYamlSchemaValidation({ yaml: ra
|
||||
...schemas.map((s) => ({ label: `${s.name} / ${s.description}`, value: s.url })),
|
||||
]"
|
||||
filterable
|
||||
:tag="!catalogAvailable"
|
||||
mb-4
|
||||
/>
|
||||
</n-form-item>
|
||||
|
||||
Reference in new issue
Block a user