Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .Jules/engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,9 @@
- **Allocation Reduction:** Introduced `getLastUserMessage(messages)` in `src/utils/chat-logic.ts` using a reverse `for` loop to eliminate `[...messages].reverse().find(...)` array clone and in-place reversal allocations on every chat API request in Cloudflare Workers edge runtimes.
- **Loop Optimization:** Refactored initial total content character count calculation in `pruneMessages` to use a direct indexed `for` loop instead of `reduce()`, eliminating callback closure allocations on context window evaluation.
- **Verification:** Added Vitest unit tests in `src/utils/chat-logic.test.ts` covering empty message history, history with trailing assistant messages, and multiple user messages.

## 2025-06-11 - Single-Pass Edge SSR Transforms & Allocation Reductions in Whats-New Glance

- **Allocation Reduction:** Refactored `collectItems`, `thisWeek`, and `ranked` in `src/utils/whats-new-glance.ts` to process release notes with direct loops and early exit bounds, eliminating intermediate `.map()`, `.filter().map().slice()`, and `.flatMap()` array allocations during edge SSR requests.
- **Single-Pass Transforms & Hoisted Regexes:** Refactored `sentenceCount`, `metricTokens`, and `groundedReleaseSummary` in `src/utils/release-summary.ts` and `github-releases.ts` to use single-pass loops and hoisted static regular expressions, avoiding regex re-compilation and intermediate array chaining.
- **Verification:** Verified via full Vitest test suite (`npm run test`), ESLint, Prettier, `npm run astro check`, and production build (`npm run build`).
1 change: 0 additions & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export default defineConfig({
}),
],
vite: {
// @ts-expect-error Codecov's Vite plugin is typed against a different Vite instance than Astro's bundled one.
plugins: [codecovPlugin],
resolve: isRender
? {
Expand Down
26 changes: 24 additions & 2 deletions src/__tests__/content.config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,18 @@ describe('content.config', () => {
});

it('validates flags fixture against schema', async () => {
const { schema } = collections.flags;
const rawSchema = collections.flags.schema;
const schema =
typeof rawSchema === 'function'
? rawSchema({
image: () =>
z.any() as unknown as ReturnType<
Parameters<Extract<typeof rawSchema, (...args: unknown[]) => unknown>>[0]['image']
>,
})
: rawSchema;
expect(schema).toBeDefined();
if (!schema) return;
const result = schema.safeParse(flagsFixture);
expect(result.success).toBe(true);

Expand All @@ -40,7 +51,18 @@ describe('content.config', () => {
});

it('validates work schema with sample data', () => {
const { schema } = collections.work;
const rawSchema = collections.work.schema;
const schema =
typeof rawSchema === 'function'
? rawSchema({
image: () =>
z.any() as unknown as ReturnType<
Parameters<Extract<typeof rawSchema, (...args: unknown[]) => unknown>>[0]['image']
>,
})
: rawSchema;
expect(schema).toBeDefined();
if (!schema) return;
const sampleWork = {
title: 'Sample Work',
description: 'A sample description',
Expand Down
2 changes: 1 addition & 1 deletion src/components/Footer.astro
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ const currentYear = new Date().getFullYear();
return;
}
openedByHover = false;
setOpen(panel.hidden);
setOpen(Boolean(panel.hidden));
});

trigger.addEventListener('focus', () => {
Expand Down
10 changes: 10 additions & 0 deletions src/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,13 @@ declare module '*.txt?raw' {
const content: string;
export default content;
}

interface Element {
append(...nodes: (string | Node)[]): void;
prepend(...nodes: (string | Node)[]): void;
}

interface ParentNode {
append(...nodes: (string | Node)[]): void;
prepend(...nodes: (string | Node)[]): void;
}
9 changes: 6 additions & 3 deletions src/utils/github-releases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,9 @@ export function formatReleaseDate(dateString: string | null): string {
return date.toISOString().split('T')[0];
}

const COMMIT_HASH_MATCH = /^([a-f0-9]{7,40})\s+(.*)/i;
const BULLET_PREFIX = /^[-*+]\s+/;

/**
* Parses a single changelog line into a ReleaseItem, extracting hashes and messages.
* @param {string} line - A single line from the release body.
Expand All @@ -187,7 +190,7 @@ export function formatReleaseDate(dateString: string | null): string {
export function parseReleaseItem(line: string): ReleaseItem {
const cleaned = line.trim();
// Matches a 7 to 40-character hex hash at the beginning
const hashMatch = cleaned.match(/^([a-f0-9]{7,40})\s+(.*)/i);
const hashMatch = cleaned.match(COMMIT_HASH_MATCH);

if (hashMatch) {
const hash = hashMatch[1];
Expand Down Expand Up @@ -223,9 +226,9 @@ export function splitReleaseBody(body: string): ReleaseItem[] {

for (const line of lines) {
const trimmed = line.trim();
if (!/^[-*+]\s+/.test(trimmed)) continue;
if (!BULLET_PREFIX.test(trimmed)) continue;

const rawMessage = trimmed.replace(/^[-*+]\s+/, '');
const rawMessage = trimmed.replace(BULLET_PREFIX, '');
const item = parseReleaseItem(rawMessage);
if (isPublicChangelogItem(item)) {
items.push(item);
Expand Down
3 changes: 1 addition & 2 deletions src/utils/hire-analytics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ describe('hire-analytics', () => {
});

it('does not throw when dataLayer is missing', () => {
// @ts-expect-error -- dataLayer is optional on Window
delete window.dataLayer;
delete (window as { dataLayer?: unknown }).dataLayer;
expect(() => trackHireEvent('linkedin_click', 'contact_cta')).not.toThrow();
});

Expand Down
70 changes: 51 additions & 19 deletions src/utils/release-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,29 +36,48 @@ Notes:
${notes}`;
}

const SENTENCE_SPLIT = /(?<=[.!?])\s+/;
const METRIC_TOKENS_REGEX = /\b\d+(?:\.\d+)?x\b|\b\d+%\b|\broi\b|\bmillion\b|\bbillion\b/gi;
const PAREN_HASH_REGEX = /\(#\d+\)/g;
const PLAIN_HASH_REGEX = /#\d+/g;
const ISSUE_NUMBER_DIGITS_REGEX = /\bissue number\s+\d+\b/gi;
const CONVENTIONAL_PREFIX_GLOBAL =
/\b(?:feat|fix|chore|docs|refactor|test|style|perf|build|ci):\s*/gi;
const PUNCTUATION_SPACE_REGEX = /\s+([.,;:])/g;
const LEADING_PUNCTUATION_REGEX = /^[\s:;\-]+/;
const MULTI_SPACE_REGEX = /\s{2,}/g;

function sentenceCount(text: string): number {
return text
.split(/(?<=[.!?])\s+/)
.map((part) => part.trim())
.filter((part) => part.length > 0).length;
const parts = text.split(SENTENCE_SPLIT);
let count = 0;
for (let i = 0; i < parts.length; i++) {
if (parts[i].trim().length > 0) {
count++;
}
}
return count;
}

function metricTokens(text: string): string[] {
const matches = text.match(/\b\d+(?:\.\d+)?x\b|\b\d+%\b|\broi\b|\bmillion\b|\bbillion\b/gi);
return matches ? matches.map((token) => token.toLowerCase()) : [];
const matches = text.match(METRIC_TOKENS_REGEX);
if (!matches) return [];
for (let i = 0; i < matches.length; i++) {
matches[i] = matches[i].toLowerCase();
}
return matches;
}

export function stripExecBanned(text: string): string {
return text
.replace(BANNED_NAME, '')
.replace(SHA_ALL, '')
.replace(/\(#\d+\)/g, '')
.replace(/#\d+/g, '')
.replace(/\bissue number\s+\d+\b/gi, '')
.replace(/\b(?:feat|fix|chore|docs|refactor|test|style|perf|build|ci):\s*/gi, '')
.replace(/\s+([.,;:])/g, '$1')
.replace(/^[\s:;\-]+/, '')
.replace(/\s{2,}/g, ' ')
.replace(PAREN_HASH_REGEX, '')
.replace(PLAIN_HASH_REGEX, '')
.replace(ISSUE_NUMBER_DIGITS_REGEX, '')
.replace(CONVENTIONAL_PREFIX_GLOBAL, '')
.replace(PUNCTUATION_SPACE_REGEX, '$1')
.replace(LEADING_PUNCTUATION_REGEX, '')
.replace(MULTI_SPACE_REGEX, ' ')
.trim();
}

Expand Down Expand Up @@ -107,12 +126,25 @@ export function parseModelText(result: unknown): string {
}

export function groundedReleaseSummary(tag: string, body: string, title = tag): string {
const items = splitReleaseBody(body)
.map((item) => stripExecBanned(item.message.trim()))
.filter(isVisitorFacingBullet);
const listed = (items.length > 0 ? items : body.trim() ? [stripExecBanned(body.trim())] : [])
.filter(isVisitorFacingBullet)
.slice(0, 3);
const rawItems = splitReleaseBody(body);
const items: string[] = [];
for (let i = 0; i < rawItems.length; i++) {
const stripped = stripExecBanned(rawItems[i].message.trim());
if (isVisitorFacingBullet(stripped)) {
items.push(stripped);
}
}

const candidateSource =
items.length > 0 ? items : body.trim() ? [stripExecBanned(body.trim())] : [];
const listed: string[] = [];
for (let i = 0; i < candidateSource.length; i++) {
if (isVisitorFacingBullet(candidateSource[i])) {
listed.push(candidateSource[i]);
if (listed.length === 3) break;
}
}

const source = `${tag}\n${title}\n${body}`;
if (listed.length > 0) {
const text = `The latest release is ${title}. Visitors can now ${listed.join('; ')}. More is in the changelog on this page.`;
Expand Down
90 changes: 57 additions & 33 deletions src/utils/whats-new-glance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,29 +78,36 @@ function collectItems(releases: SiteRelease[], nowMs: number): GlanceItem[] {
const items: GlanceItem[] = [];
const seen = new Set<string>();

for (const release of releases.map(toVisitorRelease)) {
for (const rawRelease of releases) {
const release = toVisitorRelease(rawRelease);
const publishedMs = release.publishedAt ? Date.parse(release.publishedAt) : Number.NaN;
if (Number.isNaN(publishedMs)) continue;
const age = nowMs - publishedMs;
if (age < 0 || age > MONTH_MS) continue;

const bullets = splitReleaseBody(release.body);
const lines =
bullets.length > 0
? bullets.map((item) => ({
raw: item.message,
title: toVisitorChangelogTitle(item.message),
}))
: release.body.trim()
? [{ raw: release.body, title: toVisitorChangelogTitle(release.body) }]
: [];

for (const line of lines) {
if (!isKeptVisitorLine(line.raw, line.title)) continue;
const key = line.title.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
items.push({ publishedMs, title: line.title });
if (bullets.length > 0) {
for (const item of bullets) {
const raw = item.message;
const title = toVisitorChangelogTitle(raw);
if (!isKeptVisitorLine(raw, title)) continue;
const key = title.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
items.push({ publishedMs, title });
}
} else {
const trimmedBody = release.body.trim();
if (trimmedBody) {
const title = toVisitorChangelogTitle(trimmedBody);
if (isKeptVisitorLine(trimmedBody, title)) {
const key = title.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
items.push({ publishedMs, title });
}
}
}
}
}

Expand All @@ -114,11 +121,18 @@ export function buildWhatsNewGlance(
): WhatsNewGlance {
const nowMs = now.getTime();
const items = collectItems(releases, nowMs);
const thisWeek = items
.filter((item) => nowMs - item.publishedMs <= WEEK_MS)
.map((item) => item.title)
.slice(0, 3);
const thisWeekKeys = new Set(thisWeek.map((title) => title.toLowerCase()));
const thisWeek: string[] = [];
for (const item of items) {
if (nowMs - item.publishedMs <= WEEK_MS) {
thisWeek.push(item.title);
if (thisWeek.length === 3) break;
}
}

const thisWeekKeys = new Set<string>();
for (const title of thisWeek) {
thisWeekKeys.add(title.toLowerCase());
}

const buckets = new Map<string, GlanceItem[]>();
for (const item of items) {
Expand All @@ -130,21 +144,31 @@ export function buildWhatsNewGlance(
buckets.set(theme.heading, list);
}

const ranked = THEMES.flatMap((theme) => {
const ranked: { heading: string; lines: string[]; latest: number }[] = [];
for (const theme of THEMES) {
const list = buckets.get(theme.heading);
if (!list || list.length === 0) return [];
return [
{
if (list && list.length > 0) {
const lines: string[] = [];
for (const item of list) {
lines.push(item.title);
}
ranked.push({
heading: theme.heading,
lines: list.map((item) => item.title),
lines,
latest: list[0].publishedMs,
},
];
})
.sort((a, b) => b.latest - a.latest)
.slice(0, 4);
});
}
}

const groups: GlanceGroup[] = ranked.map(({ heading, lines }) => ({ heading, lines }));
ranked.sort((a, b) => b.latest - a.latest);
if (ranked.length > 4) {
ranked.length = 4;
}

const groups: GlanceGroup[] = [];
for (const item of ranked) {
groups.push({ heading: item.heading, lines: item.lines });
}

return { thisWeek, groups };
}
Loading