Skip to content

Commit 314748a

Browse files
committed
fix(insights): provide key via plugin only
1 parent 6f0e926 commit 314748a

File tree

8 files changed

+47
-49
lines changed

8 files changed

+47
-49
lines changed

packages/docs/src/root.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ export default component$(() => {
5959
<ServiceWorkerRegister />
6060

6161
<script dangerouslySetInnerHTML={`(${collectSymbols})()`} />
62-
<Insights publicApiKey={import.meta.env.PUBLIC_QWIK_INSIGHTS_KEY} />
62+
<Insights />
6363
</head>
6464
<body
6565
class={{

packages/docs/src/routes/api/qwik-insights/api.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
}
1313
],
1414
"kind": "Variable",
15-
"content": "> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n> \n\n\n\n```typescript\nInsights: import(\"@qwik.dev/core\").Component<{\n publicApiKey?: string;\n postUrl?: string;\n}>\n```",
15+
"content": "> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.\n> \n\n\n\n```typescript\nInsights: import(\"@qwik.dev/core\").Component<unknown>\n```",
1616
"editUrl": "https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/insights/insights.ts",
1717
"mdFile": "core.insights.md"
1818
},

packages/docs/src/routes/api/qwik-insights/index.mdx

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,7 @@ title: \@qwik.dev/qwik/insights API Reference
99
> This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.
1010
1111
```typescript
12-
Insights: import("@qwik.dev/core").Component<{
13-
publicApiKey?: string;
14-
postUrl?: string;
15-
}>;
12+
Insights: import("@qwik.dev/core").Component<unknown>;
1613
```
1714

1815
[Edit this section](https://github.com/QwikDev/qwik/tree/main/packages/qwik/src/insights/insights.ts)

packages/docs/vite.config.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { transformerMetaHighlight, transformerMetaWordHighlight } from '@shikijs
1414
import { transformerColorizedBrackets } from '@shikijs/colorized-brackets';
1515
import type { ShikiTransformer } from '@shikijs/types';
1616

17-
const PUBLIC_QWIK_INSIGHTS_KEY = loadEnv('', '.', 'PUBLIC').PUBLIC_QWIK_INSIGHTS_KEY;
17+
const insightsApiKey = loadEnv('', '.', 'PUBLIC').PUBLIC_QWIK_INSIGHTS_KEY;
1818
const docsDir = new URL(import.meta.url).pathname;
1919

2020
// https://github.com/vitejs/vite/issues/15012#issuecomment-1825035992
@@ -184,7 +184,7 @@ export default defineConfig(async () => {
184184
sourceResolver(docsDir),
185185
qwikReact(),
186186
Inspect(),
187-
qwikInsights({ publicApiKey: PUBLIC_QWIK_INSIGHTS_KEY }),
187+
qwikInsights({ publicApiKey: insightsApiKey }),
188188
tailwindcss(),
189189
],
190190
build: {

packages/insights/src/root.tsx

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { component$ } from '@qwik.dev/core';
22
import { Insights } from '@qwik.dev/core/insights';
3-
import { QwikRouterProvider, RouterOutlet, ServiceWorkerRegister, z } from '@qwik.dev/router';
3+
import { QwikRouterProvider, RouterOutlet, z } from '@qwik.dev/router';
44
import { RouterHead } from './components/router-head/router-head';
55
import './global.css';
66

@@ -41,14 +41,10 @@ export default component$(() => {
4141
<meta charset="utf-8" />
4242
<link rel="manifest" href="/manifest.json" />
4343
<RouterHead />
44-
<Insights
45-
publicApiKey={import.meta.env.PUBLIC_QWIK_INSIGHTS_KEY}
46-
postUrl="/api/v1/${publicApiKey}/post/"
47-
/>
44+
<Insights />
4845
</head>
4946
<body lang="en">
5047
<RouterOutlet />
51-
<ServiceWorkerRegister />
5248
</body>
5349
</QwikRouterProvider>
5450
);

packages/qwik/src/insights/insights.ts

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { component$, sync$ } from '@qwik.dev/core';
1+
import { component$, isDev, sync$ } from '@qwik.dev/core';
22
import { jsx } from '@qwik.dev/core/jsx-runtime';
33

44
/** @public */
@@ -80,6 +80,12 @@ interface QSymbolDetail {
8080
symbol: string;
8181
}
8282

83+
// Injected by the vite plugin
84+
// eslint-disable-next-line no-var
85+
declare var __QI_KEY__: string;
86+
// eslint-disable-next-line no-var
87+
declare var __QI_URL__: string;
88+
8389
// We use a self-invoking function to minify the code, renaming long globals and attributes
8490
// the qwik optimizer only minifies somewhat, so put all var declarations in the same line
8591
/** @internal */
@@ -173,41 +179,27 @@ export const insightsPing = sync$(() =>
173179
})(window as any, document, location, navigator, performance, Math.round, JSON.stringify)
174180
);
175181

176-
// We don't add window. to save some bytes
177-
declare var __QI_KEY__: string;
178-
declare var __QI_URL__: string;
179-
180182
/**
181183
* @beta
182184
* @experimental
183185
*/
184-
export const Insights = component$<{
185-
/** The public Insights API key of your application, when using the Qwik Insights service */
186-
publicApiKey?: string;
187-
188-
/**
189-
* The URL to post the data to your own Insights service. This disables the use of the Qwik
190-
* Insights service.
191-
*
192-
* Be sure to configure the insights plugin to use your own service.
193-
*/
194-
postUrl?: string;
195-
}>(({ publicApiKey, postUrl }) => {
186+
export const Insights = component$(() => {
196187
if (!__EXPERIMENTAL__.insights) {
197188
throw new Error(
198189
'Insights is experimental and must be enabled with `experimental: ["insights"]` in the `qwikVite` plugin.'
199190
);
200191
}
201-
if (!(publicApiKey || postUrl)) {
192+
const key = (globalThis as any).__QI_KEY__;
193+
const url = (globalThis as any).__QI_URL__;
194+
if (!key || !url) {
195+
if (!isDev) {
196+
console.warn('<Insights />: no config from qwikInsights plugin, skipping...');
197+
}
202198
return null;
203199
}
204-
205-
// TODO configure these via the plugin instead
206-
return (
207-
// the script will set the variables before the qinit event
208-
/* @__PURE__ */ jsx('script', {
209-
'document:onQInit$': insightsPing,
210-
dangerouslySetInnerHTML: `__QI_KEY__=${JSON.stringify(publicApiKey)};__QI_URL__=${JSON.stringify(postUrl || `https://insights.qwik.dev/api/v1/${publicApiKey}/post/`)}`,
211-
})
212-
);
200+
return /* @__PURE__ */ jsx('script', {
201+
'document:onQInit$': insightsPing,
202+
// We must pass the vite injected variables via window because sync$ code doesn't get replaced by the vite plugin
203+
dangerouslySetInnerHTML: `__QI_KEY__=${JSON.stringify(key)};__QI_URL__=${JSON.stringify(url)}`,
204+
});
213205
});

packages/qwik/src/insights/qwik.insights.api.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ import { Component } from '@qwik.dev/core';
88
import { SyncQRL } from '@qwik.dev/core';
99

1010
// @beta (undocumented)
11-
export const Insights: Component< {
12-
publicApiKey?: string;
13-
postUrl?: string;
14-
}>;
11+
export const Insights: Component<unknown>;
1512

1613
// @public (undocumented)
1714
export interface InsightsError {

packages/qwik/src/insights/vite/insights-plugin.ts

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,20 @@ export async function qwikInsights(qwikInsightsOpts: {
2929
outDir?: string;
3030
}): Promise<PluginOption> {
3131
const { publicApiKey, baseUrl = 'https://insights.qwik.dev', outDir = '' } = qwikInsightsOpts;
32+
33+
if (!publicApiKey) {
34+
console.warn('qwikInsights: publicApiKey is required, skipping...');
35+
return;
36+
}
3237
let isProd = false;
3338
let jsonDir: string;
3439
let jsonFile: string;
3540
let data: InsightManifest | null = null;
3641
let qwikVitePlugin: QwikVitePlugin | null = null;
3742

43+
const apiUrl = `${baseUrl}/api/v1/${publicApiKey}`;
44+
const postUrl = `${apiUrl}/post/`;
45+
3846
async function loadQwikInsights(): Promise<InsightManifest | null> {
3947
if (data) {
4048
return data;
@@ -49,11 +57,19 @@ export async function qwikInsights(qwikInsightsOpts: {
4957
const vitePlugin: PluginOption = {
5058
name: 'vite-plugin-qwik-insights',
5159
enforce: 'pre',
60+
// Only activate in production builds
5261
apply: 'build',
5362
async config(viteConfig) {
5463
jsonDir = resolve(viteConfig.root || '.', outDir);
5564
jsonFile = join(jsonDir, 'q-insights.json');
5665
isProd = viteConfig.mode !== 'ssr';
66+
67+
return {
68+
define: {
69+
'globalThis.__QI_KEY__': JSON.stringify(publicApiKey),
70+
'globalThis.__QI_URL__': JSON.stringify(postUrl),
71+
},
72+
};
5773
},
5874
configResolved: {
5975
// we want to register the bundle graph adder last so we overwrite existing routes
@@ -69,15 +85,15 @@ export async function qwikInsights(qwikInsightsOpts: {
6985
if (isProd) {
7086
try {
7187
const qManifest: InsightManifest = { manual: {}, prefetch: [] };
72-
const response = await fetch(`${baseUrl}/api/v1/${publicApiKey}/bundles/strategy/`);
88+
const response = await fetch(`${apiUrl}/bundles/strategy/`);
7389
const strategy = await response.json();
7490
Object.assign(qManifest, strategy);
7591
data = qManifest;
7692
mkdirSync(jsonDir, { recursive: true });
7793
log('Fetched latest Qwik Insight data into: ' + jsonFile);
7894
await writeFile(jsonFile, JSON.stringify(qManifest));
7995
} catch (e) {
80-
logWarn('Failed to fetch manifest from Insights DB', e);
96+
logWarn(`Failed to fetch manifest from Insights DB at ${apiUrl}/bundles/strategy/`, e);
8197
await loadQwikInsights();
8298
}
8399
} else {
@@ -119,12 +135,12 @@ export async function qwikInsights(qwikInsightsOpts: {
119135
const qManifest = await readFile(path, 'utf-8');
120136

121137
try {
122-
await fetch(`${baseUrl}/api/v1/${publicApiKey}/post/manifest`, {
138+
await fetch(`${postUrl}manifest`, {
123139
method: 'post',
124140
body: qManifest,
125141
});
126142
} catch (e) {
127-
logWarn('Failed to post manifest to Insights DB', e);
143+
logWarn(`Failed to post manifest to Insights DB at ${postUrl}manifest`, e);
128144
}
129145
}
130146
},

0 commit comments

Comments
 (0)