diff --git a/package.json b/package.json index 8672ee68..905183fb 100644 --- a/package.json +++ b/package.json @@ -86,7 +86,9 @@ "@lezer/highlight": "^1.2.3", "@mdit/plugin-align": "^0.16.0", "@noble/ciphers": "^1.3.0", + "@plausible-analytics/tracker": "^0.4.6", "@regexper/render": "^1.0.0", + "@resvg/resvg-wasm": "^2.6.2", "@sindresorhus/slugify": "^3.0.0", "@skeepit/unicode-to-gsm7": "^1.0.0", "@tabler/icons-vue": "^3.44.0", @@ -157,7 +159,7 @@ "cron-validator": "^1.4.0", "cronstrue": "^3.24.0", "cross-spawn": "^7.0.6", - "crypto-js": "^4.2.0", + "crypto-es": "^3.1.3", "csstoxpath": "^2.0.0", "curlconverter": "^4.12.0", "currency-codes-ts": "^3.0.0", @@ -314,7 +316,6 @@ "pdfjs-dist": "^4.10.38", "picomatch": "^4.0.5", "pinia": "^3.0.4", - "plausible-tracker": "^0.3.9", "podletjs": "^1.0.2", "port-numbers": "^8.0.32", "postal-mime": "^2.7.5", @@ -357,7 +358,6 @@ "staveless-futhark": "^0.6.1", "stopword": "^3.1.5", "stringify-object": "^7.0.0", - "svg2png-wasm": "^1.4.1", "svgo": "^3.3.3", "swagger-ui-dist": "^5.32.8", "swap-case": "^3.0.3", @@ -412,10 +412,8 @@ "@playwright/test": "^1.62.0", "@tsconfig/node24": "^24.0.4", "@types/arr-diff": "^4.0.3", - "@types/bcryptjs": "^3.0.0", "@types/big.js": "^7.0.0", "@types/codemirror": "^5.60.17", - "@types/crypto-js": "^4.2.2", "@types/damerau-levenshtein": "^1.0.2", "@types/emscripten": "^1.41.5", "@types/har-format": "^1.2.16", @@ -448,7 +446,6 @@ "@types/ua-parser-js": "^0.7.39", "@types/unist": "^3.0.3", "@types/utf8": "^3.0.3", - "@types/uuid": "^11.0.0", "@vitejs/plugin-vue": "^6.0.7", "@vitejs/plugin-vue-jsx": "^5.1.6", "@vue/compiler-sfc": "^3.5.39", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 21f69f31..26bd0379 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -147,9 +147,15 @@ importers: '@noble/ciphers': specifier: ^1.3.0 version: 1.3.0 + '@plausible-analytics/tracker': + specifier: ^0.4.6 + version: 0.4.6 '@regexper/render': specifier: ^1.0.0 version: 1.0.0 + '@resvg/resvg-wasm': + specifier: ^2.6.2 + version: 2.6.2 '@sindresorhus/slugify': specifier: ^3.0.0 version: 3.0.0 @@ -360,9 +366,9 @@ importers: cross-spawn: specifier: ^7.0.6 version: 7.0.6 - crypto-js: - specifier: ^4.2.0 - version: 4.2.0 + crypto-es: + specifier: ^3.1.3 + version: 3.1.3 csstoxpath: specifier: ^2.0.0 version: 2.0.0 @@ -831,9 +837,6 @@ importers: pinia: specifier: ^3.0.4 version: 3.0.4(typescript@6.0.3)(vue@3.5.39(typescript@6.0.3)) - plausible-tracker: - specifier: ^0.3.9 - version: 0.3.9 podletjs: specifier: ^1.0.2 version: 1.0.2 @@ -960,9 +963,6 @@ importers: stringify-object: specifier: ^7.0.0 version: 7.0.0 - svg2png-wasm: - specifier: ^1.4.1 - version: 1.4.1 svgo: specifier: ^3.3.3 version: 3.3.3 @@ -1120,18 +1120,12 @@ importers: '@types/arr-diff': specifier: ^4.0.3 version: 4.0.3 - '@types/bcryptjs': - specifier: ^3.0.0 - version: 3.0.0 '@types/big.js': specifier: ^7.0.0 version: 7.0.0 '@types/codemirror': specifier: ^5.60.17 version: 5.60.17 - '@types/crypto-js': - specifier: ^4.2.2 - version: 4.2.2 '@types/damerau-levenshtein': specifier: ^1.0.2 version: 1.0.2 @@ -1228,9 +1222,6 @@ importers: '@types/utf8': specifier: ^3.0.3 version: 3.0.3 - '@types/uuid': - specifier: ^11.0.0 - version: 11.0.0 '@vitejs/plugin-vue': specifier: ^6.0.7 version: 6.0.7(vite@8.1.3(@types/node@24.13.3)(jiti@2.7.0)(less@4.6.7)(terser@5.48.0)(yaml@2.9.0))(vue@3.5.39(typescript@6.0.3)) @@ -3732,6 +3723,9 @@ packages: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} + '@plausible-analytics/tracker@0.4.6': + resolution: {integrity: sha512-nbu6xGgSP6jeYuoVklZBzucUnIpo75tVu3Kr+R0EDycVKaMC/jF5Q/YCaM/8gR4fPZ1IDcXt6FdBJFZ1uZwEPA==} + '@playwright/test@1.62.0': resolution: {integrity: sha512-9zOJ6ZQRAena31MpOH9VSzIz8Ou3YJ/wtY/eQm5T2uhfhG7/U3COrMS8xOtUrZrp9OgdmzEnIYODye3nY1VqzA==} engines: {node: '>=20'} @@ -3793,6 +3787,10 @@ packages: '@codemirror/state': ^6.0.0 '@codemirror/view': ^6.0.0 + '@resvg/resvg-wasm@2.6.2': + resolution: {integrity: sha512-FqALmHI8D4o6lk/LRWDnhw95z5eO+eAa6ORjVg09YRR7BkcM6oPHU9uyC0gtQG5vpFLvgpeU4+zEAz2H8APHNw==} + engines: {node: '>= 10'} + '@rolldown/binding-android-arm64@1.1.4': resolution: {integrity: sha512-EZLpf/8y7GXkkra90ML47kzik/GMP3EMcE9bPyHmRfxLC6z9+aW5A8poCsoxjrT5GfEcNAAvWwUHjvP1pUQkfw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -4406,10 +4404,6 @@ packages: '@types/asn1@0.2.4': resolution: {integrity: sha512-V91DSJ2l0h0gRhVP4oBfBzRBN9lAbPUkGDMCnwedqPKX2d84aAMc9CulOvxdw1f7DfEYx99afab+Rsm3e52jhA==} - '@types/bcryptjs@3.0.0': - resolution: {integrity: sha512-WRZOuCuaz8UcZZE4R5HXTco2goQSI2XxjGY3hbM/xDvwmqFWd4ivooImsMx65OKM6CtNKbnZ5YL+YwAwK7c1dg==} - deprecated: This is a stub types definition. bcryptjs provides its own type definitions, so you do not need this installed. - '@types/big.js@7.0.0': resolution: {integrity: sha512-WfAGp7IbJvyB8EmWK4tJD24rJRAL6uVbw3LV/hJntFNam+os9KWKj0PzXo8rRRpjupYK8U0M8FoBB8dBhWF2dg==} @@ -4419,9 +4413,6 @@ packages: '@types/codemirror@5.60.17': resolution: {integrity: sha512-AZq2FIsUHVMlp7VSe2hTfl5w4pcUkoFkM3zVsRKsn1ca8CXRDYvnin04+HP2REkwsxemuHqvDofdlhUWNpbwfw==} - '@types/crypto-js@4.2.2': - resolution: {integrity: sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==} - '@types/d3-array@3.2.2': resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} @@ -4696,10 +4687,6 @@ packages: '@types/utf8@3.0.3': resolution: {integrity: sha512-+lqLGxWZsEe4Z6OrzBI7Ym4SMUTaMS5yOrHZ0/IL0bpIye1Qbs4PpobJL2mLDbftUXlPFZR7fu6d1yM+bHLX1w==} - '@types/uuid@11.0.0': - resolution: {integrity: sha512-HVyk8nj2m+jcFRNazzqyVKiZezyhDKrGUA3jlEcg/nZ6Ms+qHwocba1Y/AaVaznJTAM9xpdFSh+ptbNrhOGvZA==} - deprecated: This is a stub types definition. uuid provides its own type definitions, so you do not need this installed. - '@types/validator@13.15.10': resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==} @@ -5134,10 +5121,12 @@ packages: '@xmldom/xmldom@0.8.13': resolution: {integrity: sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==} engines: {node: '>=10.0.0'} + deprecated: this version has critical issues, please update to the latest version '@xmldom/xmldom@0.9.10': resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==} engines: {node: '>=14.6'} + deprecated: this version has critical issues, please update to the latest version '@xterm/xterm@5.5.0': resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==} @@ -6041,6 +6030,7 @@ packages: cron-parser@4.9.0: resolution: {integrity: sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==} engines: {node: '>=12.0.0'} + deprecated: v4 is no longer maintained, upgrade to v5 cron-validator@1.4.0: resolution: {integrity: sha512-wGcJ9FCy65iaU6egSH8b5dZYJF7GU/3Jh06wzaT9lsa5dbqExjljmu+0cJ8cpKn+vUyZa/EM4WAxeLR6SypJXw==} @@ -6066,8 +6056,13 @@ packages: resolution: {integrity: sha512-r4ESw/IlusD17lgQi1O20Fa3qNnsckR126TdUuBgAu7GBYSIPvdNyONd3Zrxh0xCwA4+6w/TDArBPsMvhur+KQ==} engines: {node: '>= 0.10'} + crypto-es@3.1.3: + resolution: {integrity: sha512-NtOYHzTz98pZFeC2Tytv15mijxrdo+7cgUD3LmYPkJQ8DWauCo1ObOOBJFHzE3DnzPTn27UzcfPy/7qUTrFH7g==} + engines: {node: '>=18.0.0'} + crypto-js@4.2.0: resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==} + deprecated: Active development of CryptoJS has been discontinued. This library is no longer maintained. crypto-random-string@2.0.0: resolution: {integrity: sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==} @@ -9388,11 +9383,6 @@ packages: platform@1.3.6: resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} - plausible-tracker@0.3.9: - resolution: {integrity: sha512-hMhneYm3GCPyQon88SZrVJx+LlqhM1kZFQbuAgXPoh/Az2YvO1B6bitT9qlhpiTdJlsT5lsr3gPmzoVjb5CDXA==} - engines: {node: '>=10'} - deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. - playwright-core@1.62.0: resolution: {integrity: sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==} engines: {node: '>=20'} @@ -10339,10 +10329,6 @@ packages: sver@1.8.4: resolution: {integrity: sha512-71o1zfzyawLfIWBOmw8brleKyvnbn73oVHNCsu51uPMz/HWiKkkXsI31JjHW5zqXEqnPYkIiHd8ZmL7FCimLEA==} - svg2png-wasm@1.4.1: - resolution: {integrity: sha512-ZFy1NtwZVAsslaTQoI+/QqX2sg0vjmgJ/jGAuLZZvYcRlndI54hLPiwLC9JzXlFBerfxN5JiS7kpEUG0mrXS3Q==} - deprecated: svg2png-wasm is no longer supported. Please use the resvg-js package instead. - svgo@3.3.3: resolution: {integrity: sha512-+wn7I4p7YgJhHs38k2TNjy1vCfPIfLIJWR5MnCStsN8WuuTcBnRKcMHQLMM2ijxGZmDoZwNv8ipl5aTTen62ng==} engines: {node: '>=14.0.0'} @@ -14215,6 +14201,8 @@ snapshots: '@pkgjs/parseargs@0.11.0': optional: true + '@plausible-analytics/tracker@0.4.6': {} + '@playwright/test@1.62.0': dependencies: playwright: 1.62.0 @@ -14266,6 +14254,8 @@ snapshots: '@codemirror/state': 6.7.0 '@codemirror/view': 6.43.5 + '@resvg/resvg-wasm@2.6.2': {} + '@rolldown/binding-android-arm64@1.1.4': optional: true @@ -14808,10 +14798,6 @@ snapshots: dependencies: '@types/node': 24.13.3 - '@types/bcryptjs@3.0.0': - dependencies: - bcryptjs: 3.0.3 - '@types/big.js@7.0.0': {} '@types/chai@5.2.3': @@ -14823,8 +14809,6 @@ snapshots: dependencies: '@types/tern': 0.23.9 - '@types/crypto-js@4.2.2': {} - '@types/d3-array@3.2.2': {} '@types/d3-axis@3.0.6': @@ -15109,10 +15093,6 @@ snapshots: '@types/utf8@3.0.3': {} - '@types/uuid@11.0.0': - dependencies: - uuid: 14.0.1 - '@types/validator@13.15.10': {} '@types/web-bluetooth@0.0.20': {} @@ -16660,6 +16640,8 @@ snapshots: randombytes: 2.1.0 randomfill: 1.0.4 + crypto-es@3.1.3: {} + crypto-js@4.2.0: {} crypto-random-string@2.0.0: {} @@ -20321,8 +20303,6 @@ snapshots: platform@1.3.6: {} - plausible-tracker@0.3.9: {} - playwright-core@1.62.0: {} playwright@1.62.0: @@ -21493,8 +21473,6 @@ snapshots: optionalDependencies: semver: 6.3.1 - svg2png-wasm@1.4.1: {} - svgo@3.3.3: dependencies: commander: 7.2.0 diff --git a/public/svg2png_wasm_bg.wasm b/public/svg2png_wasm_bg.wasm deleted file mode 100644 index 1bef3f1f..00000000 Binary files a/public/svg2png_wasm_bg.wasm and /dev/null differ diff --git a/renovate.json b/renovate.json index 17361f31..5b396143 100644 --- a/renovate.json +++ b/renovate.json @@ -73,17 +73,12 @@ "matchPackageNames": ["@vueuse/core", "@vueuse/head", "@vueuse/router"], "matchUpdateTypes": ["major", "minor", "patch"] }, - { - "groupName": "uuid with types", - "matchPackageNames": ["uuid", "@types/uuid"], - "matchUpdateTypes": ["major", "minor", "patch"] - }, { "groupName": "Type packages with their dependencies", "matchDepTypes": ["devDependencies"], "groupSlug": "types", "automerge": true, - "matchPackageNames": ["/^@types//", "!@types/uuid"] + "matchPackageNames": ["/^@types//"] } ] } diff --git a/src/modules/tracker/tracker.services.test.ts b/src/modules/tracker/tracker.services.test.ts new file mode 100644 index 00000000..fbca8d14 --- /dev/null +++ b/src/modules/tracker/tracker.services.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { PlausibleInstance } from './tracker.types'; +import { createTrackerService, useTracker } from './tracker.services'; + +function createPlausibleStub(): PlausibleInstance { + return { + trackEvent: vi.fn<(eventName: string) => void>(), + enableAutoPageviews: vi.fn<() => void>(), + }; +} + +describe('tracker service', () => { + describe('createTrackerService', () => { + it('forwards the event name to the tracker', () => { + const plausible = createPlausibleStub(); + + createTrackerService({ plausible }).trackEvent({ eventName: 'tool-opened' }); + + expect(plausible.trackEvent).toHaveBeenCalledWith('tool-opened'); + }); + }); + + describe('useTracker', () => { + it('throws when no tracker has been provided', () => { + expect(() => useTracker()).toThrow(new TypeError('Plausible must be instantiated')); + }); + }); +}); diff --git a/src/modules/tracker/tracker.services.ts b/src/modules/tracker/tracker.services.ts index e102f38c..f37cd8b4 100644 --- a/src/modules/tracker/tracker.services.ts +++ b/src/modules/tracker/tracker.services.ts @@ -1,10 +1,10 @@ import * as _ from 'es-toolkit/compat'; -import type Plausible from 'plausible-tracker'; import { inject } from 'vue'; +import type { PlausibleInstance } from './tracker.types'; export { createTrackerService, useTracker }; -function createTrackerService({ plausible }: { plausible: ReturnType }) { +function createTrackerService({ plausible }: { plausible: PlausibleInstance }) { return { trackEvent({ eventName }: { eventName: string }) { plausible.trackEvent(eventName); @@ -13,7 +13,7 @@ function createTrackerService({ plausible }: { plausible: ReturnType | undefined = inject('plausible'); + const plausible: PlausibleInstance | undefined = inject('plausible'); if (_.isNil(plausible)) { throw new TypeError('Plausible must be instantiated'); diff --git a/src/modules/tracker/tracker.types.ts b/src/modules/tracker/tracker.types.ts index edf79208..4eb9fee8 100644 --- a/src/modules/tracker/tracker.types.ts +++ b/src/modules/tracker/tracker.types.ts @@ -1,3 +1,12 @@ import type { createTrackerService } from './tracker.services'; export type TrackerService = ReturnType; + +/** + * The slice of the analytics tracker the app depends on. Keeping our own shape here means the tools + * and the tracker service are not tied to the tracking library currently in use. + */ +export interface PlausibleInstance { + trackEvent: (eventName: string) => void + enableAutoPageviews: () => void +} diff --git a/src/plugins/plausible.plugin.test.ts b/src/plugins/plausible.plugin.test.ts new file mode 100644 index 00000000..1895af39 --- /dev/null +++ b/src/plugins/plausible.plugin.test.ts @@ -0,0 +1,131 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { PlausibleConfig, PlausibleEventOptions } from '@plausible-analytics/tracker'; + +vi.mock('@plausible-analytics/tracker', () => ({ + init: vi.fn<(config: PlausibleConfig) => void>(), + track: vi.fn<(eventName: string, options: PlausibleEventOptions) => void>(), +})); + +const enabledConfig = { + isTrackerEnabled: true, + domain: 'it-tools.tech', + apiHost: 'https://plausible.example.com', + trackLocalhost: false, +}; + +// The plugin remembers whether the tracker has been initialized, so every test starts from a fresh +// copy of the module. +async function loadPlugin() { + vi.resetModules(); + + const { init, track } = await import('@plausible-analytics/tracker'); + const { createPlausibleInstance } = await import('./plausible.plugin'); + + return { createPlausibleInstance, init: vi.mocked(init), track: vi.mocked(track) }; +} + +describe('plausible plugin', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('when the tracker is disabled', () => { + it('does not initialize the tracker', async () => { + const { createPlausibleInstance, init } = await loadPlugin(); + + createPlausibleInstance({ config: { ...enabledConfig, isTrackerEnabled: false } }); + + expect(init).not.toHaveBeenCalled(); + }); + + it('returns an instance whose methods do nothing', async () => { + const { createPlausibleInstance, track } = await loadPlugin(); + + const plausible = createPlausibleInstance({ config: { ...enabledConfig, isTrackerEnabled: false } }); + plausible.enableAutoPageviews(); + plausible.trackEvent('some-event'); + + expect(track).not.toHaveBeenCalled(); + }); + }); + + describe('when no domain is configured', () => { + it('does not initialize the tracker, as it would throw', async () => { + const { createPlausibleInstance, init, track } = await loadPlugin(); + + createPlausibleInstance({ config: { ...enabledConfig, domain: '' } }).trackEvent('some-event'); + + expect(init).not.toHaveBeenCalled(); + expect(track).not.toHaveBeenCalled(); + }); + }); + + describe('when the tracker is enabled', () => { + it('initializes the tracker with the configured domain and endpoint', async () => { + const { createPlausibleInstance, init } = await loadPlugin(); + + createPlausibleInstance({ config: enabledConfig }); + + expect(init).toHaveBeenCalledWith({ + domain: 'it-tools.tech', + endpoint: 'https://plausible.example.com/api/event', + captureOnLocalhost: false, + }); + }); + + it('keeps posting to a same origin endpoint when no api host is configured', async () => { + const { createPlausibleInstance, init } = await loadPlugin(); + + createPlausibleInstance({ config: { ...enabledConfig, apiHost: '' } }); + + expect(init).toHaveBeenCalledWith(expect.objectContaining({ endpoint: '/api/event' })); + }); + + it('does not double the slash when the api host ends with one', async () => { + const { createPlausibleInstance, init } = await loadPlugin(); + + createPlausibleInstance({ config: { ...enabledConfig, apiHost: 'https://plausible.example.com/' } }); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ endpoint: 'https://plausible.example.com/api/event' }), + ); + }); + + it('forwards the localhost tracking setting', async () => { + const { createPlausibleInstance, init } = await loadPlugin(); + + createPlausibleInstance({ config: { ...enabledConfig, trackLocalhost: true } }); + + expect(init).toHaveBeenCalledWith(expect.objectContaining({ captureOnLocalhost: true })); + }); + + it('tracks events through the tracker', async () => { + const { createPlausibleInstance, track } = await loadPlugin(); + + createPlausibleInstance({ config: enabledConfig }).trackEvent('some-event'); + + expect(track).toHaveBeenCalledWith('some-event', {}); + }); + + it('does not enable pageviews twice, as init already captures them', async () => { + const { createPlausibleInstance, track } = await loadPlugin(); + + createPlausibleInstance({ config: enabledConfig }).enableAutoPageviews(); + + expect(track).not.toHaveBeenCalled(); + }); + + it('initializes the tracker only once, as a second init would throw', async () => { + const { createPlausibleInstance, init, track } = await loadPlugin(); + + createPlausibleInstance({ config: enabledConfig }); + const second = createPlausibleInstance({ config: enabledConfig }); + + expect(init).toHaveBeenCalledTimes(1); + + // the already running tracker stays usable from the second instance + second.trackEvent('some-event'); + expect(track).toHaveBeenCalledWith('some-event', {}); + }); + }); +}); diff --git a/src/plugins/plausible.plugin.ts b/src/plugins/plausible.plugin.ts index a32cdd47..760fe88e 100644 --- a/src/plugins/plausible.plugin.ts +++ b/src/plugins/plausible.plugin.ts @@ -1,17 +1,20 @@ import { noop } from 'es-toolkit/compat'; -import Plausible from 'plausible-tracker'; +import { init, track } from '@plausible-analytics/tracker'; import type { App } from 'vue'; +import type { PlausibleInstance } from '@/modules/tracker/tracker.types'; import { config } from '@/config'; -function createFakePlausibleInstance(): Pick, 'trackEvent' | 'enableAutoPageviews'> { +function createFakePlausibleInstance(): PlausibleInstance { return { trackEvent: noop, - enableAutoPageviews: () => noop, + enableAutoPageviews: noop, }; } -function createPlausibleInstance({ +let isTrackerInitialized = false; + +export function createPlausibleInstance({ config, }: { config: { @@ -20,12 +23,33 @@ function createPlausibleInstance({ apiHost: string trackLocalhost: boolean } -}) { - if (config.isTrackerEnabled) { - return Plausible(config); +}): PlausibleInstance { + // `init` throws when no domain is configured. Without a domain the events would be attributed to + // nothing anyway, so stay with the no-op instance instead. + if (!config.isTrackerEnabled || !config.domain) { + return createFakePlausibleInstance(); } - return createFakePlausibleInstance(); + // `init` also throws when called twice, which would take the whole app down as soon as the plugin + // is installed on a second app instance (tests, hot reload). The tracker is already running at + // that point, so reuse it rather than initializing it again. + if (!isTrackerInitialized) { + init({ + domain: config.domain, + // the previous tracker took an api host and appended the path itself; keep the very same + // endpoint, including the relative one used when no api host is configured + endpoint: `${config.apiHost.replace(/\/$/, '')}/api/event`, + captureOnLocalhost: config.trackLocalhost, + }); + + isTrackerInitialized = true; + } + + return { + trackEvent: eventName => track(eventName, {}), + // `init` already captures pageviews, `autoCapturePageviews` being enabled by default + enableAutoPageviews: noop, + }; } export const plausible = { diff --git a/src/tools/crc-calculator/crc-calculator.service.test.ts b/src/tools/crc-calculator/crc-calculator.service.test.ts new file mode 100644 index 00000000..7b73c6ac --- /dev/null +++ b/src/tools/crc-calculator/crc-calculator.service.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'vitest'; +import { algoNames, getCRCs } from './crc-calculator.service'; +import { formatHexWithEncoding } from '../hash-text/hash-text.service'; + +describe('crc-calculator', () => { + describe('algoNames', () => { + it('exposes the algorithms in the order the ui renders them', () => { + expect(algoNames).toEqual([ + 'crc1', + 'crc8', + 'crc81wire', + 'crc8dvbs2', + 'crc16', + 'crc16ccitt', + 'crc16modbus', + 'crc16kermit', + 'crc16xmodem', + 'crc24', + 'crc32', + 'crc32mpeg', + 'crcjam', + ]); + }); + }); + + describe('getCRCs', () => { + it('computes every checksum of an empty string', () => { + expect(getCRCs('')).toEqual({ + crc1: '0', + crc8: '0', + crc81wire: '0', + crc8dvbs2: '0', + crc16: '0', + crc16ccitt: 'ffff', + crc16modbus: 'ffff', + crc16kermit: '0', + crc16xmodem: '0', + crc24: 'b704ce', + crc32: '0', + crc32mpeg: 'ffffffff', + crcjam: 'ffffffff', + }); + }); + + it('computes every checksum of a string', () => { + expect(getCRCs('Hello, World!')).toEqual({ + crc1: '69', + crc8: '87', + crc81wire: '9c', + crc8dvbs2: '50', + crc16: 'fa4d', + crc16ccitt: '67da', + crc16modbus: '114e', + crc16kermit: '543e', + crc16xmodem: '4fd6', + crc24: 'df8bce', + crc32: 'ec4ac3d0', + crc32mpeg: '19270120', + crcjam: '13b53c2f', + }); + }); + + it('matches the reference "123456789" check values', () => { + expect(getCRCs('123456789')).toEqual({ + crc1: 'dd', + crc8: 'f4', + crc81wire: 'a1', + crc8dvbs2: 'bc', + crc16: 'bb3d', + crc16ccitt: '29b1', + crc16modbus: '4b37', + crc16kermit: '2189', + crc16xmodem: '31c3', + crc24: '21cf02', + crc32: 'cbf43926', + crc32mpeg: '376e6e7', + crcjam: '340bc6d9', + }); + }); + + it('computes every checksum of binary content', () => { + expect(getCRCs(new Uint8Array([0, 1, 2, 254, 255]))).toEqual({ + crc1: '0', + crc8: 'f1', + crc81wire: 'b0', + crc8dvbs2: '1c', + crc16: '1ca0', + crc16ccitt: '27e6', + crc16modbus: '1c84', + crc16kermit: '4063', + crc16xmodem: '36ea', + crc24: '705e51', + crc32: 'da2767a8', + crc32mpeg: 'b59ddd84', + crcjam: '25d89857', + }); + }); + }); + + describe('checksum rendering', () => { + it('re-encodes every checksum of "Hello, World!" as the ui does', () => { + const hashes = getCRCs('Hello, World!'); + + expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Hex'))).toEqual([ + '69', + '87', + '9c', + '50', + 'fa4d', + '67da', + '114e', + '543e', + '4fd6', + 'df8bce', + 'ec4ac3d0', + '19270120', + '13b53c2f', + ]); + expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Base64'))).toEqual([ + 'aQ==', + 'hw==', + 'nA==', + 'UA==', + '+k0=', + 'Z9o=', + 'EU4=', + 'VD4=', + 'T9Y=', + '34vO', + '7ErD0A==', + 'GScBIA==', + 'E7U8Lw==', + ]); + }); + + it('keeps the historical rendering of odd length checksums', () => { + const hashes = getCRCs(''); + + expect(formatHexWithEncoding(hashes.crc1, 'Hex')).toEqual('00'); + expect(formatHexWithEncoding(hashes.crc1, 'Base64')).toEqual('A==='); + expect(formatHexWithEncoding(hashes.crc1, 'Base64url')).toEqual('A'); + expect(formatHexWithEncoding(hashes.crc1, 'Bin')).toEqual('00000000'); + }); + }); +}); diff --git a/src/tools/crc-calculator/crc-calculator.service.ts b/src/tools/crc-calculator/crc-calculator.service.ts new file mode 100644 index 00000000..059ca56d --- /dev/null +++ b/src/tools/crc-calculator/crc-calculator.service.ts @@ -0,0 +1,40 @@ +import crc from 'crc'; + +export const defaultCRCValues = { + crc1: '', + crc8: '', + crc81wire: '', + crc8dvbs2: '', + crc16: '', + crc16ccitt: '', + crc16modbus: '', + crc16kermit: '', + crc16xmodem: '', + crc24: '', + crc32: '', + crc32mpeg: '', + crcjam: '', +}; + +export type AlgoNames = keyof typeof defaultCRCValues; + +export const algoNames = Object.keys(defaultCRCValues) as AlgoNames[]; + +export function getCRCs(rawContent: Uint8Array | string) { + const content = rawContent as Buffer | string; + return { + crc1: crc.crc1(content).toString(16), + crc8: crc.crc8(content).toString(16), + crc81wire: crc.crc81wire(content).toString(16), + crc8dvbs2: crc.crc8dvbs2(content).toString(16), + crc16: crc.crc16(content).toString(16), + crc16ccitt: crc.crc16ccitt(content).toString(16), + crc16modbus: crc.crc16modbus(content).toString(16), + crc16kermit: crc.crc16kermit(content).toString(16), + crc16xmodem: crc.crc16xmodem(content).toString(16), + crc24: crc.crc24(content).toString(16), + crc32: crc.crc32(content).toString(16), + crc32mpeg: crc.crc32mpeg2(content).toString(16), + crcjam: crc.crcjam(content).toString(16), + }; +} diff --git a/src/tools/crc-calculator/crc-calculator.vue b/src/tools/crc-calculator/crc-calculator.vue index 78d4398f..04a41199 100644 --- a/src/tools/crc-calculator/crc-calculator.vue +++ b/src/tools/crc-calculator/crc-calculator.vue @@ -1,11 +1,10 @@ diff --git a/src/tools/hmac-generator/index.ts b/src/tools/hmac-generator/index.ts index 97706e80..ab79b19d 100644 --- a/src/tools/hmac-generator/index.ts +++ b/src/tools/hmac-generator/index.ts @@ -8,6 +8,6 @@ export const tool = defineTool({ keywords: ['hmac', 'generator', 'MD5', 'SHA1', 'SHA256', 'SHA224', 'SHA512', 'SHA384', 'SHA3', 'RIPEMD160'], component: () => import('./hmac-generator.vue'), icon: defineAsyncComponent(() => import('@vicons/material/es/ShortTextRound')), - npmPackages: ['crypto-js'], + npmPackages: ['crypto-es'], category: 'Crypto', }); diff --git a/src/tools/html-wysiwyg-editor/index.ts b/src/tools/html-wysiwyg-editor/index.ts index 13b78d0a..694c16f7 100644 --- a/src/tools/html-wysiwyg-editor/index.ts +++ b/src/tools/html-wysiwyg-editor/index.ts @@ -8,6 +8,6 @@ export const tool = defineTool({ keywords: ['html', 'wysiwyg', 'editor', 'p', 'ul', 'ol', 'converter', 'live'], component: () => import('./html-wysiwyg-editor.vue'), icon: defineAsyncComponent(() => import('@vicons/tabler/es/Edit')), - npmPackages: ['monaco', 'prettier'], + npmPackages: ['@tiptap/vue-3', 'htmlfy'], category: 'Web', }); diff --git a/src/tools/image-converter/image-converter.service.test.ts b/src/tools/image-converter/image-converter.service.test.ts new file mode 100644 index 00000000..b315ed1d --- /dev/null +++ b/src/tools/image-converter/image-converter.service.test.ts @@ -0,0 +1,80 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +// the repo aliases `node:fs` to an empty stub, so the binary is inlined by vite instead of read from disk +import wasmDataUrl from '@resvg/resvg-wasm/index_bg.wasm?url&inline'; +import { convertSvgToPng, initializeSvgRenderer } from './image-converter.service'; + +const svg = ''; + +function readPngSize(png: Uint8Array) { + const view = new DataView(png.buffer, png.byteOffset, png.byteLength); + + // width and height are the first two fields of the IHDR chunk, which always comes first + return { width: view.getUint32(16), height: view.getUint32(20) }; +} + +function isPng(bytes: Uint8Array) { + return [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A].every((byte, index) => bytes[index] === byte); +} + +describe('image-converter', () => { + const loadWasm = async () => new Uint8Array(await (await fetch(wasmDataUrl)).arrayBuffer()); + let firstAttemptError: unknown; + + beforeAll(async () => { + // a failed download must not be memoized: this first attempt fails, and the next one still has + // to initialize the renderer for the rest of the suite + await initializeSvgRenderer(() => Promise.reject(new Error('network is down'))).catch((error) => { + firstAttemptError = error; + }); + + await initializeSvgRenderer(loadWasm); + }); + + describe('convertSvgToPng', () => { + it('rasterizes an svg to a png', async () => { + const png = await convertSvgToPng({ svg, scale: 1 }); + + expect(isPng(png)).toBe(true); + expect(readPngSize(png)).toEqual({ width: 100, height: 50 }); + }); + + it('scales the output', async () => { + expect(readPngSize(await convertSvgToPng({ svg, scale: 2 }))).toEqual({ width: 200, height: 100 }); + expect(readPngSize(await convertSvgToPng({ svg, scale: 4 }))).toEqual({ width: 400, height: 200 }); + expect(readPngSize(await convertSvgToPng({ svg, scale: 0.5 }))).toEqual({ width: 50, height: 25 }); + }); + + it.each<[string, string]>([ + ['the default family', 'it-tools'], + ['an explicit roboto family', 'it-tools'], + ])('draws text using %s', async (_, text) => { + const canvas = (content: string) => + `${content}`; + + const blank = await convertSvgToPng({ svg: canvas(''), scale: 1 }); + const png = await convertSvgToPng({ svg: canvas(text), scale: 1 }); + + expect(isPng(png)).toBe(true); + expect(readPngSize(png)).toEqual({ width: 200, height: 50 }); + // something was actually drawn: svg2png-wasm used to return an empty canvas for the second case + expect(png).not.toEqual(blank); + }); + + it('rejects content that is not an svg', async () => { + await expect(convertSvgToPng({ svg: 'not an svg at all', scale: 1 })).rejects.toThrow(); + }); + }); + + describe('initializeSvgRenderer', () => { + it('surfaces a failed download without memoizing it', () => { + // the whole suite renders fine afterwards, which is what proves the retry actually happened + expect(firstAttemptError).toEqual(new Error('network is down')); + }); + + it('only initializes the wasm module once, as a second call would throw', async () => { + await expect(initializeSvgRenderer(() => { + throw new Error('should not be called again'); + })).resolves.toBeUndefined(); + }); + }); +}); diff --git a/src/tools/image-converter/image-converter.service.ts b/src/tools/image-converter/image-converter.service.ts new file mode 100644 index 00000000..3fa20cce --- /dev/null +++ b/src/tools/image-converter/image-converter.service.ts @@ -0,0 +1,56 @@ +import type { InitInput } from '@resvg/resvg-wasm'; +import { Resvg, initWasm } from '@resvg/resvg-wasm'; +import { Base64 } from 'js-base64'; +import { normal as robotoBase64 } from 'roboto-base64'; +import resvgWasmUrl from '@resvg/resvg-wasm/index_bg.wasm?url'; + +type WasmLoader = () => Promise | InitInput; + +const defaultWasmLoader: WasmLoader = () => fetch(resvgWasmUrl); + +let initialization: Promise | undefined; + +/** + * `initWasm` throws when called more than once, so the very first call wins and every later one + * awaits it. The loader is injectable so tests can feed the binary without going through the network. + */ +export function initializeSvgRenderer(loadWasm: WasmLoader = defaultWasmLoader) { + initialization ??= Promise.resolve(loadWasm()) + .then(input => initWasm(input)) + .catch((error) => { + // a failed download must not be memoized, otherwise a single network hiccup would leave the + // tool broken until the page is reloaded + initialization = undefined; + throw error; + }); + + return initialization; +} + +export async function convertSvgToPng({ svg, scale }: { svg: string; scale: number }) { + await initializeSvgRenderer(); + + const renderer = new Resvg(svg, { + fitTo: { mode: 'zoom', value: scale }, + // Roboto is the only font embedded in the app, so it also has to be the fallback family: + // resvg defaults to a family that is not loaded, which would drop every text node. + font: { + fontBuffers: [Base64.toUint8Array(robotoBase64)], + defaultFontFamily: 'Roboto', + }, + }); + + try { + const rendered = renderer.render(); + + try { + return rendered.asPng(); + } + finally { + rendered.free(); + } + } + finally { + renderer.free(); + } +} diff --git a/src/tools/image-converter/image-converter.vue b/src/tools/image-converter/image-converter.vue index 67c6cb6b..4e3f8aa2 100644 --- a/src/tools/image-converter/image-converter.vue +++ b/src/tools/image-converter/image-converter.vue @@ -14,8 +14,7 @@ import { encodeTiff, } from 'image-in-browser'; import { arrayBufferToWebP } from 'webp-converter-browser'; -import { createSvg2png, initialize } from 'svg2png-wasm'; -import { normal as robotoBase64 } from 'roboto-base64'; +import { convertSvgToPng } from './image-converter.service'; import { useDownloadFileFromBase64 } from '@/composable/downloadBase64'; import { useQueryParamOrStorage } from '@/composable/queryParams'; @@ -88,8 +87,6 @@ const outputFormatHasQuality = computed(() => { return outputFormat.value === 'jpg'; }); -const svgWasmLoaded = ref(false); - async function onFilesUploaded(uploadedFiles: File[]) { for (const file of uploadedFiles) { await onFileUploaded(file); @@ -109,17 +106,10 @@ async function onFileUploaded(uploadedFile: File) { base64OutputFile.value = `data:image/webp;base64,${Base64.fromUint8Array(new Uint8Array(await encodedImage.arrayBuffer()))}`; } else { if (uploadedFile.type === 'image/svg+xml') { - if (!svgWasmLoaded.value) { - await initialize(fetch('/svg2png_wasm_bg.wasm')); - svgWasmLoaded.value = true; - } - const svg2png = createSvg2png({ - fonts: [Base64.toUint8Array(robotoBase64)], - }); - fileBuffer = (await svg2png(await readAsText(uploadedFile), { + fileBuffer = (await convertSvgToPng({ + svg: await readAsText(uploadedFile), scale: svgScale.value, })) as Uint8Array; - svg2png.dispose(); } const decodedImage = decodeImage({ data: fileBuffer, diff --git a/src/tools/ipv6-ula-generator/index.ts b/src/tools/ipv6-ula-generator/index.ts index 07a2ef75..4053dc5b 100644 --- a/src/tools/ipv6-ula-generator/index.ts +++ b/src/tools/ipv6-ula-generator/index.ts @@ -9,6 +9,6 @@ export const tool = defineTool({ component: () => import('./ipv6-ula-generator.vue'), icon: defineAsyncComponent(() => import('@vicons/tabler/es/BuildingFactory')), createdAt: new Date('2023-04-09'), - npmPackages: ['crypto-js'], + npmPackages: ['crypto-es'], category: 'Network', }); diff --git a/src/tools/ipv6-ula-generator/ipv6-ula-generator.service.test.ts b/src/tools/ipv6-ula-generator/ipv6-ula-generator.service.test.ts new file mode 100644 index 00000000..a2e2ed12 --- /dev/null +++ b/src/tools/ipv6-ula-generator/ipv6-ula-generator.service.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; +import { generateUlaBlocks, generateUlaPrefix } from './ipv6-ula-generator.service'; + +describe('ipv6-ula-generator', () => { + describe('generateUlaPrefix', () => { + it.each<[number, string, string]>([ + [0, '20:37:06:12:34:56', 'fda8:5b32:b6f9'], + [1700000000000, '20:37:06:12:34:56', 'fdb7:29eb:4229'], + [1234567890, 'aa:bb:cc:dd:ee:ff', 'fd0c:d4a8:7e9a'], + ])('derives the prefix from timestamp %s and mac %s', (timestamp, macAddress, expected) => { + expect(generateUlaPrefix({ macAddress, timestamp })).toEqual(expected); + }); + + it('always starts with the fd00::/8 locally assigned prefix', () => { + for (let timestamp = 0; timestamp < 50; timestamp++) { + expect(generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp })).toMatch( + /^fd[0-9a-f]{2}:[0-9a-f]{4}:[0-9a-f]{4}$/, + ); + } + }); + + it('is stable for a given timestamp and mac address', () => { + const args = { macAddress: '20:37:06:12:34:56', timestamp: 42 }; + + expect(generateUlaPrefix(args)).toEqual(generateUlaPrefix(args)); + }); + + it('changes when the timestamp or the mac address changes', () => { + expect(generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp: 1 })).not.toEqual( + generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp: 2 }), + ); + expect(generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp: 1 })).not.toEqual( + generateUlaPrefix({ macAddress: '20:37:06:12:34:57', timestamp: 1 }), + ); + }); + }); + + describe('generateUlaBlocks', () => { + it('builds the ula and its routable blocks', () => { + expect(generateUlaBlocks({ macAddress: '20:37:06:12:34:56', timestamp: 1700000000000 })).toEqual({ + ula: 'fdb7:29eb:4229::/48', + firstRoutableBlock: 'fdb7:29eb:4229:0::/64', + lastRoutableBlock: 'fdb7:29eb:4229:ffff::/64', + }); + }); + }); +}); diff --git a/src/tools/ipv6-ula-generator/ipv6-ula-generator.service.ts b/src/tools/ipv6-ula-generator/ipv6-ula-generator.service.ts new file mode 100644 index 00000000..48e89c25 --- /dev/null +++ b/src/tools/ipv6-ula-generator/ipv6-ula-generator.service.ts @@ -0,0 +1,20 @@ +import { SHA1 } from 'crypto-es'; + +// RFC 4193 §3.2.2: sha1 of the current timestamp concatenated with the mac address, keeping the lowest 40 bits. +export function generateUlaPrefix({ macAddress, timestamp }: { macAddress: string; timestamp: number }) { + const hex40bit = SHA1(timestamp + macAddress) + .toString() + .substring(30); + + return `fd${hex40bit.substring(0, 2)}:${hex40bit.substring(2, 6)}:${hex40bit.substring(6)}`; +} + +export function generateUlaBlocks({ macAddress, timestamp }: { macAddress: string; timestamp: number }) { + const ula = generateUlaPrefix({ macAddress, timestamp }); + + return { + ula: `${ula}::/48`, + firstRoutableBlock: `${ula}:0::/64`, + lastRoutableBlock: `${ula}:ffff::/64`, + }; +} diff --git a/src/tools/ipv6-ula-generator/ipv6-ula-generator.vue b/src/tools/ipv6-ula-generator/ipv6-ula-generator.vue index d9628c6a..ea4f9289 100644 --- a/src/tools/ipv6-ula-generator/ipv6-ula-generator.vue +++ b/src/tools/ipv6-ula-generator/ipv6-ula-generator.vue @@ -1,6 +1,6 @@