From 9bc362373ce922245a1518d17296f2b3364f27fd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 00:36:59 +0000 Subject: [PATCH 1/5] fix(gzip_decompress): call short non-gzip input not gzip, not damaged gzip The streaming reader checks a header only once it has all of it, so a few bytes of anything ({, [, a cut-off H4sIAAAA) ended the stream with no member and no error, and the trailer check reported a failed CRC-32. Check the magic bytes and the 20-byte minimum first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016MBDS61t2hQgzoraTNWAvz --- src/utilities/gzip_decompress/index.test.ts | 19 +++++++++++++++++++ src/utilities/gzip_decompress/index.ts | 11 +++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/utilities/gzip_decompress/index.test.ts b/src/utilities/gzip_decompress/index.test.ts index dc45af7..d80e5e7 100644 --- a/src/utilities/gzip_decompress/index.test.ts +++ b/src/utilities/gzip_decompress/index.test.ts @@ -117,6 +117,25 @@ describe('gzip_decompress', () => { ) }) + it('calls a few bytes of non-gzip input not gzip, never damaged gzip', async () => { + // the streaming reader waits for a whole header before checking it, so these once + // reached the trailer check and were reported as a failed CRC-32 + for (const input of ['{', '[', '}', '{"a":1}', new Uint8Array([0x7b])]) { + const error = await Promise.resolve(util.apply(input as never, {})).then(() => null, (e: Error) => e.message) + expect(error).toMatch(/^not valid gzip data/) + expect(error).not.toMatch(/integrity/) + } + }) + + it('says a gzip header cut off before a whole stream is too short to be gzip', async () => { + // H4sIAAAA is Base64 for 1f 8b 08 00 00 00: the start of every CloudWatch Logs payload + await expect(util.apply('H4sIAAAA', {})).rejects.toThrow( + /^not valid gzip data .*: only 6 bytes, and the shortest gzip stream is 20$/ + ) + const full = await gz('short') + await expect(util.apply(full.slice(0, 19), {})).rejects.toThrow(/only 19 bytes/) + }) + it('throws on truncated gzip data', async () => { const full = await gz('a reasonably long sentence to compress and then truncate') await expect(util.apply(full.slice(0, full.length - 6), {})).rejects.toThrow() diff --git a/src/utilities/gzip_decompress/index.ts b/src/utilities/gzip_decompress/index.ts index 16ee0b8..9dcccc4 100644 --- a/src/utilities/gzip_decompress/index.ts +++ b/src/utilities/gzip_decompress/index.ts @@ -42,6 +42,9 @@ const readU32LE = (b: Uint8Array, i: number) => const CORRUPT = 'gzip integrity check failed: the CRC-32/size trailer does not match the decompressed data (corrupt or truncated input)' +/** The shortest gzip member: a 10-byte header, an empty deflate block (2 bytes) and the 8-byte trailer. */ +const MIN_GZIP_LENGTH = 20 + /** * Decompress a gzip stream and check it. * @@ -52,6 +55,14 @@ const CORRUPT = * against its slice of the output. */ async function gunzipVerified(bytes: Uint8Array): Promise { + // The streaming reader checks a header only once it has all of it, so a few bytes of + // anything (`{`, `[`, a cut-off `H4sIAAAA`) end the stream with no member and no error, + // and the trailer check below would report them as damaged gzip. They are not gzip. + if (!hasGzipMagic(bytes)) throw new Error('invalid gzip data') + if (bytes.length < MIN_GZIP_LENGTH) { + throw new Error(`only ${bytes.length} bytes, and the shortest gzip stream is ${MIN_GZIP_LENGTH}`) + } + const { Gunzip } = await getFflate() const chunks: Uint8Array[] = [] From 3125a25519a5e736d1aac32e364c5f057890b6f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 00:36:59 +0000 Subject: [PATCH 2/5] feat(recipes): laneEach/laneBranch helpers; close two checker loopholes - define.ts: laneEach() and laneBranch() build nested containers with regex condition flags normalized, like the top-level builders. - check.ts: count utility steps through containers, so one utility wrapped in run-on-each is no longer a recipe on its own. - check.ts: refuse a primaryQuery that contains a utility guide title's head term ("bulk slug generator" vs /util/slug/). On the 13 shipped and 13 planned queries it catches only that one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016MBDS61t2hQgzoraTNWAvz --- src/recipes/check.test.ts | 53 ++++++++++++++++++++++++++++++++++++--- src/recipes/check.ts | 41 ++++++++++++++++++++---------- src/recipes/define.ts | 16 +++++++++--- 3 files changed, 91 insertions(+), 19 deletions(-) diff --git a/src/recipes/check.test.ts b/src/recipes/check.test.ts index cf8287d..0c2aea5 100644 --- a/src/recipes/check.test.ts +++ b/src/recipes/check.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it } from 'vitest' import { runPipeline } from '../core/runner' import { staticRegistry, STATIC_UTILITIES } from '../utilities/static-registry' import { MANIFEST } from '../utilities/_generated/manifest' -import { checkRecipe, checkRecipeSet, overlap, shingles, type RecipeCheckContext } from './check' -import { branch, each, laneStep, step } from './define' +import { checkRecipe, checkRecipeSet, headTerm, overlap, shingles, type RecipeCheckContext } from './check' +import { branch, each, laneBranch, laneStep, step } from './define' import type { Recipe } from './types' const byId = new Map(STATIC_UTILITIES.map(u => [u.id, u])) @@ -101,7 +101,36 @@ describe('checkRecipe', () => { { id: 'b', title: 'B', input: 'cd ', output: 'CD' }, ], }), 'upper-slugs', guide(), ctx()) - expect(problems.join('\n')).toContain('needs ≥ 2 steps besides') + expect(problems.join('\n')).toContain('needs ≥ 2 utility steps besides') + }) + + it('counts the utilities inside a container: one utility wrapped in "run on each" is still one', async () => { + const wrapped = (steps: Recipe['steps']) => checkRecipe(recipe({ + steps, + samples: [ + { id: 'a', title: 'A', input: ' ab\ncd', output: 'AB\nCD' }, + { id: 'b', title: 'B', input: 'x', output: 'X' }, + ], + }), 'upper-slugs', guide(), ctx()) + const perLine = each('per-line', { mode: 'lines' }, [laneStep('l1', 'case', { mode: 'upper' })], + 'Uppercases every line on its own, which one utility does for the whole text.') + const trimmed = step('t', 'trim_lines', { side: 'both', characters: '' }, 'Removes the spaces around every line before anything else.') + expect((await wrapped([perLine])).join('\n')).toContain('needs ≥ 2 utility steps besides') + expect((await wrapped([trimmed, perLine])).join('\n')).toContain('needs ≥ 2 utility steps besides') + }) + + it('accepts one container holding two utilities across a nested branch and a pass-through lane', async () => { + const counted = each('per-line', { mode: 'lines' }, [ + laneBranch('both', [[laneStep('n', 'text_stats', {}), laneStep('g', 'jsonpath', { path: '$.graphemes', mode: 'first', indent: 2 })], []], + { mode: 'concat', separator: ' · ' }), + ], 'Writes how many characters each line has in front of the line itself.') + expect(await checkRecipe(recipe({ + steps: [counted], + samples: [ + { id: 'a', title: 'A', input: 'ab\ncde', output: '2 · ab\n3 · cde' }, + { id: 'b', title: 'B', input: 'é', output: '1 · é' }, + ], + }), 'upper-slugs', guide(), ctx())).toEqual([]) }) it('accepts a branch as the multi-step part', async () => { @@ -260,6 +289,16 @@ describe('checkRecipeSet', () => { expect(problems.join('\n')).toContain('is the head term of /util/csv_to_sql/') }) + it("refuses a target query that contains a utility page's head term, and only its head term", () => { + const utils = [utilGuide('slug', 'Slug Generator Online — URL-Safe Slugs From Any Text'), utilGuide('case', 'Change Case Online')] + const check = (primaryQuery: string) => checkRecipeSet([{ recipe: recipe({ primaryQuery }), guide: guide() }], utils).join('\n') + expect(check('bulk slug generator')).toContain('primary query "bulk slug generator" contains "slug generator", the head term of /util/slug/') + expect(check('change case of every heading')).toContain('contains "change case", the head term of /util/case/') + // words of the subtitle, or of the head term on their own, are fine + expect(check('url-safe slugs from a list of titles')).toBe('') + expect(check('slug list from titles')).toBe('') + }) + it('refuses near-copied prose, from another recipe or a utility the recipe uses', () => { const shared = filler('s', 300) const problems = checkRecipeSet([ @@ -272,6 +311,14 @@ describe('checkRecipeSet', () => { }) }) +describe('headTerm', () => { + it('is the title before " — ", without a trailing "Online", lowercased', () => { + expect(headTerm('Slug Generator Online — URL-Safe Slugs From Any Text')).toBe('slug generator') + expect(headTerm('CSV to SQL INSERT Generator Online')).toBe('csv to sql insert generator') + expect(headTerm('Tabs to Spaces Converter Online (and Back)')).toBe('tabs to spaces converter online (and back)') + }) +}) + describe('shingles / overlap', () => { it('compares prose as 8-word runs, ignoring code, link targets and case', () => { const a = shingles('---\ntitle: t\n---\nOne two three four five six seven eight nine `code here` [x](/util/a/)') diff --git a/src/recipes/check.ts b/src/recipes/check.ts index 4198dfc..c3d4c12 100644 --- a/src/recipes/check.ts +++ b/src/recipes/check.ts @@ -5,10 +5,10 @@ * Two kinds of rule. Engine rules keep the page honest: real utilities and * params, every sample reproduces its golden output on every run, and every * step earns its place (leaving any one out changes some sample's output). - * Search rules keep it from being a thin or competing page: two real steps or - * a branch, a guide long enough to be worth a visit, a title and target query - * that no utility page already owns, and prose that is not a near-copy of - * another page's. + * Search rules keep it from being a thin or competing page: two real utility + * steps (nested ones count), a guide long enough to be worth a visit, a title + * and target query that no utility page already owns, and prose that is not a + * near-copy of another page's. */ import type { PipelineStep, Utility } from '../types/utility' import type { UtilityMeta } from '../core/registry' @@ -48,8 +48,8 @@ export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ const DATE = /^\d{4}-\d{2}-\d{2}$/ /** - * Tidying steps: useful, but no recipe on their own. A page needs two real steps besides - * these, or a container (branch, macro or "run on each") holding the work. + * Tidying steps: useful, but no recipe on their own. A page needs two real utility steps + * besides these, at the top level or inside a branch, macro or "run on each" step. */ export const HELPER_UTILITIES: ReadonlySet = new Set([ 'trim', 'trim_lines', 'remove_blank_lines', 'collapse_whitespace', 'normalize_line_endings', @@ -138,9 +138,11 @@ function checkSteps(recipe: Recipe, steps: PipelineStep[], ctx: RecipeCheckConte const runnable = problems.length === 0 if (!sameData(sanitizeSteps(steps), steps)) problems.push('steps change when sanitized (as share links and the library store them): use plain JSON params') - const real = recipe.steps.filter(s => !isUtilityStep(s) || !HELPER_UTILITIES.has(s.utilityId)) - if (!recipe.steps.some(s => !isUtilityStep(s)) && real.length < 2) { - problems.push(`needs ≥ 2 steps besides ${[...HELPER_UTILITIES].join('/')} (or a branch, macro or each step): one utility is its own page, at /util//`) + // counted through containers too: one utility wrapped in a branch or "run on each" is still one utility + let real = 0 + walkSteps(steps, s => { if (isUtilityStep(s) && !HELPER_UTILITIES.has(s.utilityId)) real++ }) + if (real < 2) { + problems.push(`needs ≥ 2 utility steps besides ${[...HELPER_UTILITIES].join('/')}, nested ones included: one utility is its own page, at /util//`) } for (const s of recipe.steps) { const n = words(s.why ?? '') @@ -242,6 +244,13 @@ export interface GuideEntry { source: string } +/** + * What a utility page ranks for: its guide title before " — ", without a trailing + * "Online" ("Slug Generator Online — URL-Safe Slugs" → "slug generator"). + */ +export const headTerm = (title: string): string => + title.split(' — ')[0].replace(/\s+online$/i, '').trim().toLowerCase() + /** A guide's prose (code spans and fenced blocks dropped) as a set of `shingleWords`-word runs. */ export function shingles(source: string, size = RECIPE_RULES.shingleWords): Set { const text = proseLines(source).join(' ').replace(/`[^`\n]*`/g, ' ').replace(/\]\([^)]*\)/g, ']') @@ -261,8 +270,9 @@ export function overlap(a: Set, b: Set): number { /** * Problems no single recipe shows: duplicate names, titles, descriptions or target - * queries; a target query some utility page already leads with; prose that is a - * near-copy of another recipe's guide or of a guide for a utility it uses. + * queries; a target query some utility page already leads with, or that contains its + * head term ("bulk slug generator"); prose that is a near-copy of another recipe's + * guide or of a guide for a utility it uses. */ export function checkRecipeSet( recipes: Array<{ recipe: Recipe; guide: string | null }>, @@ -294,8 +304,13 @@ export function checkRecipeSet( } const query = recipe.primaryQuery.trim().toLowerCase() for (const u of utilTitles) { - if (query && u.guide.title?.toLowerCase().includes(query)) { - problems.push(`${owner}: primary query ${show(query)} is the head term of /util/${u.id}/ (${show(u.guide.title!)}) — the pages would compete; target the task, not the tool`) + const title = u.guide.title + if (!query || !title) continue + const head = headTerm(title) + if (title.toLowerCase().includes(query)) { + problems.push(`${owner}: primary query ${show(query)} is the head term of /util/${u.id}/ (${show(title)}) — the pages would compete; target the task, not the tool`) + } else if (head && query.includes(head)) { + problems.push(`${owner}: primary query ${show(query)} contains ${show(head)}, the head term of /util/${u.id}/ (${show(title)}) — the pages would compete; target the task, not the tool`) } } } diff --git a/src/recipes/define.ts b/src/recipes/define.ts index 6d5f955..e0fef20 100644 --- a/src/recipes/define.ts +++ b/src/recipes/define.ts @@ -3,7 +3,7 @@ * than a wall of `{ id, utilityId, enabled, params }` objects. Every builder * returns plain step data: what the engine, share links and the library store. */ -import type { Condition, ErrorPolicy, MergeSpec, PipelineStep, SplitSpec, UtilityStep } from '../types/utility' +import type { BranchStep, Condition, EachStep, ErrorPolicy, MergeSpec, PipelineStep, SplitSpec, UtilityStep } from '../types/utility' import type { RecipeStep } from './types' export interface StepOptions { @@ -35,7 +35,12 @@ export function laneStep(id: string, utilityId: string, params: Record Date: Thu, 8 Oct 2026 00:36:59 +0000 Subject: [PATCH 3/5] feat(recipes): show nested steps on recipe pages; stop skip traces on leave - RecipeArticle renders the steps inside run-on-each, branch and macro steps recursively: utility link, label, changed params, condition, failure policy, the each split and the branch merge. The pre-rendered page is all a crawler sees, so a setting inside a lane must show there. - The skip section names the top-level step a failing nested step is in. - "1 step", not "1 steps", on the page and on the OG card. - RecipePage aborts its skip-trace runs when the page unmounts, instead of running them on while the next page waits for the executor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016MBDS61t2hQgzoraTNWAvz --- scripts/seo/build.ts | 4 +- src/app/pages/recipes/RecipeArticle.test.tsx | 87 +++++++++- src/app/pages/recipes/RecipeArticle.tsx | 166 +++++++++++++++---- src/app/pages/recipes/RecipePage.tsx | 18 +- src/app/pages/recipes/recipeHelpers.ts | 3 + 5 files changed, 231 insertions(+), 47 deletions(-) diff --git a/scripts/seo/build.ts b/scripts/seo/build.ts index 0d75ea6..7af1ad9 100644 --- a/scripts/seo/build.ts +++ b/scripts/seo/build.ts @@ -24,7 +24,7 @@ import { import { loadOgFonts, renderOgPng, runPool } from './og' import { parseGuide, renderGuideHtml, renderMarkdownDocument, type Guide } from '../../src/app/pages/guide' import { relatedUtilities } from '../../src/app/pages/related' -import { featuredRecipes, recipesUsing, relatedRecipes } from '../../src/app/pages/recipes/recipeHelpers' +import { featuredRecipes, recipesUsing, relatedRecipes, stepCountText } from '../../src/app/pages/recipes/recipeHelpers' import { traceRecipe, TRACE_ELEMENT_ID, type PipelineRunner, type RecipeTrace } from '../../src/recipes/trace' import type { Recipe, RecipeMeta } from '../../src/recipes/types' import { metaOfRecipe } from '../gen-recipes' @@ -578,7 +578,7 @@ export async function buildSeo(options: BuildSeoOptions): Promise ({ file: `${m.id}.png`, card: { name: displayName(m.name), category: m.category, description: m.description } })), ...recipeMetas.map(r => ({ file: path.join('recipes', `${r.slug}.png`), - card: { name: r.name, category: `Recipe · ${r.stepCount} steps`, description: r.chain.join(' → ') }, + card: { name: r.name, category: `Recipe · ${stepCountText(r.stepCount)}`, description: r.chain.join(' → ') }, })), { file: 'default.png', diff --git a/src/app/pages/recipes/RecipeArticle.test.tsx b/src/app/pages/recipes/RecipeArticle.test.tsx index 568467c..1ae60a9 100644 --- a/src/app/pages/recipes/RecipeArticle.test.tsx +++ b/src/app/pages/recipes/RecipeArticle.test.tsx @@ -1,10 +1,11 @@ import React from 'react' import { describe, expect, it } from 'vitest' +import { renderToStaticMarkup } from 'react-dom/server' import { render, screen } from '@testing-library/react' import { MANIFEST } from '@/utilities/_generated/manifest' -import { each, laneStep, step } from '@/recipes/define' +import { each, laneBranch, laneEach, laneStep, step } from '@/recipes/define' import type { Recipe } from '@/recipes/types' -import { RecipeArticle } from './RecipeArticle' +import { RecipeArticle, RecipeWidget } from './RecipeArticle' const metas = new Map(MANIFEST.map(m => [m.id, m])) @@ -32,10 +33,83 @@ describe('RecipeArticle', () => { } render( metas.get(id)} guideHtml="" steps={[]} skip={[]} live={null} related={[]} />) expect(screen.getAllByText('Run on each value').length).toBeGreaterThan(0) - expect(screen.getByText('on each value:')).toBeInTheDocument() + expect(screen.getByText('Each value of the JSON object goes through:')).toBeInTheDocument() expect(screen.getAllByRole('link').some(a => a.getAttribute('href') === '/util/base64_decode/')).toBe(true) }) + it('shows every nested step with its label, utility link, changed params, condition and failure policy', () => { + const nested: Recipe = { + ...recipe, + steps: [ + step('find', 'extract_preset', { type: ['jwt'], unique: true }, 'Finds every token in the pasted log, one per line.'), + each('tokens', { mode: 'lines' }, [ + laneStep('payload', 'jwt_decode', { part: 'payload' }, { onError: 'stop', label: 'read the payload' }), + laneEach('dates', { mode: 'json-values' }, [ + laneStep('date', 'timestamp_convert', { to: 'iso', timezone: 'UTC' }, { condition: { kind: 'regex', pattern: '^1[4-9]\\d{8}$' } }), + ]), + ], 'Decodes every token on its own and turns its timestamps into dates.', { onError: 'empty', includeEmpty: true }), + ], + } + const { container } = render( metas.get(id)} guideHtml="" steps={[]} skip={[]} live={null} related={[]} />) + const text = container.textContent ?? '' + expect(screen.getByText('Each line, empty ones included, goes through:')).toBeInTheDocument() + expect(screen.getByText('A line whose steps fail comes out empty.')).toBeInTheDocument() + expect(screen.getByText('If it fails, the steps after it do not run.')).toBeInTheDocument() + expect(text).toContain('read the payload (jwt decode)') + expect(screen.getByText('Each value of the JSON object goes through:')).toBeInTheDocument() + expect(screen.getByText(/Runs only when its input matches/).textContent) + .toBe('Runs only when its input matches ^1[4-9]\\d{8}$; otherwise the input passes through.') + // the nested steps' non-default params, with the labels the editor shows + const terms = screen.getAllByRole('term').map(t => t.textContent) + expect(terms).toContain(metas.get('jwt_decode')!.params.part.label) + expect(terms).toContain(metas.get('timestamp_convert')!.params.to.label) + for (const id of ['extract_preset', 'jwt_decode', 'timestamp_convert']) { + expect(screen.getAllByRole('link').some(a => a.getAttribute('href') === `/util/${id}/`)).toBe(true) + } + }) + + it("shows a branch's lanes, an empty pass-through lane and how the lanes are merged", () => { + const lanes: Recipe = { + ...recipe, + steps: [each('count', { mode: 'lines' }, [ + laneBranch('both', [[laneStep('n', 'text_stats', {}), laneStep('g', 'jsonpath', { path: '$.graphemes', mode: 'first', indent: 2 })], []], + { mode: 'concat', separator: ' · ' }), + ], 'Writes how many characters each line has in front of the line itself.')], + } + const { container } = render( metas.get(id)} guideHtml="" steps={[]} skip={[]} live={null} related={[]} />) + expect(container.textContent).toContain('Every lane gets the same input, and their outputs are joined with · :') + expect(screen.getByText('Lane 1:')).toBeInTheDocument() + expect(screen.getByText('Lane 2: its input, unchanged')).toBeInTheDocument() + expect(screen.getByText('$.graphemes')).toBeInTheDocument() + }) + + it('renders nested steps in static markup, as the pre-render does', () => { + const tracking: Recipe = { + ...recipe, + steps: [each('strip', { mode: 'lines' }, [ + laneStep('drop', 'query_params_normalize', { drop: 'utm_*,fbclid', sort: false }, { condition: { kind: 'regex', pattern: '^https?://\\S+$', flags: 'i' } }), + laneStep('upper', 'case', { mode: 'upper' }), + ], 'Cleans one link at a time and leaves every other line alone.')], + } + const html = renderToStaticMarkup( metas.get(id)} guideHtml="" steps={[]} skip={[]} live={null} related={[]} />) + expect(html).toContain('utm_*,fbclid') + expect(html).toContain('^https?://\\S+$ (ignoring case); otherwise the input passes through.') + expect(html).toContain('href="/util/query_params_normalize/"') + }) + + it('names the top-level step a failing nested step is in, when a step is left out', () => { + const nested: Recipe = { + ...recipe, + steps: [ + step('unquote', 'replace', { pattern: '"', replacement: '', regex: false }, 'Drops the quotes so every value reads as plain text.'), + each('values', { mode: 'lines' }, [laneStep('b64', 'base64_decode')], 'Decodes every line of Base64 on its own.'), + ], + } + render( metas.get(id)} guideHtml="" steps={[]} live={null} related={[]} + skip={[{ id: 'unquote', error: { stepId: 'b64', message: 'not Base64' }, unchanged: false }]} />) + expect(screen.getByText('The pipeline breaks: step 2 (Run on each line) fails with “not Base64”.')).toBeInTheDocument() + }) + it('words a condition by what it does: runs on a match, or is skipped on a match', () => { render( metas.get(id)} guideHtml="" steps={[]} skip={[]} live={null} related={[]} />) expect(screen.getByText(/Runs only when its input matches/).textContent) @@ -61,4 +135,11 @@ describe('RecipeArticle', () => { expect(screen.getByRole('heading', { name: 'What if you skip a step?' })).toBeTruthy() expect(screen.getByText('Working it out…')).toBeTruthy() }) + + it('counts the numbered steps in the widget, in the singular for one', () => { + const widget = (stepCount: number) => renderToStaticMarkup( + ) + expect(widget(1)).toContain('1 step, every one editable.') + expect(widget(4)).toContain('4 steps, every one editable.') + }) }) diff --git a/src/app/pages/recipes/RecipeArticle.tsx b/src/app/pages/recipes/RecipeArticle.tsx index d00caef..d91706a 100644 --- a/src/app/pages/recipes/RecipeArticle.tsx +++ b/src/app/pages/recipes/RecipeArticle.tsx @@ -7,13 +7,13 @@ * every handler is optional (the pre-render passes none). */ import React from 'react' -import type { PipelineStep } from '@/types/utility' -import { childSequences, isBranchStep, isEachStep, isUtilityStep, utilityIds } from '@/core/steps' +import type { BranchStep, Condition, EachStep, PipelineStep, ValueType } from '@/types/utility' +import { isBranchStep, isEachStep, isMacroStep, isUtilityStep, utilityIds, walkSteps } from '@/core/steps' import { itemNoun } from '@/core/split' import { RECIPE_CATEGORIES, RECIPES_PATH, recipePath, type Recipe, type RecipeMeta, type RecipeSample } from '@/recipes/types' import type { Preview, SkipTrace, StepTrace } from '@/recipes/trace' import { utilityPath } from '../related' -import { changedParams, describeString, nameOf, revealInvisible, stepTitle, stringPairs, type UtilityLookup } from './recipeHelpers' +import { changedParams, describeString, nameOf, revealInvisible, stepCountText, stepTitle, stringPairs, type UtilityLookup } from './recipeHelpers' /** One param value, as the recipe runs it: strings raw (never JSON-escaped), rule tables as rows. */ function ParamValue({ value }: { value: unknown }) { @@ -69,32 +69,131 @@ function PreviewBlock({ preview, label }: { preview: Preview; label: string }) { ) } -/** Links to the utilities a step uses (a branch's lanes, a macro's or an each step's body). */ -function StepUtilities({ step, utility }: { step: PipelineStep; utility: UtilityLookup }) { - if (isUtilityStep(step)) { - return {nameOf(step.utilityId, utility)} +const VALUE_TYPE_NAMES: Record = { string: 'text', bytes: 'bytes', json: 'JSON' } + +/** A regex condition's flags in words: `i` is the one recipes use. */ +function flagNote(flags = ''): string { + const other = flags.replace('i', '') + const notes = [flags.includes('i') ? 'ignoring case' : '', other ? `flags ${other}` : ''].filter(Boolean) + return notes.length ? ` (${notes.join(', ')})` : '' +} + +/** What a step's condition does, worded the same for a top-level step and a nested one. */ +function ConditionNote({ condition }: { condition?: Condition }) { + if (!condition || condition.kind === 'always') return null + const what = condition.kind === 'regex' + ? <>matches {condition.pattern}{flagNote(condition.flags)} + : condition.kind === 'nonEmpty' ? 'is not empty' : `is ${VALUE_TYPE_NAMES[condition.type]}` + return ( +

+ {condition.negate + ? <>Skipped (its input passes through) when the input {what}. + : <>Runs only when its input {what}; otherwise the input passes through.} +

+ ) +} + +/** A failure policy other than the default (a failed step hands its input on). */ +function ErrorNote({ step }: { step: PipelineStep }) { + if (!step.onError || step.onError === 'passthrough') return null + const noun = isEachStep(step) ? itemNoun(step.split.mode, 1) : '' + const text = isEachStep(step) + ? step.onError === 'empty' ? `A ${noun} whose steps fail comes out empty.` : `One ${noun} that fails fails the whole step.` + : step.onError === 'empty' ? 'If it fails, the next step gets empty input.' : 'If it fails, the steps after it do not run.' + return

{text}

+} + +/** How a "run on each" step cuts its input, as the line above its steps. */ +function eachIntro(step: EachStep): React.ReactNode { + const empty = step.skipEmpty === false ? ', empty ones included,' : '' + switch (step.split.mode) { + case 'lines': return <>Each line{empty} goes through: + case 'delimiter': return <>Each item between {describeString(step.split.separator)}{empty} goes through: + case 'json-array': return <>Each element of the JSON array{empty} goes through: + case 'json-values': return <>Each value of the JSON object{empty} goes through: } - const lanes = childSequences(step) +} + +/** How a branch puts its lanes back together, as the line above its lanes. */ +function branchIntro(step: BranchStep): React.ReactNode { + const merge = step.merge ?? { mode: 'concat' } + const sep = (separator = '\n') => {describeString(separator)} + switch (merge.mode) { + case 'concat': return <>Every lane gets the same input, and their outputs are joined with {sep(merge.separator)}: + case 'zip': return <>Every lane gets the same input, and their outputs are interleaved line by line, joined with {sep(merge.separator)}: + case 'json': return <>Every lane gets the same input, and their outputs are collected into a JSON array: + case 'pick': return <>Every lane gets the same input, and only lane {merge.index + 1}’s output is kept: + } +} + +/** A nested step's name: a link to its utility's page, after the step's own label when it has one. */ +function NestedTitle({ step, utility }: { step: PipelineStep; utility: UtilityLookup }) { + if (!isUtilityStep(step)) return {stepTitle(step, utility)} + const link = {nameOf(step.utilityId, utility)} + return step.label + ? {step.label} ({link}) + : {link} +} + +/** Steps inside a container, in order, each with everything it is set to. */ +function StepSequence({ steps, utility }: { steps: PipelineStep[]; utility: UtilityLookup }) { return ( -
    - {lanes.map((lane, i) => ( -
  1. - {isBranchStep(step) && lane {i + 1}:} - {isEachStep(step) && on each {itemNoun(step.split.mode, 1)}:} - {lane.map((s, j) => ( - - {j > 0 && →} - {isUtilityStep(s) - ? {stepTitle(s, utility)} - : {stepTitle(s, utility)}} - - ))} +
      + {steps.map(s => ( +
    1. + +
    2. ))}
    ) } +/** What runs inside a branch, macro or "run on each" step, containers within containers included. */ +function ContainerBody({ step, utility }: { step: PipelineStep; utility: UtilityLookup }) { + if (isEachStep(step)) { + return ( +
    +

    {eachIntro(step)}

    + +
    + ) + } + if (isBranchStep(step)) { + return ( +
    +

    {branchIntro(step)}

    +
      + {step.branches.map((lane, i) => ( +
    1. + Lane {i + 1}{lane.length === 0 ? ': its input, unchanged' : ':'} + {lane.length > 0 && } +
    2. + ))} +
    +
    + ) + } + if (isMacroStep(step)) return + return null +} + +/** + * Everything a step is set to: its condition, failure policy and changed params, then + * (for a container) the steps it runs, each shown the same way. The pre-rendered page + * is all a crawler or a visitor without JavaScript gets, so nothing here may hide. + */ +function StepSettings({ step, utility }: { step: PipelineStep; utility: UtilityLookup }) { + return ( + <> + + + + + + ) +} + export interface RecipeWidgetProps { samples: RecipeSample[] sampleId: string @@ -173,7 +272,7 @@ export function RecipeWidget(props: RecipeWidgetProps) { Open in the editor - {stepCount} steps, every one editable. Runs in your browser: nothing you paste is uploaded. + {stepCountText(stepCount)}, every one editable. Runs in your browser: nothing you paste is uploaded. {extension} @@ -202,7 +301,9 @@ export interface RecipeArticleProps { export function RecipeArticle({ recipe, utility, guideHtml, steps, skip, live, related, ad, running }: RecipeArticleProps) { const traceOf = new Map(steps.map(s => [s.id, s])) const skipOf = new Map((skip ?? []).map(s => [s.id, s])) - const index = new Map(recipe.steps.map((s, i) => [s.id, i + 1])) + // every step id, nested ones included, to the number of the top-level step it is in + const index = new Map() + recipe.steps.forEach((top, i) => walkSteps([top], s => { index.set(s.id, i + 1) })) const firstSample = recipe.samples[0] const utilitiesUsed = utilityIds(recipe.steps) @@ -239,17 +340,12 @@ export function RecipeArticle({ recipe, utility, guideHtml, steps, skip, live, r

    {s.why}

    - - {s.condition?.kind === 'regex' && ( -

    - {s.condition.negate - ? <>Skipped (its input passes through) when the input matches {s.condition.pattern}. - : <>Runs only when its input matches {s.condition.pattern}; otherwise the input passes through.} -

    + {isUtilityStep(s) && ( + {nameOf(s.utilityId, utility)} )} - +
    -
    +
    {trace?.error &&

    This step failed: {trace.error}

    } {trace?.skipped &&

    Its condition did not match this input, so the input passed through unchanged.

    } {trace?.output && } @@ -276,10 +372,8 @@ export function RecipeArticle({ recipe, utility, guideHtml, steps, skip, live, r {recipe.steps.map((s, i) => { const result = skipOf.get(s.id) if (!result) return null - const failed = result.error && recipe.steps.find(t => t.id === result.error!.stepId) - const where = result.error - ? index.has(result.error.stepId) ? `step ${index.get(result.error.stepId)} (${stepTitle(failed!, utility)})` : 'a later step' - : '' + const at = result.error && index.get(result.error.stepId) + const where = at ? `step ${at} (${stepTitle(recipe.steps[at - 1], utility)})` : 'a later step' return (
  2. Without step {i + 1}, {stepTitle(s, utility)}

    diff --git a/src/app/pages/recipes/RecipePage.tsx b/src/app/pages/recipes/RecipePage.tsx index 09c015e..4d31951 100644 --- a/src/app/pages/recipes/RecipePage.tsx +++ b/src/app/pages/recipes/RecipePage.tsx @@ -88,7 +88,13 @@ function readEmbeddedTrace(recipe: Recipe, steps: PipelineStep[]): RecipeTrace | } } -const runInBrowser: PipelineRunner = (input, steps, previews) => execute(input, steps, { previews }) +/** + * The browser's runner for the skip traces, cancelled with `signal`: the in-flight run + * is aborted and no further one starts, so a page left behind stops taking turns on + * the executor that the next page's runs use. + */ +const runInBrowser = (signal: AbortSignal): PipelineRunner => (input, steps, previews) => + signal.aborted ? Promise.reject(new Error('the recipe page was left')) : execute(input, steps, { previews, signal }) const COPIED_MS = 2000 @@ -126,13 +132,13 @@ function RecipeView({ data }: { data: RecipeData }) { const [skip, setSkip] = useState(embedded?.skip ?? null) useEffect(() => { if (embedded) return - let cancelled = false - traceRecipe(recipe, runInBrowser).then( - trace => { if (!cancelled) setSkip(trace.skip) }, + const left = new AbortController() + traceRecipe(recipe, runInBrowser(left.signal)).then( + trace => { if (!left.signal.aborted) setSkip(trace.skip) }, // the section is a bonus: without it the page is still complete - () => { if (!cancelled) setSkip([]) }, + () => { if (!left.signal.aborted) setSkip([]) }, ) - return () => { cancelled = true } + return () => left.abort() }, [recipe, embedded]) const blank = held || failed diff --git a/src/app/pages/recipes/recipeHelpers.ts b/src/app/pages/recipes/recipeHelpers.ts index 8dbd461..6232274 100644 --- a/src/app/pages/recipes/recipeHelpers.ts +++ b/src/app/pages/recipes/recipeHelpers.ts @@ -24,6 +24,9 @@ export function stepTitle(step: PipelineStep, utility: UtilityLookup): string { return 'Step' } +/** "1 step", "4 steps": a recipe's numbered (top-level) steps, as the page and its share card count them. */ +export const stepCountText = (n: number): string => `${n} ${n === 1 ? 'step' : 'steps'}` + /** * Params that differ from the utility's defaults: what the recipe actually sets, * each with the label the editor shows for it. From 89c26c49beb4785f57c4037ab2c2dada10ba7573 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 00:36:59 +0000 Subject: [PATCH 4/5] refactor(recipes): use run-on-each in three recipes - excel-column-to-sql-in-clause: sql_escape runs per value, so the mysql and mssql flavors work (mysql used to merge the column into one value). - decode-cloudwatch-logs-data: every record of a batch is decoded, events printed by Python or Node are found, and a message ending in a literal \n no longer fails (6 steps to 4; the kinesis sample is now a 2-record batch with the same golden output). - bulk-utm-link-builder: old utm_* tags are dropped with query_params_normalize per link (keys with digits, without = or percent-encoded now go too). utm_ tags inside a #fragment stay. Goldens are unchanged on every sample. Guides, CHANGELOG and CLAUDE.md updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016MBDS61t2hQgzoraTNWAvz --- CHANGELOG.md | 19 +++++ CLAUDE.md | 16 ++-- src/app/pages/recipes/RecipePage.test.tsx | 29 ++++++- src/recipes/_generated/index.ts | 34 ++++---- src/recipes/bulk-utm-link-builder/guide.md | 6 +- src/recipes/bulk-utm-link-builder/recipe.ts | 24 +++--- .../decode-cloudwatch-logs-data/guide.md | 31 +++++--- .../decode-cloudwatch-logs-data/recipe.ts | 78 +++++++++++-------- .../excel-column-to-sql-in-clause/guide.md | 8 +- .../excel-column-to-sql-in-clause/recipe.ts | 16 ++-- 10 files changed, 164 insertions(+), 97 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d8cbe4..5d7473e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,11 +13,30 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). desktop Chrome, Edge or other Chromium browser without it, the page links to the extension's Chrome Web Store listing instead; other browsers and phones, which can't install it, see neither. +### Changed + +- Recipe pages show what runs inside a run-on-each or branch step: every nested step with its link, the + settings it changes, its condition and what happens when it fails, how an each step splits its input and + how a branch merges its lanes, in the pre-rendered page too. +- **Decode CloudWatch Logs subscription data** decodes every record of a Kinesis or Firehose batch, not + only the first, and finds the payload in an event printed by Python or Node.js. A message ending in a + literal `\n` no longer stops it. +- **Excel column to SQL IN clause** escapes and quotes each value on its own, so the `mysql` flavor + (backslash escapes) and the `mssql` flavor (`N'…'` for non-ASCII values) work per value. +- **Bulk UTM link builder** removes old `utm_` parameters with *normalize query params*, so names with + digits, without `=` or percent-encoded are removed too, and the drop list takes more names (`fbclid`, + `gclid`). Tags inside a `#fragment` are no longer removed. + ### Fixed - CSV: an empty value in a one-column table no longer disappears. `csv normalize headers` used to drop it (it parsed as a blank line), and `json to csv` wrote it as a blank line that `csv to json` skipped; both now write it as `""`, and `csv normalize headers` also keeps a final `""` that has no trailing newline. +- **gzip decompress** reports short input that is not gzip (`{`, `[`, a cut-off `H4sIAAAA`) as not valid + gzip data instead of a failed integrity check. +- A recipe page with one numbered step says "1 step", on the page and on its share card. +- Leaving a recipe page stops working out its "What if you skip a step?" examples, instead of running them + on in the background while the next page waits for the engine. ## [1.5.0] - 2026-10-07 diff --git a/CLAUDE.md b/CLAUDE.md index eb45f92..ff62534 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,17 +88,21 @@ npm run release -- plan # what a release from HEAD would ship, at which versio ### Recipes (`src/recipes/`) — pre-rendered pipeline pages - A recipe is a hand-picked multi-step pipeline for one real task, published at `/recipes//` (index: `/recipes/`). - Folder per recipe: `recipe.ts` (default export `Recipe`: steps built with `step()`/`branch()`/`each()`/`laneStep()` from - `define.ts`, each top-level step with a `why`; `each()` runs `laneStep()`s on every line or JSON value; 2+ `samples` with golden outputs, the first is the page's worked - example) and `guide.md` (frontmatter `title`/`description` for the page head, then prose `##` sections — no + Folder per recipe: `recipe.ts` (default export `Recipe`: top-level steps built with `step()`/`branch()`/`each()` from + `define.ts`, each with a `why`; nested steps with `laneStep()`/`laneBranch()`/`laneEach()`, which carry no `why` and + spell out regex condition flags as `sanitizeSteps` stores them (never raw literals); `each()` runs its steps on every + line or JSON value; 2+ `samples` with golden outputs, the first is the page's worked example) and `guide.md` (frontmatter `title`/`description` for the page head, then prose `##` sections — no example blocks). `npm run gen` also writes `src/recipes/_generated/` (`index.ts` metadata, `loaders.ts` one chunk per recipe with its guide via `?raw`, `static.ts` for Node); `generated.test.ts` fails when stale. - Rules (`check.ts`, run by `recipes.test.ts` and `check:recipes`): real utilities/params, no `dom`/`main`/`eval` steps (the build runs recipes in Node, the page in a worker), every sample reproduces its output on every run and - at any date, **every top-level step changes some sample's output when left out** (no padding), 2+ real steps or a - branch, title/description/primaryQuery unique across recipes and utility guides, `primaryQuery` not a utility - guide title's head term (no competing with `/util//`), ≥300 words of guide prose, no near-copied prose. + at any date, **every top-level step changes some sample's output when left out** (no padding), 2+ real utility steps + counting nested ones (one utility wrapped in `each` is still one), title/description/primaryQuery unique across recipes + and utility guides, `primaryQuery` neither inside a utility guide title nor containing its head term (the title before + " — ", minus "Online": "bulk slug generator" competes with `/util/slug/`), ≥300 words of guide prose, no near-copied prose. - `trace.ts` turns a run into what the page shows (each step's output, what leaving each step out does). + `RecipeArticle` renders nested steps recursively (params, conditions, failure policy, split and merge modes): + the pre-rendered page is all a crawler sees, so a setting inside a lane must show there. `scripts/seo/build.ts` traces every recipe with the static registry, **fails the build** if the first sample's output drifted, renders `RecipeArticle` with `renderToStaticMarkup` and embeds the trace as `