nuxtjs-vk-pixel 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) chemist-repo <larcev.dima@yandex.ru>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,260 @@
1
+ # nuxtjs-vk-pixel
2
+
3
+ Nuxt модуль для интеграции VK Pixel (Top.Mail.Ru счетчика) в Nuxt 3 приложения.
4
+
5
+ ## 📦 Установка
6
+
7
+ ```bash
8
+ npm install nuxtjs-vk-pixel
9
+ ```
10
+
11
+ ## ⚙️ Настройка
12
+
13
+ Добавьте модуль в `nuxt.config.ts`:
14
+
15
+ ```typescript
16
+ export default defineNuxtConfig({
17
+ modules: [
18
+ 'nuxtjs-vk-pixel',
19
+ ],
20
+ vkPixel: {
21
+ id: 'your-pixel-id', // Обязательный параметр
22
+ scriptSrc: 'https://top-fwz1.mail.ru/js/code.js', // Опционально
23
+ noscriptSrc: 'https://top-fwz1.mail.ru/counter', // Опционально
24
+ debug: false, // Опционально, по умолчанию true в dev режиме
25
+ },
26
+ })
27
+ ```
28
+
29
+ ### Параметры конфигурации
30
+
31
+ | Параметр | Тип | Обязательный | По умолчанию | Описание |
32
+ |----------|-----|--------------|--------------|----------|
33
+ | `id` | `string` | ✅ | `'xxx'` | ID вашего VK Pixel счетчика |
34
+ | `scriptSrc` | `string` | ❌ | `'https://top-fwz1.mail.ru/js/code.js'` | URL скрипта счетчика |
35
+ | `noscriptSrc` | `string` | ❌ | `'https://top-fwz1.mail.ru/counter'` | URL для noscript версии |
36
+ | `debug` | `boolean` | ❌ | `NODE_ENV !== 'production'` | Включить режим отладки |
37
+
38
+ ## 🚀 Использование
39
+
40
+ ### Composable
41
+
42
+ Используйте `useVkPixel()` для доступа к API счетчика:
43
+
44
+ ```vue
45
+ <script setup lang="ts">
46
+ const vkPixel = useVkPixel()
47
+
48
+ // Отправка события просмотра страницы
49
+ vkPixel.pageView({
50
+ url: window.location.href,
51
+ referrer: document.referrer
52
+ })
53
+
54
+ // Отправка произвольного события
55
+ vkPixel.push({
56
+ type: 'reachGoal',
57
+ goal: 'purchase',
58
+ params: {
59
+ order_id: '12345',
60
+ amount: 1000
61
+ }
62
+ })
63
+ </script>
64
+ ```
65
+
66
+ ### Прямой доступ через NuxtApp
67
+
68
+ Вы также можете получить доступ к счетчику через `$vkPixel`:
69
+
70
+ ```typescript
71
+ const { $vkPixel } = useNuxtApp()
72
+ $vkPixel.push({ type: 'pageView' })
73
+ ```
74
+
75
+ ## 📚 API
76
+
77
+ ### `useVkPixel()`
78
+
79
+ Возвращает объект с методами для работы с VK Pixel.
80
+
81
+ #### `pageView(payload: IPageViewPayload)`
82
+
83
+ Отправляет событие просмотра страницы.
84
+
85
+ **Параметры:**
86
+ - `url: string` - URL страницы
87
+ - `referrer: string` - URL реферера
88
+
89
+ **Пример:**
90
+ ```typescript
91
+ vkPixel.pageView({
92
+ url: 'https://example.com/page',
93
+ referrer: 'https://google.com'
94
+ })
95
+ ```
96
+
97
+ #### `push(payload: IPushPayload)`
98
+
99
+ Отправляет произвольное событие в счетчик.
100
+
101
+ **Параметры:**
102
+ - `type: 'reachGoal' | 'pageView' | 'onready'` - Тип события
103
+ - `goal?: string` - Идентификатор цели (для `reachGoal`)
104
+ - `start?: number` - Время начала (timestamp)
105
+ - `url?: string` - URL страницы
106
+ - `category?: string` - Категория события
107
+ - `action?: string` - Действие
108
+ - `label?: string` - Метка события
109
+ - `params?: Record<string, unknown>` - Дополнительные параметры
110
+ - `callback?: (...args: any[]) => void` - Функция обратного вызова
111
+
112
+ **Примеры:**
113
+
114
+ ```typescript
115
+ // Отслеживание достижения цели
116
+ vkPixel.push({
117
+ type: 'reachGoal',
118
+ goal: 'purchase',
119
+ params: {
120
+ order_id: '12345',
121
+ amount: 1000,
122
+ currency: 'RUB'
123
+ }
124
+ })
125
+
126
+ // Отслеживание просмотра страницы
127
+ vkPixel.push({
128
+ type: 'pageView',
129
+ url: window.location.href,
130
+ start: Date.now()
131
+ })
132
+
133
+ // Отслеживание готовности страницы
134
+ vkPixel.push({
135
+ type: 'onready',
136
+ callback: () => {
137
+ console.log('Pixel загружен')
138
+ }
139
+ })
140
+ ```
141
+
142
+ ## 🔧 Типы
143
+
144
+ Модуль экспортирует следующие TypeScript типы:
145
+
146
+ ```typescript
147
+ interface IPageViewPayload {
148
+ id: string
149
+ url: string
150
+ referrer: string
151
+ }
152
+
153
+ interface IPushPayload {
154
+ id: string
155
+ type: 'reachGoal' | 'pageView' | 'onready'
156
+ goal?: string
157
+ start?: number
158
+ url?: string
159
+ category?: string
160
+ action?: string
161
+ label?: string
162
+ params?: Record<string, unknown>
163
+ callback?: (...args: any[]) => void
164
+ }
165
+
166
+ interface IVkPixelTmr {
167
+ pageView: (payload: IPageViewPayload) => void
168
+ push: (payload: IPushPayload) => void
169
+ }
170
+ ```
171
+
172
+ ## 📝 Примеры использования
173
+
174
+ ### Отслеживание покупки
175
+
176
+ ```vue
177
+ <script setup lang="ts">
178
+ const vkPixel = useVkPixel()
179
+
180
+ const handlePurchase = async (orderId: string, amount: number) => {
181
+ // Ваша логика покупки
182
+ await processPurchase(orderId, amount)
183
+
184
+ // Отправка события в VK Pixel
185
+ vkPixel.push({
186
+ type: 'reachGoal',
187
+ goal: 'purchase',
188
+ params: {
189
+ order_id: orderId,
190
+ amount: amount,
191
+ currency: 'RUB'
192
+ }
193
+ })
194
+ }
195
+ </script>
196
+ ```
197
+
198
+ ### Отслеживание регистрации
199
+
200
+ ```vue
201
+ <script setup lang="ts">
202
+ const vkPixel = useVkPixel()
203
+
204
+ const handleRegistration = async (email: string) => {
205
+ await registerUser(email)
206
+
207
+ vkPixel.push({
208
+ type: 'reachGoal',
209
+ goal: 'registration',
210
+ params: {
211
+ email: email
212
+ }
213
+ })
214
+ }
215
+ </script>
216
+ ```
217
+
218
+ ### Отслеживание добавления в корзину
219
+
220
+ ```vue
221
+ <script setup lang="ts">
222
+ const vkPixel = useVkPixel()
223
+
224
+ const addToCart = (productId: string, price: number) => {
225
+ // Ваша логика добавления в корзину
226
+ cart.add(productId)
227
+
228
+ vkPixel.push({
229
+ type: 'reachGoal',
230
+ goal: 'add_to_cart',
231
+ params: {
232
+ product_id: productId,
233
+ price: price
234
+ }
235
+ })
236
+ }
237
+ </script>
238
+ ```
239
+
240
+ ## 🔍 Особенности
241
+
242
+ - ✅ Автоматическая загрузка скрипта счетчика
243
+ - ✅ Поддержка noscript версии для пользователей без JavaScript
244
+ - ✅ TypeScript поддержка из коробки
245
+ - ✅ Интеграция с `@nuxt/scripts` для оптимизированной загрузки
246
+ - ✅ Автоматическая инициализация при готовности Nuxt приложения
247
+ - ✅ Доступ через composable и через `$vkPixel`
248
+
249
+ ## 📄 Лицензия
250
+
251
+ MIT
252
+
253
+ ## 👤 Автор
254
+
255
+ Dmitrii Lartsev - [GitHub](https://github.com/chemist-repo)
256
+
257
+ ## 🔗 Ссылки
258
+
259
+ - [Репозиторий](https://github.com/chemist-repo/nuxtjs-vk-pixel)
260
+ - [VK Pixel документация](https://top-fwz1.mail.ru/js/code.js)
@@ -0,0 +1,12 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+
3
+ interface ModuleOptions {
4
+ id: string;
5
+ scriptSrc: string;
6
+ noscriptSrc: string;
7
+ debug: boolean;
8
+ }
9
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
10
+
11
+ export { _default as default };
12
+ export type { ModuleOptions };
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "vk-pixel",
3
+ "configKey": "vkPixel",
4
+ "version": "0.0.3",
5
+ "builder": {
6
+ "@nuxt/module-builder": "1.0.2",
7
+ "unbuild": "3.6.1"
8
+ }
9
+ }
@@ -0,0 +1,36 @@
1
+ import { defineNuxtModule, createResolver, addPlugin, addImports } from '@nuxt/kit';
2
+
3
+ const defaultOptions = {
4
+ id: "xxx",
5
+ debug: import.meta.env.NODE_ENV !== "production",
6
+ scriptSrc: "https://top-fwz1.mail.ru/js/code.js",
7
+ noscriptSrc: "https://top-fwz1.mail.ru/counter"
8
+ };
9
+ const module$1 = defineNuxtModule({
10
+ meta: {
11
+ name: "vk-pixel",
12
+ configKey: "vkPixel"
13
+ },
14
+ moduleDependencies() {
15
+ return {
16
+ "@nuxt/scripts": {}
17
+ };
18
+ },
19
+ defaults: defaultOptions,
20
+ setup(options, nuxt) {
21
+ nuxt.options.runtimeConfig.public.vkPixel = {
22
+ ...nuxt.options.runtimeConfig.public.vkPixel ?? {},
23
+ ...options,
24
+ ...defaultOptions
25
+ };
26
+ const resolver = createResolver(import.meta.url);
27
+ addPlugin(resolver.resolve("./runtime/plugin"));
28
+ addImports({
29
+ name: "useVkPixel",
30
+ as: "useVkPixel",
31
+ from: resolver.resolve("./runtime/composable")
32
+ });
33
+ }
34
+ });
35
+
36
+ export { module$1 as default };
@@ -0,0 +1 @@
1
+ export declare function useVkPixel(): unknown;
@@ -0,0 +1,5 @@
1
+ import { useNuxtApp } from "#app";
2
+ export function useVkPixel() {
3
+ const { $vkPixel } = useNuxtApp();
4
+ return $vkPixel;
5
+ }
@@ -0,0 +1,12 @@
1
+ import type { IVkPixelTmr } from './types'
2
+
3
+ declare global {
4
+ interface Window {
5
+ _tmr?: IVkPixelTmr
6
+ }
7
+ interface NuxtApp {
8
+ $vkPixel: IVkPixelTmr
9
+ }
10
+ }
11
+
12
+ export {}
@@ -0,0 +1,7 @@
1
+ import type { IVkPixelTmr } from './types.js';
2
+ declare const _default: import("#app").Plugin<{
3
+ vkPixel: IVkPixelTmr;
4
+ }> & import("#app").ObjectPlugin<{
5
+ vkPixel: IVkPixelTmr;
6
+ }>;
7
+ export default _default;
@@ -0,0 +1,52 @@
1
+ import { defineNuxtPlugin, useHead } from "#app";
2
+ import { useScript } from "#nuxt-scripts/composables/useScript";
3
+ export default defineNuxtPlugin({
4
+ parallel: true,
5
+ setup(nuxtApp) {
6
+ const { id, scriptSrc, noscriptSrc } = nuxtApp.$config.public.vkPixel ?? {};
7
+ const { proxy } = useScript(
8
+ scriptSrc,
9
+ {
10
+ trigger: "onNuxtReady",
11
+ use() {
12
+ (window._tmr || (window._tmr = [])).push({
13
+ id,
14
+ type: "pageView",
15
+ url: window.location.href,
16
+ start: (/* @__PURE__ */ new Date()).getTime()
17
+ });
18
+ return window._tmr;
19
+ }
20
+ }
21
+ );
22
+ useHead({
23
+ noscript: [
24
+ {
25
+ tagPosition: "bodyOpen",
26
+ textContent() {
27
+ return `<div><img src="${noscriptSrc}?id=${id};js=na" style="position:absolute;left:-9999px;" alt="Top.Mail.Ru" /></div>`;
28
+ }
29
+ }
30
+ ]
31
+ });
32
+ const vkPixel = {
33
+ push(payload) {
34
+ proxy.push({
35
+ ...payload,
36
+ id
37
+ });
38
+ },
39
+ pageView(payload) {
40
+ proxy.pageView({
41
+ ...payload,
42
+ id
43
+ });
44
+ }
45
+ };
46
+ return {
47
+ provide: {
48
+ vkPixel
49
+ }
50
+ };
51
+ }
52
+ });
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "../../../.nuxt/tsconfig.server.json",
3
+ }
@@ -0,0 +1,25 @@
1
+ export interface IBasePayload {
2
+ id: string;
3
+ }
4
+ export interface IPushPayload extends IBasePayload {
5
+ type: 'reachGoal' | 'pageView' | 'onready';
6
+ goal?: string;
7
+ start?: number;
8
+ url?: string;
9
+ category?: string;
10
+ action?: string;
11
+ label?: string;
12
+ params?: Record<string, unknown>;
13
+ callback?: (...args: any[]) => void;
14
+ }
15
+ export interface IPageViewPayload extends IBasePayload {
16
+ url: string;
17
+ referrer: string;
18
+ }
19
+ export interface IVkPixelTmr {
20
+ pageView: (payload: IPageViewPayload) => void;
21
+ push: (payload: IPushPayload) => void;
22
+ }
23
+ export interface IVkPixel {
24
+ tmr?: IVkPixelTmr;
25
+ }
File without changes
@@ -0,0 +1,3 @@
1
+ export { default } from './module.mjs'
2
+
3
+ export { type ModuleOptions } from './module.mjs'
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "nuxtjs-vk-pixel",
3
+ "type": "module",
4
+ "version": "0.0.3",
5
+ "description": "NuxtJS VK Pixel module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/chemist-repo/nuxtjs-vk-pixel.git"
9
+ },
10
+ "author": {
11
+ "name": "Dmitrii Lartsev <https://github.com/chemist-repo/>",
12
+ "url": "https://github.com/chemist-repo"
13
+ },
14
+ "homepage": "chemist-repo/nuxtjs-vk-pixel",
15
+ "license": "MIT",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/types.d.mts",
19
+ "import": "./dist/module.mjs"
20
+ }
21
+ },
22
+ "main": "./dist/module.mjs",
23
+ "typesVersions": {
24
+ "*": {
25
+ ".": [
26
+ "./dist/types.d.mts"
27
+ ]
28
+ }
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "prepack": "nuxt-module-build build",
38
+ "dev": "npm run dev:prepare && nuxi dev playground",
39
+ "dev:build": "nuxi build playground",
40
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
41
+ "release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags",
42
+ "lint": "eslint .",
43
+ "test": "vitest run",
44
+ "test:watch": "vitest watch",
45
+ "test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
46
+ "hook:install": "lefthook install"
47
+ },
48
+ "dependencies": {
49
+ "@nuxt/kit": "^4.2.2"
50
+ },
51
+ "peerDependencies": {
52
+ "@nuxt/scripts": "^0.13.2"
53
+ },
54
+ "devDependencies": {
55
+ "@commitlint/cli": "^20.3.1",
56
+ "@commitlint/config-conventional": "^20.3.1",
57
+ "@commitlint/types": "^20.3.1",
58
+ "@nuxt/devtools": "^3.1.1",
59
+ "@nuxt/eslint-config": "^1.12.1",
60
+ "@nuxt/module-builder": "^1.0.2",
61
+ "@nuxt/schema": "^4.2.2",
62
+ "@nuxt/test-utils": "^3.22.0",
63
+ "@types/node": "latest",
64
+ "changelogen": "^0.6.2",
65
+ "eslint": "^9.39.2",
66
+ "lefthook": "^2.0.13",
67
+ "nuxt": "^4.2.2",
68
+ "typescript": "~5.9.3",
69
+ "vitest": "^3.2.4",
70
+ "vue-tsc": "^3.2.2"
71
+ }
72
+ }