From d1356b3c54724fc6a6e9818be8e8a5bf4b95c020 Mon Sep 17 00:00:00 2001 From: Christoph Auer Date: Sat, 31 Oct 2026 20:06:00 +0100 Subject: [PATCH 1/3] Add GitHub Pages documentation and SELECT-to-Delphi converter --- .github/workflows/pages.yml | 62 ++++ .gitignore | 2 + docs/WEBSITE.md | 104 ++++++ website/app.mjs | 49 +++ website/build.mjs | 85 +++++ website/converter.html | 11 + website/converter.mjs | 203 ++++++++++++ website/favicon.svg | 1 + website/navigation.mjs | 36 +++ website/package-lock.json | 558 ++++++++++++++++++++++++++++++++ website/package.json | 20 ++ website/preview.mjs | 15 + website/style.css | 68 ++++ website/test/converter.test.mjs | 123 +++++++ website/test/site.test.mjs | 25 ++ 15 files changed, 1362 insertions(+) create mode 100644 .github/workflows/pages.yml create mode 100644 docs/WEBSITE.md create mode 100644 website/app.mjs create mode 100644 website/build.mjs create mode 100644 website/converter.html create mode 100644 website/converter.mjs create mode 100644 website/favicon.svg create mode 100644 website/navigation.mjs create mode 100644 website/package-lock.json create mode 100644 website/package.json create mode 100644 website/preview.mjs create mode 100644 website/style.css create mode 100644 website/test/converter.test.mjs create mode 100644 website/test/site.test.mjs diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..b705fd0 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,62 @@ +name: Documentation & SQL converter + +on: + push: + branches: [main] + paths: + - 'README.md' + - 'CHANGELOG.md' + - 'docs/**' + - 'src/**' + - 'website/**' + - '.github/workflows/pages.yml' + pull_request: + paths: + - 'README.md' + - 'CHANGELOG.md' + - 'docs/**' + - 'src/**' + - 'website/**' + - '.github/workflows/pages.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + defaults: + run: + working-directory: website + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: '24' + cache: npm + cache-dependency-path: website/package-lock.json + - run: npm ci + - run: npm test + - run: npm run build + - run: npm run test:site + - uses: actions/upload-pages-artifact@v4 + with: + path: website/dist + + deploy: + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + concurrency: + group: github-pages + cancel-in-progress: false + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/deploy-pages@v4 + id: deployment diff --git a/.gitignore b/.gitignore index dabc57d..7ca5f8c 100644 --- a/.gitignore +++ b/.gitignore @@ -85,3 +85,5 @@ __pycache__/ tools/oracle/bin/ tools/oracle/obj/ build/ +website/node_modules/ +website/dist/ diff --git a/docs/WEBSITE.md b/docs/WEBSITE.md new file mode 100644 index 0000000..8c8f56f --- /dev/null +++ b/docs/WEBSITE.md @@ -0,0 +1,104 @@ +# Documentation website and SQL converter + +The website is a static GitHub Pages application. **Documentation stays in +`README.md`, `CHANGELOG.md`, and `docs/*.md`.** The build reads these files +directly; do not copy their contents into website templates. Every Markdown +file immediately inside `docs/` becomes a page. Add navigation entries in +`website/build.mjs` when introducing a new guide. + +Markdown links between documentation pages become relative HTML links, +including heading anchors. Links to source files and other repository artifacts +point back to GitHub. The generated pages include syntax highlighting, an +on-page contents list, and a link to their original Markdown source. +The generated `website/dist/` directory is ignored by Git. + +## Local development + +Requires Node.js 24 and npm. From the repository root: + +```sh +cd website +npm ci +npm test +npm run build +npm run test:site +npm run preview +``` + +Open `http://127.0.0.1:4173/` for documentation or +`http://127.0.0.1:4173/converter.html` for the converter. Rebuild after editing +Markdown or website sources, then refresh the browser. Stop preview with Ctrl+C. + +The build bundles all browser dependencies locally; no CDN, backend, database, +AI API, or analytics service is required. Only the selected dialect's parser is +loaded. SQL input is processed in memory and is neither uploaded nor persisted. + +## GitHub Pages deployment + +1. Merge the website files and `.github/workflows/pages.yml` into `main`. +2. In the repository's **Settings → Pages → Build and deployment**, select + **GitHub Actions** as the source. +3. Run **Documentation & SQL converter** from the Actions tab, or push a change + to the website, documentation or library sources on `main`. + +The workflow tests the converter, builds the documentation, checks generated +links and anchors, and uploads a Pages artifact. Pull requests run these checks +without deploying. The deployment job runs only on `main` and uses the +`github-pages` environment, with write permissions scoped to that job. +If environment protection requires approval, approve the deployment in GitHub. + +The default project URL is `https://auchri.github.io/QueryBuilder4Delphi/`. +All local asset and page links are relative, so the project subpath is supported. +If the repository or default branch changes, update the workflow branch filters +and repository links in `website/build.mjs`. + +## SELECT conversion + +`website/converter.mjs` parses SQL with `node-sql-parser` and translates a +deliberately bounded subset into the library's actual fluent API. The result is +a `BuildQuery: IQuery` function and its required imports. The browser never +compiles Delphi or executes SQL. Use the correct output dialect with +`BuildQuery.Compile(TSqlDialect.MySql)` or another matching dialect in Delphi. + +Supported input dialects: MySQL, PostgreSQL, SQL Server and SQLite. + +- Column selection, wildcards, DISTINCT, table and column aliases. +- INNER, LEFT and RIGHT JOIN with one column comparison; CROSS JOIN. +- Nested AND/OR conditions, scalar and column comparisons, LIKE/NOT LIKE, + IN/NOT IN, BETWEEN/NOT BETWEEN, IS NULL/IS NOT NULL. +- GROUP BY columns and HAVING using the same supported conditions. +- ORDER BY columns, ascending or descending. +- Literal LIMIT/OFFSET, MySQL-style LIMIT offset,count, and SQL Server + TOP and OFFSET/FETCH. + +String values retain doubled apostrophes and control characters correctly in +Delphi syntax. PostgreSQL unquoted names are folded to lowercase; double-quoted +names retain their case. Values become library bindings when the generated query +is compiled. Comments are omitted from generated code. + +Simple LIKE patterns use the corresponding fluent helper: `foo%` becomes +`WhereStarts('a', 'foo')`, `%foo` becomes `WhereEnds`, and `%foo%` becomes +`WhereContains`. Other patterns use `WhereLike` with the complete pattern. +NOT LIKE, OR conditions and HAVING use their corresponding method variants. + +Unsupported syntax produces an error and clears any earlier output. There is no +partial conversion or raw SQL fallback. This includes writes, multiple +statements, CTEs, unions, subqueries, aggregate/function expressions, complex +JOIN predicates, placeholders, unusual identifiers, window clauses, locking +clauses, DISTINCT ON and TOP PERCENT/WITH TIES. MySQL backslash string escapes +are rejected because they depend on SQL mode. Use SQL-standard doubled quotes. +Identifiers currently use ASCII letters, digits, underscore and dollar signs, +and cannot begin with a digit. Numeric literals are limited to 15 significant +digits and JavaScript's safe integer range. Paging counts must fit a Delphi +Integer. Zero row limits are rejected because the library's `Limit(0)` means +unlimited. SQL dialects and database collations can still affect comparisons; +review generated code against your application's schema and dialect. + +## Validation + +`npm test` checks conversion across all four dialects, aliases and JOIN argument +order, condition grouping, string escaping, NULL handling, paging, rejected +constructs, and emitted method names against the Delphi interface. +`npm run test:site`, after building, checks local links, heading anchors, assets +and compatibility with a project URL subpath. Delphi compilation is a separate +check and requires an available Delphi compiler. diff --git a/website/app.mjs b/website/app.mjs new file mode 100644 index 0000000..6c49ed9 --- /dev/null +++ b/website/app.mjs @@ -0,0 +1,49 @@ +import { convert } from './converter.mjs'; +const $ = id => document.getElementById(id); +const examples = { + basic: 'SELECT Id, Title\nFROM Books\nWHERE AuthorId = 42\nORDER BY Title;', + join: "SELECT b.Id, b.Title, a.Name AS AuthorName\nFROM Books AS b\nLEFT JOIN Authors AS a ON a.Id = b.AuthorId\nWHERE b.Price >= 10\nORDER BY b.Title;", + group: "SELECT Id, Title\nFROM Books\nWHERE (AuthorId = 42 OR AuthorId = 7)\n AND Price BETWEEN 10 AND 50\n AND DeletedAt IS NULL\nORDER BY Title DESC;", + paging: 'SELECT Id, Title\nFROM Books\nORDER BY Title, Id\nLIMIT 20 OFFSET 40;', +}; +let revision = 0; +function invalidate() { + revision++; + $('delphi').value = ''; + $('copy').disabled = true; + $('status').textContent = 'Ready to convert.'; + $('status').className = ''; +} +async function run() { + invalidate(); + const current = revision; + $('convert').disabled = true; + $('status').textContent = 'Converting…'; + try { + const code = await convert($('sql').value, $('dialect').value); + if (current !== revision) return; + $('delphi').value = code; + $('copy').disabled = false; + $('status').textContent = 'Converted. Values use the library’s parameterized API.'; + } catch (error) { + if (current !== revision) return; + $('status').textContent = error.message; + $('status').className = 'error'; + } finally { $('convert').disabled = false; } +} +$('convert').addEventListener('click', run); +$('sql').addEventListener('input', invalidate); +$('dialect').addEventListener('change', invalidate); +$('load-example').addEventListener('click', () => { + $('sql').value = $('example').value === 'paging' && $('dialect').value === 'TransactSQL' + ? 'SELECT TOP 20 Id, Title\nFROM Books\nORDER BY Title, Id;' : examples[$('example').value]; + invalidate(); +}); +$('copy').addEventListener('click', async () => { + try { await navigator.clipboard.writeText($('delphi').value); $('status').textContent = 'Delphi code copied.'; } + catch { $('delphi').focus(); $('delphi').select(); $('status').textContent = 'Select the output and copy it with Ctrl+C (or ⌘C).'; } +}); +$('sql').addEventListener('keydown', event => { + if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); run(); } +}); +run(); diff --git a/website/build.mjs b/website/build.mjs new file mode 100644 index 0000000..89832aa --- /dev/null +++ b/website/build.mjs @@ -0,0 +1,85 @@ +import { readdir, readFile, mkdir, writeFile, cp } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { Marked } from 'marked'; +import GithubSlugger from 'github-slugger'; +import hljs from 'highlight.js'; +import { build } from 'esbuild'; + +export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const site = path.join(root, 'website'); +export const output = path.join(site, 'dist'); +const repo = 'https://github.com/auchri/QueryBuilder4Delphi'; +const escape = s => String(s).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"'); +export const documents = ['README.md', 'CHANGELOG.md', ...(await readdir(path.join(root, 'docs'))).filter(f => f.endsWith('.md')).map(f => `docs/${f}`)]; +const target = source => source === 'README.md' ? 'index.html' : source.replace(/\.md$/, '.html'); +export function linkTo(href, source) { + if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(href)) return href; + const match = href.match(/^([^?#]*)(.*)$/); + const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(source), decodeURI(match[1]))); + if (!documents.includes(resolved)) return `${repo}/blob/main/${resolved}${match[2]}`; + return path.posix.relative(path.posix.dirname(target(source)), target(resolved)) + match[2]; +} +const menu = [ + ['README.md', 'Overview'], ['converter.html', 'SQL → Delphi'], + ['docs/EXAMPLES.md', 'Examples'], ['docs/API.md', 'API & limitations'], + ['docs/OBJECT_MAPPING.md', 'Object mapping'], ['docs/PORTING.md', 'Porting'], + ['docs/VALIDATION.md', 'Validation'], ['docs/XML_DOCUMENTATION.md', 'XML documentation'], + ['docs/MAPPING_PERFORMANCE.md', 'Mapping performance'], ['CHANGELOG.md', 'Changelog'], + ['docs/WEBSITE.md', 'Website maintenance'], +]; +function shell(title, body, source, toc = []) { + const filename = target(source); + const prefix = path.posix.relative(path.posix.dirname(filename), '.') || '.'; + const relative = to => path.posix.relative(path.posix.dirname(filename), to); + return ` + +${escape(title)} · QueryBuilder4Delphi + +
QueryBuilder4DelphiGitHub ↗
+
+
${body}
+${toc.length ? `` : ''}
+ +`; +} +await mkdir(path.join(output, 'assets'), { recursive: true }); +for (const source of documents) { + const markdown = await readFile(path.join(root, source), 'utf8'); + const slugger = new GithubSlugger(); + const toc = []; + const marked = new Marked({ renderer: { + heading({ tokens, depth }) { + const text = this.parser.parseInline(tokens); + const id = slugger.slug(text.replace(/<[^>]+>/g, '')); + if (depth === 2) toc.push({ id, text }); + return `${text}#`; + }, + link({ href, title, tokens }) { return `${this.parser.parseInline(tokens)}`; }, + code({ text, lang }) { + const language = (lang || '').split(/\s/)[0]; + const html = hljs.getLanguage(language) ? hljs.highlight(text, { language }).value : escape(text); + return `
${escape(language || 'text')}
${html}
`; + }, + }}); + const body = marked.parse(markdown); + const title = markdown.match(/^# (.+)/m)?.[1] || source; + const file = path.join(output, target(source)); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, shell(title, body, source, toc)); +} +const converter = await readFile(path.join(site, 'converter.html'), 'utf8'); +await writeFile(path.join(output, 'converter.html'), shell('SQL to Delphi', converter, 'converter.html')); +await cp(path.join(site, 'style.css'), path.join(output, 'assets/style.css')); +await cp(path.join(site, 'favicon.svg'), path.join(output, 'assets/favicon.svg')); +await cp(path.join(site, 'node_modules/highlight.js/styles/github-dark.css'), path.join(output, 'assets/highlight.css')); +const licenses = []; +for (const name of ['node-sql-parser', 'big-integer', 'highlight.js']) { + const dependency = path.join(site, 'node_modules', name); + const pkg = JSON.parse(await readFile(path.join(dependency, 'package.json'), 'utf8')); + licenses.push(`${name} ${pkg.version}\n${await readFile(path.join(dependency, 'LICENSE'), 'utf8')}`); +} +await writeFile(path.join(output, 'assets/third-party-licenses.txt'), licenses.join('\n\n---\n\n')); +await writeFile(path.join(output, '.nojekyll'), ''); +await build({ entryPoints: ['app.mjs', 'navigation.mjs'].map(file => path.join(site, file)), outdir: path.join(output, 'assets'), bundle: true, splitting: true, format: 'esm', minify: true, entryNames: '[name]', chunkNames: '[name]-[hash]', logLevel: 'info' }); +console.log(`Built ${documents.length} documentation pages directly from repository Markdown, plus the converter.`); diff --git a/website/converter.html b/website/converter.html new file mode 100644 index 0000000..96d9dda --- /dev/null +++ b/website/converter.html @@ -0,0 +1,11 @@ +

THE QUERY WORKBENCH

+

SQL in. Delphi out.

+

Turn a SELECT query into fluent QueryBuilder4Delphi code. Everything runs in your browser; your SQL stays on your device.

+
+
SELECT
+

Ready to convert.

+

What can I convert?

One SELECT statement with table and column aliases, DISTINCT, INNER/LEFT/RIGHT JOIN with one column comparison, CROSS JOIN, grouped AND/OR conditions, column comparisons, LIKE, IN, BETWEEN, IS NULL, GROUP BY, simple HAVING, ORDER BY and literal paging values. SQL Server TOP and OFFSET/FETCH are also supported.

CTEs, unions, subqueries, aggregate/function expressions, complex JOIN conditions, placeholders, quoted identifiers containing spaces or punctuation, and dialect-specific extensions are rejected. No partial code or raw SQL fallback is emitted. Numbers are limited to 15 significant digits. Zero row limits and MySQL string literals with backslash escapes are rejected because their meaning cannot be preserved reliably.

The output is a complete BuildQuery: IQuery function. Compile it with your chosen TSqlDialect in Delphi; the converter does not execute SQL or run the Delphi compiler. PostgreSQL unquoted identifiers are folded to lowercase. SQL comments are not included in the output.

+ diff --git a/website/converter.mjs b/website/converter.mjs new file mode 100644 index 0000000..12edf99 --- /dev/null +++ b/website/converter.mjs @@ -0,0 +1,203 @@ +// The parser only reads SQL. Generated code uses the library's parameterized API. +const dialects = { + MySQL: () => import('node-sql-parser/build/mysql.js'), + PostgreSQL: () => import('node-sql-parser/build/postgresql.js'), + TransactSQL: () => import('node-sql-parser/build/transactsql.js'), + SQLite: () => import('node-sql-parser/build/sqlite.js'), +}; +const unsupported = detail => { throw new Error(`${detail} is not supported in this version. No code was generated.`); }; +const meaningful = value => value != null && value !== false && value !== '' && + (typeof value !== 'object' || Object.values(value).some(meaningful)); +function check(node, keys, context) { + for (const [key, value] of Object.entries(node)) { + if (!keys.includes(key) && meaningful(value)) unsupported(`${context}: ${key}`); + } +} +export function delphiString(value) { + // Delphi strings cannot contain physical line breaks. Keep control characters explicit. + return String(value).split(/([\x00-\x1f\x7f])/).filter(Boolean).map(part => + /^[\x00-\x1f\x7f]$/.test(part) ? `#${part.charCodeAt(0)}` : `'${part.replaceAll("'", "''")}'` + ).join('') || "''"; +} +function identifier(value) { + if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_$]*$/.test(value)) unsupported('Identifiers containing spaces, punctuation or non-ASCII characters'); + return value; +} +function column(node, star = false) { + if (node?.type !== 'column_ref') unsupported('Expressions, functions and subqueries in place of columns'); + check(node, ['type', 'table', 'column', 'parentheses', 'loc'], 'Column'); + const name = typeof node.column === 'object' ? node.column.expr?.value : node.column; + return (node.table ? `${identifier(node.table)}.` : '') + (star && name === '*' ? '*' : identifier(name)); +} +function table(node) { + check(node, ['db', 'schema', 'table', 'as', 'join', 'on', 'loc'], 'FROM/JOIN'); + if (!node.table) unsupported('Derived tables'); + return [node.db, node.schema, node.table].filter(Boolean).map(identifier).join('.') + (node.as ? ` as ${identifier(node.as)}` : ''); +} +function literal(node, literals) { + if (!node) unsupported('Missing values'); + check(node, ['type', 'value', 'loc'], 'Value'); + if (['single_quote_string', 'string'].includes(node.type)) { + if (!literals.has(node.value)) unsupported('This string literal syntax'); + return delphiString(literals.get(node.value)); + } + if (['bool', 'boolean'].includes(node.type)) return node.value ? 'True' : 'False'; + if (node.type === 'number') { + const value = Number(node.value); + if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER || String(node.value).replace(/[^0-9]/g, '').replace(/^0+/, '').length > 15) unsupported('Numbers requiring more than 15 significant digits'); + if (Number.isInteger(value) && (value > 2147483647 || value < -2147483648)) return `Int64(${value})`; + return String(value); + } + unsupported('Parameters, NULL values in lists, or non-scalar values (use literal values for conversion)'); +} +const comparisons = ['=', '!=', '<>', '<', '>', '<=', '>=']; +function predicate(node, method = 'Where', indent = ' ', depth = 0, literals) { + if (depth > 30) unsupported('Conditions nested more than 30 levels'); + if (node?.type !== 'binary_expr') unsupported('This condition'); + check(node, ['type', 'operator', 'left', 'right', 'parentheses', 'loc'], 'Condition'); + const op = node.operator.toUpperCase(); + if (['AND', 'OR'].includes(op)) { + const base = method.replace(/^Or/, ''); + return `${indent}.${method}(\n${indent} function(Q: IQuery): IQuery\n${indent} begin\n${indent} Result := Q\n` + + predicate(node.left, base, indent + ' ', depth + 1, literals) + '\n' + + predicate(node.right, (op === 'OR' ? 'Or' : '') + base, indent + ' ', depth + 1, literals) + `;\n${indent} end)`; + } + const col = delphiString(column(node.left)); + if (['IS', 'IS NOT'].includes(op) && node.right.type === 'null') return `${indent}.${method}${op === 'IS NOT' ? 'Not' : ''}Null(${col})`; + if (['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'].includes(op)) { + if (node.right.type !== 'expr_list' || !Array.isArray(node.right.value)) unsupported('Subqueries in conditions'); + check(node.right, ['type', 'value', 'parentheses', 'loc'], 'Value list'); + const values = node.right.value.map(value => literal(value, literals)); + const between = op.includes('BETWEEN'); + if ((between && values.length !== 2) || !values.length) unsupported('This value list'); + return `${indent}.${method}${op.startsWith('NOT ') ? 'Not' : ''}${between ? 'Between' : 'In'}(${col}, ${between ? values.join(', ') : `[${values.join(', ')}]`})`; + } + if (![...comparisons, 'LIKE', 'NOT LIKE'].includes(op)) unsupported(`Operator ${op}`); + if (node.right.type === 'column_ref') { + if (!comparisons.includes(op)) unsupported('Column comparisons with LIKE'); + return `${indent}.${method}Columns(${col}, ${delphiString(op)}, ${delphiString(column(node.right))})`; + } + if (['LIKE', 'NOT LIKE'].includes(op)) { + // Validate the scalar before choosing an idiomatic string helper. These + // helpers add only their boundary wildcards and do not escape the value. + literal(node.right, literals); + const pattern = literals.get(node.right.value); + if (typeof pattern !== 'string') unsupported('LIKE with a non-string pattern'); + const simple = pattern.match(/^(%?)([^%_\\[\]]+)(%?)$/); + let suffix = 'Like'; + let value = pattern; + if (simple && (simple[1] || simple[3])) { + suffix = simple[1] && simple[3] ? 'Contains' : simple[1] ? 'Ends' : 'Starts'; + value = simple[2]; + } + return `${indent}.${method}${op === 'NOT LIKE' ? 'Not' : ''}${suffix}(${col}, ${delphiString(value)})`; + } + return `${indent}.${method}(${col}, ${delphiString(op.toLowerCase())}, ${literal(node.right, literals)})`; +} +function integer(node, max) { + if (node?.type !== 'number' || !Number.isSafeInteger(Number(node.value)) || Number(node.value) < 0 || Number(node.value) > max) unsupported('Non-literal or out-of-range paging values'); + return Number(node.value); +} +export async function convert(sql, dialect = 'MySQL') { + if (!dialects[dialect]) unsupported('This SQL dialect'); + if (!sql.trim()) throw new Error('Enter a SELECT query to convert.'); + if (sql.length > 50000) throw new Error('Please use a query shorter than 50,000 characters.'); + const mod = await dialects[dialect](); + const Parser = mod.Parser || mod.default?.Parser; + let ast; + // Preserve SQL literal values ourselves: the parser decodes backslash escapes + // even in dialects where backslashes are ordinary characters. + const literals = new Map(); + sql = sql.replace(/--[^\r\n]*|#[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:\]\]|[^\]])*\]|'(?:''|[^'])*'|(?:\b\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/g, (token, offset) => { + if (dialect === 'MySQL' && token.startsWith('/*!')) unsupported('MySQL executable comments'); + if (/^(?:\d|\.\d)/.test(token)) { + const significant = token.split(/[eE]/)[0].replace('.', '').replace(/^0+/, ''); + if (significant.length > 15) unsupported('Numbers requiring more than 15 significant digits'); + if (Number(token) === 0 && /[1-9]/.test(significant)) unsupported('Numbers below the supported numeric range'); + return token; + } + if (!token.startsWith("'")) return token; + if (offset > 0 && /[A-Za-z0-9_$]/.test(sql[offset - 1])) unsupported('Prefixed string literals'); + if (dialect === 'MySQL' && token.includes('\\')) unsupported('MySQL string literals with backslash escapes (SQL mode dependent)'); + const marker = `QBD-LITERAL-${literals.size}`; + literals.set(marker, token.slice(1, -1).replaceAll("''", "'")); + return `'${marker}'`; + }); + // PostgreSQL folds unquoted identifiers to lowercase. Preserve quoted tokens, + // strings and comments, while normalizing the unquoted input before parsing. + if (dialect === 'PostgreSQL') sql = sql.replace(/("(?:""|[^"])*"|'(?:''|[^'])*'|--[^\r\n]*|\/\*[\s\S]*?\*\/)|\b[A-Za-z_][A-Za-z0-9_$]*\b/g, + (token, quoted) => quoted ? token : token.toLowerCase()); + try { ast = new Parser().astify(sql, { database: dialect }); } + catch (error) { throw new Error(`Cannot parse this ${dialect} query: ${error.message}`); } + if (Array.isArray(ast)) { + if (ast.length !== 1) unsupported('Multiple statements'); + [ast] = ast; + } + if (ast.type !== 'select') unsupported('Statements other than SELECT'); + check(ast, ['type', 'columns', 'from', 'where', 'distinct', 'groupby', 'having', 'orderby', 'limit', 'top', 'loc', 'parentheses_symbol', '_parentheses'], 'SELECT'); + if (!Array.isArray(ast.from) || !ast.from.length) unsupported('SELECT without a table'); + const lines = [` Result := TQuery.Create(${delphiString(table(ast.from[0]))})`]; + if (ast.from[0].join || ast.from[0].on) unsupported('This FROM clause'); + if (meaningful(ast.distinct)) { + if (ast.distinct !== 'DISTINCT' && !(ast.distinct.type === 'DISTINCT' && !meaningful(ast.distinct.on))) unsupported('DISTINCT ON'); + lines.push(' .Distinct'); + } + if (ast.columns === '*') lines.push(" .Select(['*'])"); + else lines.push(` .Select([${ast.columns.map(item => { + check(item, ['expr', 'as', 'type', 'loc'], 'SELECT item'); + if (item.type && item.type !== 'expr') unsupported('This SELECT item'); + const name = item.expr?.type === 'star' ? '*' : column(item.expr, true); + return delphiString(name + (item.as ? ` as ${identifier(item.as)}` : '')); + }).join(', ')}])`); + for (const join of ast.from.slice(1)) { + const target = delphiString(table(join)); + if (join.join === 'CROSS JOIN' && !join.on) { lines.push(` .CrossJoin(${target})`); continue; } + const method = { 'INNER JOIN': 'Join', 'LEFT JOIN': 'LeftJoin', 'RIGHT JOIN': 'RightJoin' }[join.join]; + const on = join.on; + if (!method || on?.type !== 'binary_expr' || !comparisons.includes(on.operator)) unsupported('JOINs other than INNER/LEFT/RIGHT with a single column comparison, or CROSS JOIN'); + check(on, ['type', 'operator', 'left', 'right', 'parentheses', 'loc'], 'JOIN condition'); + lines.push(` .${method}(${target}, ${delphiString(column(on.left))}, ${delphiString(column(on.right))}, ${delphiString(on.operator)})`); + } + if (ast.where) lines.push(predicate(ast.where, 'Where', ' ', 0, literals)); + if (ast.groupby) { + const group = ast.groupby; + if (!Array.isArray(group)) check(group, ['columns', 'modifiers'], 'GROUP BY'); + if (meaningful(group.modifiers)) unsupported('GROUP BY modifiers'); + lines.push(` .GroupBy([${(Array.isArray(group) ? group : group.columns).map(c => delphiString(column(c))).join(', ')}])`); + } + if (ast.having) lines.push(predicate(ast.having, 'Having', ' ', 0, literals)); + for (const order of ast.orderby || []) { + check(order, ['expr', 'type', 'loc'], 'ORDER BY'); + if (order.type && !['ASC', 'DESC'].includes(order.type)) unsupported('This sort direction'); + lines.push(` .OrderBy${order.type === 'DESC' ? 'Desc' : ''}(${delphiString(column(order.expr))})`); + } + if (ast.top) { + check(ast.top, ['value', 'percent', 'with_ties'], 'TOP'); + if (ast.top.percent || ast.top.with_ties) unsupported('TOP PERCENT/WITH TIES'); + const count = integer({ type: 'number', value: ast.top.value }, 2147483647); + if (count === 0) unsupported('TOP 0 (the library treats Limit(0) as unlimited)'); + lines.push(` .Limit(${count})`); + } + if (ast.limit?.offset || ast.limit?.fetch) { + check(ast.limit, ['offset', 'fetch'], 'Paging'); + if (ast.top) unsupported('TOP combined with OFFSET/FETCH'); + if (ast.limit.fetch) { + const count = integer(ast.limit.fetch.value, 2147483647); + if (!count) unsupported('FETCH 0'); + lines.push(` .Limit(${count})`); + } + if (ast.limit.offset) lines.push(` .Offset(${integer(ast.limit.offset.value, Number.MAX_SAFE_INTEGER)})`); + } else if (meaningful(ast.limit)) { + check(ast.limit, ['value', 'seperator'], 'Paging'); + const values = ast.limit.value; + if (!Array.isArray(values) || !values.length || values.length > 2 || !['', ',', 'offset'].includes(ast.limit.seperator || '')) unsupported('This paging syntax'); + const offsetFirst = ast.limit.seperator === ','; + const count = values[offsetFirst ? 1 : 0]; + const offset = values.length === 2 ? values[offsetFirst ? 0 : 1] : null; + const limit = integer(count, 2147483647); + if (limit === 0) unsupported('LIMIT 0 (the library treats Limit(0) as unlimited)'); + lines.push(` .Limit(${limit})`); + if (offset) lines.push(` .Offset(${integer(offset, Number.MAX_SAFE_INTEGER)})`); + } + return `uses\n QueryBuilder4Delphi.Query.Core,\n QueryBuilder4Delphi.Query;\n\nfunction BuildQuery: IQuery;\nbegin\n${lines.join('\n')};\nend;\n`; +} diff --git a/website/favicon.svg b/website/favicon.svg new file mode 100644 index 0000000..e9070c7 --- /dev/null +++ b/website/favicon.svg @@ -0,0 +1 @@ +Q diff --git a/website/navigation.mjs b/website/navigation.mjs new file mode 100644 index 0000000..d8273d7 --- /dev/null +++ b/website/navigation.mjs @@ -0,0 +1,36 @@ +// Native anchor navigation keeps URLs, keyboard access and browser history intact. +// CSS provides smooth scrolling, with an immediate fallback for reduced motion. +const backToTop = document.querySelector('.back-to-top'); +const links = [...document.querySelectorAll('.toc nav a')]; +const sections = links.map(link => ({ + link, + heading: document.getElementById(decodeURIComponent(link.hash.slice(1))), +})).filter(section => section.heading); +let scheduled = false; + +function updateNavigation() { + scheduled = false; + backToTop.hidden = window.scrollY < 400; + const offset = parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) + 32; + let current = null; + for (const section of sections) { + if (section.heading.getBoundingClientRect().top <= offset) current = section; + else break; + } + // Keep the final section selected when it is too short to reach the header. + if (window.scrollY > 0 && window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2) current = sections.at(-1); + for (const section of sections) { + if (section === current) section.link.setAttribute('aria-current', 'location'); + else section.link.removeAttribute('aria-current'); + } +} + +window.addEventListener('scroll', () => { + if (!scheduled) { scheduled = true; requestAnimationFrame(updateNavigation); } +}, { passive: true }); +window.addEventListener('resize', updateNavigation); +window.addEventListener('pageshow', updateNavigation); +backToTop.addEventListener('click', () => { + document.querySelector('.brand').focus({ preventScroll: true }); +}); +updateNavigation(); diff --git a/website/package-lock.json b/website/package-lock.json new file mode 100644 index 0000000..a6d3197 --- /dev/null +++ b/website/package-lock.json @@ -0,0 +1,558 @@ +{ + "name": "querybuilder4delphi-website", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "querybuilder4delphi-website", + "dependencies": { + "github-slugger": "^2.0.0", + "highlight.js": "^11.12.0", + "marked": "^18.1.2", + "node-sql-parser": "^5.4.0" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/pegjs": { + "version": "0.10.6", + "resolved": "https://registry.npmjs.org/@types/pegjs/-/pegjs-0.10.6.tgz", + "integrity": "sha512-eLYXDbZWXh2uxf+w8sXS8d6KSoXTswfps6fvCUuVAGN8eRpfe7h9eSRydxiSJvo9Bf+GzifsDOr9TMQlmJdmkw==", + "license": "MIT" + }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/github-slugger": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/github-slugger/-/github-slugger-2.0.0.tgz", + "integrity": "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==", + "license": "ISC" + }, + "node_modules/highlight.js": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz", + "integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/marked": { + "version": "18.1.2", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.1.2.tgz", + "integrity": "sha512-DfOnvLAQ6WYeWxWO1u4RyFOeqyHup6dks5PPqnoFiooU7ipRvidO/2j8plhAHIiZg574E9ZlzSjUiPMLAzFkgg==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/node-sql-parser": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/node-sql-parser/-/node-sql-parser-5.4.0.tgz", + "integrity": "sha512-jVe6Z61gPcPjCElPZ6j8llB3wnqGcuQzefim1ERsqIakxnEy5JlzV7XKdO1KmacRG5TKwPc4vJTgSRQ0LfkbFw==", + "license": "Apache-2.0", + "dependencies": { + "@types/pegjs": "^0.10.0", + "big-integer": "^1.6.48" + }, + "engines": { + "node": ">=8" + } + } + } +} diff --git a/website/package.json b/website/package.json new file mode 100644 index 0000000..976a0f6 --- /dev/null +++ b/website/package.json @@ -0,0 +1,20 @@ +{ + "name": "querybuilder4delphi-website", + "private": true, + "type": "module", + "scripts": { + "build": "node build.mjs", + "test": "node --test test/converter.test.mjs", + "test:site": "node --test test/site.test.mjs", + "preview": "node preview.mjs" + }, + "dependencies": { + "github-slugger": "^2.0.0", + "highlight.js": "^11.12.0", + "marked": "^18.1.2", + "node-sql-parser": "^5.4.0" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } +} diff --git a/website/preview.mjs b/website/preview.mjs new file mode 100644 index 0000000..fa56af5 --- /dev/null +++ b/website/preview.mjs @@ -0,0 +1,15 @@ +import http from 'node:http'; +import { readFile, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'dist'); +const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.svg': 'image/svg+xml' }; +http.createServer(async (req, res) => { + try { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + const file = path.resolve(root, '.' + pathname + (pathname.endsWith('/') ? 'index.html' : '')); + if (!file.startsWith(root + path.sep) || !(await stat(file)).isFile()) throw new Error('Not found'); + res.setHeader('Content-Type', `${types[path.extname(file)] || 'application/octet-stream'}; charset=utf-8`); + res.end(await readFile(file)); + } catch { res.writeHead(404); res.end('Not found'); } +}).listen(4173, '127.0.0.1', () => console.log('Local: http://127.0.0.1:4173')); diff --git a/website/style.css b/website/style.css new file mode 100644 index 0000000..c7b50d4 --- /dev/null +++ b/website/style.css @@ -0,0 +1,68 @@ +@import url('./highlight.css'); +:root{color-scheme:dark;--bg:#111714;--panel:#18201b;--line:#303d33;--text:#e5ece5;--muted:#a0b2a3;--accent:#b3ef91;font-family:Inter,Segoe UI,Arial,sans-serif;font-size:16px;line-height:1.65}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}a{color:var(--accent);text-underline-offset:4px}a:hover{color:#d5ffc1}header{height:82px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 38px;gap:20px}header>a:last-child{font-size:.9rem;color:var(--muted)}.brand{display:flex;align-items:center;color:var(--text);text-decoration:none;font-size:1.12rem;font-weight:650;letter-spacing:-.4px}.logo{background:var(--accent);color:#172317;display:inline-flex;align-items:center;justify-content:center;width:39px;height:39px;border-radius:9px;margin-right:13px;font-family:monospace;font-size:27px}.logo span{font-size:24px}.muted{color:var(--muted);font-weight:400}.layout{display:grid;grid-template-columns:245px minmax(0,1fr) 190px;max-width:1700px;margin:auto}.sidebar{padding:40px 24px;border-right:1px solid var(--line)}.sidebar nav{display:flex;flex-direction:column;gap:5px}.sidebar nav a{color:var(--muted);padding:8px 12px;border-radius:6px;text-decoration:none;font-size:.9rem}.sidebar nav a:hover,.sidebar nav a[aria-current]{background:#263629;color:var(--accent)}.eyebrow{font-size:.69rem;letter-spacing:1.8px;color:var(--muted);font-weight:700}.sidebar .eyebrow{margin-left:12px}.sidebar-note{font-size:.8rem;line-height:1.8;color:var(--text);margin:45px 12px 0;padding-top:20px;border-top:1px solid var(--line)}.sidebar-note span{color:var(--muted)}main{min-width:0;padding:42px 48px 24px}h1{font-size:2.8rem;line-height:1.15;letter-spacing:-1.5px;font-weight:650;margin:10px 0 28px}h2{font-size:1.65rem;letter-spacing:-.5px;margin:2.3rem 0 1rem}h3{margin:1.8rem 0 .7rem}h1,h2,h3,h4{scroll-margin-top:24px}p{margin:0 0 1.1rem}.documentation{max-width:1050px}.documentation h1{font-size:2.5rem}.documentation p,.documentation li{color:#c1cec2}.documentation strong{color:var(--text)}.documentation li{margin:.4rem 0}.documentation img{max-width:100%}.documentation table{display:block;overflow:auto;border-collapse:collapse;font-size:.9rem;margin:24px 0}.documentation th,.documentation td{padding:10px 14px;border:1px solid var(--line);text-align:left}.documentation th{background:var(--panel)}code,textarea{font-family:Consolas,SFMono-Regular,monospace;font-size:.86rem}p code,li code,td code{background:#263129;padding:2px 5px;border-radius:4px;color:#ceeabb}.code-block{border:1px solid var(--line);border-radius:8px;overflow:hidden;margin:20px 0;background:#141c17}.code-language{display:block;padding:7px 16px;border-bottom:1px solid var(--line);font-size:.7rem;letter-spacing:.5px;color:var(--muted)}pre{padding:17px 20px;overflow:auto;line-height:1.65;margin:0}pre .hljs{background:transparent}blockquote{border-left:3px solid var(--accent);padding-left:20px;margin-left:0}.anchor{opacity:0;font-size:.8em;margin-left:10px;text-decoration:none}h1:hover .anchor,h2:hover .anchor,h3:hover .anchor,.anchor:focus{opacity:1}.toc{padding:46px 20px 20px 0}.toc nav{display:flex;flex-direction:column;gap:10px}.toc a{font-size:.76rem;text-decoration:none;color:var(--muted)}footer{border-top:1px solid var(--line);margin-top:54px;padding:22px 0;color:var(--muted);font-size:.75rem}footer a{color:var(--muted)}.converter-page{grid-column:2/4;padding-right:40px}.converter-page h1{font-size:clamp(2.5rem,4vw,4.25rem);margin:16px 0 20px}.accent{color:var(--accent)}.lead{max-width:700px;color:var(--muted);font-size:1.05rem}.toolbar{display:flex;flex-wrap:wrap;align-items:end;gap:16px;margin:32px 0 20px}.toolbar label{display:flex;flex-direction:column;gap:6px;font-size:.77rem;color:var(--muted)}select,button{font:inherit;border:1px solid var(--line);border-radius:6px;color:var(--text);background:var(--panel);padding:9px 14px;font-size:.85rem}select{min-width:165px}button{cursor:pointer}button:hover{border-color:var(--accent)}button:disabled{opacity:.45;cursor:default}button:focus-visible,select:focus-visible,a:focus-visible,textarea:focus-visible{outline:2px solid var(--accent);outline-offset:3px}.editors{display:grid;grid-template-columns:1fr 1fr;gap:18px}.editor-panel{border:1px solid var(--line);border-radius:9px;overflow:hidden;background:#141c17;min-width:0}.panel-heading{height:58px;display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--line);font-size:.7rem;color:var(--muted);gap:12px}.panel-heading strong{font-size:.83rem;color:var(--text);margin-left:9px;font-weight:500}.panel-heading button{font-size:.72rem;padding:4px 9px}textarea{display:block;resize:vertical;min-height:390px;width:100%;border:0;border-radius:0;background:transparent;color:#d6ebcd;padding:20px;line-height:1.8;tab-size:2}#delphi{color:#becddd}.convert-actions{display:flex;align-items:center;gap:20px;margin:20px 0 34px}.convert-actions p{margin:0;font-size:.83rem;color:var(--muted);overflow-wrap:anywhere}.primary{background:var(--accent);color:#14220f;font-weight:650;border-color:var(--accent);white-space:nowrap}.primary span{margin-left:20px}.convert-actions .error{color:#ffa89a}.support{border-top:1px solid var(--line);padding-top:24px;max-width:960px}.support h2{font-size:1.2rem;margin:0 0 12px}.support p{color:var(--muted);font-size:.85rem}.skip{position:absolute;top:-60px;left:12px;background:var(--accent);color:#111;padding:8px;z-index:2}.skip:focus{top:10px}@media(min-width:1500px){textarea{min-height:450px}}@media(max-width:1150px){.layout{grid-template-columns:210px minmax(0,1fr)}.toc{display:none}.converter-page{grid-column:2}main{padding:32px}.sidebar{padding:28px 15px}.editors{grid-template-columns:1fr}textarea{min-height:280px}}@media(max-width:680px){header{height:70px;padding:0 18px}.brand{font-size:.95rem}.logo{width:30px;height:32px;font-size:23px;margin-right:8px}.layout{display:block}.sidebar{border-right:0;border-bottom:1px solid var(--line);padding:14px 18px}.sidebar .eyebrow,.sidebar-note{display:none}.sidebar nav{flex-direction:row;overflow:auto}.sidebar nav a{white-space:nowrap;font-size:.8rem;padding:6px 10px}main,.converter-page{padding:30px 20px 12px}h1,.documentation h1{font-size:2rem}.convert-actions{align-items:start;flex-direction:column;gap:12px}.toolbar{gap:10px}.toolbar label{flex:1}.toolbar select{width:100%;min-width:120px}.documentation ul{padding-left:22px}pre{padding:14px}.anchor{opacity:1}} + +/* Keep orientation while reading long guides. */ +:root { --header-height: 82px; --scroll-offset: 106px; } +html { scroll-behavior: smooth; scroll-padding-top: var(--scroll-offset); } +header { + position: sticky; + top: 0; + z-index: 10; + background: rgb(17 23 20 / 88%); + backdrop-filter: blur(16px); + box-shadow: 0 6px 24px rgb(0 0 0 / 8%); +} +.sidebar, .toc { + position: sticky; + top: var(--header-height); + align-self: start; + max-height: calc(100dvh - var(--header-height)); + overflow-y: auto; + scrollbar-width: thin; + scrollbar-color: var(--line) transparent; +} +.sidebar { min-height: calc(100dvh - var(--header-height)); } +.sidebar nav a, .toc a, button, .back-to-top { + transition: background-color 160ms ease, color 160ms ease, border-color 160ms ease, box-shadow 160ms ease; +} +.toc nav { gap: 3px; border-left: 1px solid var(--line); } +.toc a { padding: 7px 10px 7px 14px; border-left: 2px solid transparent; margin-left: -1px; border-radius: 0 5px 5px 0; } +.toc a:hover { background: rgb(179 239 145 / 5%); color: var(--text); } +.toc a[aria-current="location"] { color: var(--accent); border-left-color: var(--accent); background: rgb(179 239 145 / 7%); } +main { animation: page-arrive 260ms ease-out both; } +.documentation :is(h1,h2,h3,h4):target { animation: section-arrive 900ms ease-out; border-radius: 6px; } +.back-to-top { + position: fixed; + right: 28px; + bottom: 24px; + z-index: 12; + display: inline-flex; + align-items: center; + gap: 10px; + padding: 10px 16px; + border: 1px solid #4d6348; + border-radius: 999px; + background: rgb(30 44 32 / 95%); + backdrop-filter: blur(12px); + box-shadow: 0 8px 28px rgb(0 0 0 / 25%); + color: var(--accent); + text-decoration: none; + font-size: .8rem; + animation: page-arrive 180ms ease-out; +} +.back-to-top[hidden] { display: none; } +.back-to-top span { font-size: 1.1rem; line-height: 1; } +.back-to-top:hover { background: #30452d; border-color: var(--accent); box-shadow: 0 8px 28px rgb(0 0 0 / 35%); } +.skip { position: fixed; z-index: 20; } +@keyframes page-arrive { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } } +@keyframes section-arrive { from { background: rgb(179 239 145 / 16%); box-shadow: 0 0 0 8px rgb(179 239 145 / 8%); } to { background: transparent; box-shadow: 0 0 0 8px transparent; } } +@media(max-width:680px) { + :root { --header-height: 70px; --scroll-offset: 150px; } + .sidebar { min-height: 0; max-height: none; overflow: visible; z-index: 9; background: rgb(17 23 20 / 96%); backdrop-filter: blur(12px); } + .back-to-top { right: 18px; bottom: 18px; padding: 9px 13px; } +} +@media(prefers-reduced-motion:reduce) { + html { scroll-behavior: auto; } + main, .documentation :is(h1,h2,h3,h4):target, .back-to-top { animation: none; } + .sidebar nav a, .toc a, button, .back-to-top { transition: none; } +} diff --git a/website/test/converter.test.mjs b/website/test/converter.test.mjs new file mode 100644 index 0000000..2e02c7f --- /dev/null +++ b/website/test/converter.test.mjs @@ -0,0 +1,123 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { convert, delphiString } from '../converter.mjs'; + +for (const dialect of ['MySQL', 'PostgreSQL', 'TransactSQL', 'SQLite']) { + test(`${dialect}: basic query and aliases`, async () => { + const code = await convert('SELECT b.Id, b.Title AS BookTitle FROM Books b WHERE b.AuthorId = 42 ORDER BY b.Title DESC', dialect); + const folded = dialect === 'PostgreSQL'; + assert.ok(code.includes(`TQuery.Create('${folded ? 'books' : 'Books'} as b')`)); + assert.ok(code.includes(folded ? "'b.title as booktitle'" : "'b.Title as BookTitle'")); + assert.ok(code.includes(folded ? ".Where('b.authorid', '=', 42)" : ".Where('b.AuthorId', '=', 42)")); + assert.match(code, /\.OrderByDesc\(/); + }); + test(`${dialect}: standard string escaping and NULL`, async () => { + const code = await convert("SELECT * FROM Books WHERE Title = 'O''Reilly' AND DeletedAt IS NOT NULL", dialect); + assert.match(code, /, '=', 'O''Reilly'\)/); + assert.match(code, /\.WhereNotNull\(/); + assert.match(code, /\.Select\(\['\*'\]\)/); + }); + test(`${dialect}: distinct, grouping and HAVING`, async () => { + const code = await convert('SELECT DISTINCT AuthorId FROM Books GROUP BY AuthorId HAVING AuthorId > 2', dialect); + assert.match(code, /\.Distinct/); + assert.match(code, /\.GroupBy\(/); + assert.match(code, /\.Having\(/); + }); + test(`${dialect}: joins use column arguments in library order`, async () => { + const code = await convert('SELECT b.Id FROM Books b LEFT JOIN Authors a ON a.Id = b.AuthorId', dialect); + assert.ok(code.includes(dialect === 'PostgreSQL' ? ".LeftJoin('authors as a', 'a.id', 'b.authorid', '=')" : ".LeftJoin('Authors as a', 'a.Id', 'b.AuthorId', '=')")); + }); + test(`${dialect}: reject unions, subqueries and aggregates`, async () => { + for (const query of ['SELECT Id FROM Books UNION SELECT Id FROM Authors', 'SELECT COUNT(*) FROM Books', 'SELECT Id FROM Books WHERE Id IN (SELECT Id FROM Authors)', 'SELECT * FROM (SELECT Id FROM Books) b']) { + await assert.rejects(convert(query, dialect), /not supported|Cannot parse/); + } + }); +} +test('keeps mixed AND/OR precedence through nested callbacks', async () => { + const code = await convert('SELECT Id FROM Books WHERE (A = 1 OR B = 2) AND (C = 3 OR D = 4)'); + assert.equal((code.match(/function\(Q: IQuery\)/g) || []).length, 3); + assert.match(code, /\.Where\('A', '=', 1\)\n\s+\.OrWhere\('B', '=', 2\)/); + assert.match(code, /\.Where\('C', '=', 3\)\n\s+\.OrWhere\('D', '=', 4\)/); +}); +test('IN, BETWEEN, LIKE and column comparisons', async () => { + const code = await convert("SELECT Id FROM Books WHERE Id NOT IN (1, 2) AND Price BETWEEN 10 AND 20 AND Title LIKE 'Delphi%' AND A >= B"); + assert.match(code, /\.WhereNotIn\('Id', \[1, 2\]\)/); + assert.match(code, /\.WhereBetween\('Price', 10, 20\)/); + assert.match(code, /\.WhereStarts\('Title', 'Delphi'\)/); + assert.match(code, /\.WhereColumns\('A', '>=', 'B'\)/); +}); +for (const dialect of ['MySQL', 'PostgreSQL', 'TransactSQL', 'SQLite']) { + test(`${dialect}: LIKE uses the matching fluent string helper`, async () => { + for (const [pattern, method, value] of [ + ['foo%', 'Starts', 'foo'], ['%foo', 'Ends', 'foo'], ['%foo%', 'Contains', 'foo'], + ['foo', 'Like', 'foo'], ['f%oo%', 'Like', 'f%oo%'], ['foo_%', 'Like', 'foo_%'], + ['[ab]%', 'Like', '[ab]%'], ['%', 'Like', '%'], ['%%', 'Like', '%%'], ['', 'Like', ''], + ]) { + for (const negated of [false, true]) { + const code = await convert(`SELECT * FROM test WHERE a ${negated ? 'NOT ' : ''}LIKE '${pattern}'`, dialect); + assert.ok(code.includes(`.Where${negated ? 'Not' : ''}${method}('a', '${value}')`), code); + } + } + }); +} +test('LIKE helpers preserve OR and HAVING context', async () => { + const code = await convert("SELECT a FROM test WHERE a LIKE 'foo%' OR a NOT LIKE '%bar%' GROUP BY a HAVING a LIKE '%end'"); + assert.match(code, /\.WhereStarts\('a', 'foo'\)/); + assert.match(code, /\.OrWhereNotContains\('a', 'bar'\)/); + assert.match(code, /\.HavingEnds\('a', 'end'\)/); +}); +test('dialect paging', async () => { + for (const dialect of ['MySQL', 'PostgreSQL', 'SQLite']) { + assert.match(await convert('SELECT Id FROM Books ORDER BY Id LIMIT 20 OFFSET 40', dialect), /\.Limit\(20\)\n\s+\.Offset\(40\)/); + } + assert.match(await convert('SELECT Id FROM Books LIMIT 40,20'), /\.Limit\(20\)\n\s+\.Offset\(40\)/); + assert.match(await convert('SELECT TOP 20 Id FROM Books', 'TransactSQL'), /\.Limit\(20\)/); + assert.match(await convert('SELECT Id FROM Books ORDER BY Id OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY', 'TransactSQL'), /\.Limit\(20\)\n\s+\.Offset\(40\)/); +}); +test('PostgreSQL quoted identifiers retain case', async () => { + assert.match(await convert('SELECT "Id" FROM "Books" WHERE "Title" = \'ABC\'', 'PostgreSQL'), /TQuery.Create\('Books'\)[\s\S]*\.Select\(\['Id'\]\)[\s\S]*\.Where\('Title', '=', 'ABC'\)/); +}); +test('Delphi strings encode controls and quotes', () => { + assert.equal(delphiString("O'Reilly\nline\r\t"), "'O''Reilly'#10'line'#13#9"); + assert.equal(delphiString(''), "''"); +}); +test('literal contents survive parser escape rules without double decoding', async () => { + for (const dialect of ['PostgreSQL', 'TransactSQL', 'SQLite']) { + assert.ok((await convert(String.raw`SELECT * FROM Books WHERE Title = 'a\nb'`, dialect)).includes(String.raw`'a\nb'`)); + assert.ok((await convert("SELECT * FROM Books WHERE Title = 'O''''Reilly'", dialect)).includes("'O''''Reilly'")); + assert.ok((await convert("SELECT * FROM Books WHERE Title = 'line\nnext'", dialect)).includes("'line'#10'next'")); + } +}); +test('large signed integer literals use an explicit Int64', async () => { + assert.match(await convert('SELECT Id FROM Books WHERE Id = 3000000000'), /Int64\(3000000000\)/); +}); +test('reject statements and clauses that would otherwise silently lose meaning', async () => { + for (const query of [ + 'DELETE FROM Books', 'SELECT Id FROM Books; SELECT Id FROM Authors', + 'SELECT SQL_CALC_FOUND_ROWS Id FROM Books', 'SELECT Id INTO Other FROM Books', + 'SELECT Id FROM Books FOR UPDATE', 'SELECT Id FROM Books b, Authors a', + 'SELECT b.Id FROM Books b JOIN Authors a ON a.Id=b.AuthorId AND a.Id>0', + 'SELECT Id FROM Books WHERE Id = NULL', 'SELECT Id FROM Books WHERE Id = ?', + 'SELECT Id FROM Books ORDER BY Id + 1', 'SELECT Id FROM Books GROUP BY Id WITH ROLLUP', + 'SELECT Id FROM Books WHERE Id = 9007199254740993', + 'SELECT `odd.column` FROM Books', 'SELECT * FROM Books LIMIT -1', + 'SELECT * FROM Books LIMIT 0', 'SELECT /*! DISTINCT */ Id FROM Books', + 'SELECT Id FROM Books WHERE Id = 100000000000000.000001', + 'SELECT Id FROM Books WHERE Id = 1e-324', + String.raw`SELECT * FROM Books WHERE Title = 'a\nb'`, + ]) await assert.rejects(convert(query), /not supported|Cannot parse/, query); + await assert.rejects(convert('SELECT TOP 10 PERCENT Id FROM Books', 'TransactSQL'), /not supported/); + await assert.rejects(convert('SELECT TOP 0 Id FROM Books', 'TransactSQL'), /not supported/); + await assert.rejects(convert("SELECT * FROM Books WHERE Title = E'abc'", 'PostgreSQL'), /not supported/); + await assert.rejects(convert('SELECT DISTINCT ON (Id) Id FROM Books', 'PostgreSQL'), /not supported/); + await assert.rejects(convert(''), /Enter a SELECT/); +}); +test('generated fluent calls exist in the Delphi interface', async () => { + const api = await readFile(new URL('../../src/QueryBuilder4Delphi.Query.Core.pas', import.meta.url), 'utf8'); + const code = await convert("SELECT DISTINCT b.Id FROM Books b RIGHT JOIN Authors a ON b.AuthorId=a.Id WHERE b.Price NOT BETWEEN 1 AND 2 OR b.Title NOT LIKE 'A%' GROUP BY b.Id HAVING b.Id IN (1,2) ORDER BY b.Id DESC LIMIT 10 OFFSET 5"); + for (const [, method] of code.matchAll(/\.(\w+)(?:\(|\n)/g)) { + if (method === 'Create') continue; + assert.match(api, new RegExp(`function ${method}\\b`, 'i'), method); + } +}); diff --git a/website/test/site.test.mjs b/website/test/site.test.mjs new file mode 100644 index 0000000..eed0878 --- /dev/null +++ b/website/test/site.test.mjs @@ -0,0 +1,25 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { access, readFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../dist'); +test('built documentation links and anchors resolve under a project subpath', async () => { + const files = ['index.html', 'CHANGELOG.html', 'converter.html', ...(await readdir(path.join(root, 'docs'))).filter(f => f.endsWith('.html')).map(f => `docs/${f}`)]; + for (const file of files) { + const html = await readFile(path.join(root, file), 'utf8'); + assert.match(html, /
Date: Sat, 31 Oct 2026 20:06:00 +0100 Subject: [PATCH 2/3] Harden SQL conversion and add Delphi smoke validation --- .github/workflows/pages.yml | 2 + docs/WEBSITE.md | 99 +++++++++++++++++- tools/test_converter_smoke.ps1 | 49 +++++++++ website/app.mjs | 48 ++++----- website/build.mjs | 2 +- website/conversion-state.mjs | 28 +++++ website/converter.html | 2 +- website/converter.mjs | 71 +++++++------ website/generate-smoke.mjs | 137 +++++++++++++++++++++++++ website/numbers.mjs | 42 ++++++++ website/package.json | 3 +- website/smoke-cases.mjs | 15 +++ website/test/conversion-state.test.mjs | 76 ++++++++++++++ website/test/converter.test.mjs | 4 +- website/test/delphi-smoke.test.mjs | 63 ++++++++++++ website/test/numbers.test.mjs | 71 +++++++++++++ 16 files changed, 645 insertions(+), 67 deletions(-) create mode 100644 tools/test_converter_smoke.ps1 create mode 100644 website/conversion-state.mjs create mode 100644 website/generate-smoke.mjs create mode 100644 website/numbers.mjs create mode 100644 website/smoke-cases.mjs create mode 100644 website/test/conversion-state.test.mjs create mode 100644 website/test/delphi-smoke.test.mjs create mode 100644 website/test/numbers.test.mjs diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index b705fd0..7562ae7 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -8,6 +8,7 @@ on: - 'CHANGELOG.md' - 'docs/**' - 'src/**' + - 'test/QueryBuilder.Tests.dproj' - 'website/**' - '.github/workflows/pages.yml' pull_request: @@ -16,6 +17,7 @@ on: - 'CHANGELOG.md' - 'docs/**' - 'src/**' + - 'test/QueryBuilder.Tests.dproj' - 'website/**' - '.github/workflows/pages.yml' workflow_dispatch: diff --git a/docs/WEBSITE.md b/docs/WEBSITE.md index 8c8f56f..790d7c6 100644 --- a/docs/WEBSITE.md +++ b/docs/WEBSITE.md @@ -88,17 +88,108 @@ JOIN predicates, placeholders, unusual identifiers, window clauses, locking clauses, DISTINCT ON and TOP PERCENT/WITH TIES. MySQL backslash string escapes are rejected because they depend on SQL mode. Use SQL-standard doubled quotes. Identifiers currently use ASCII letters, digits, underscore and dollar signs, -and cannot begin with a digit. Numeric literals are limited to 15 significant -digits and JavaScript's safe integer range. Paging counts must fit a Delphi -Integer. Zero row limits are rejected because the library's `Limit(0)` means +and cannot begin with a digit. Zero row limits are rejected because the library's `Limit(0)` means unlimited. SQL dialects and database collations can still affect comparisons; review generated code against your application's schema and dialect. +### Numeric values and SQL types + +The converter saves numeric tokens as original text before parsing SQL. Only +small placeholder integers enter the JavaScript SQL parser; user values never +pass through JavaScript floating point. + +- Integer literals use exact `BigInt` range checks. Delphi `Integer` is used + within its signed 32-bit range, and explicit `Int64(...)` outside it, up to + `9223372036854775807`. Negative type boundaries use `Low(Integer)` and + `Low(Int64)` so their Delphi types are explicit. Integers + outside signed 64-bit range are rejected, including unsigned-only values. +- Ordinary decimals generate natural Delphi literals: `19.99` stays `19.99`, + `.125` becomes `0.125`, `0001.2300` becomes `1.23`, and `1.` or `1.000` + becomes `1.0`. The decimal point retains floating-point intent for + integer-valued decimals. No BCD machinery, wrappers or extra imports are + generated. The compiler resolves the natural literal through TValue's + standard Double/Extended conversions; binding type can vary by platform. +- The default decimal policy accepts at most 15 significant digits, ignoring + leading and insignificant trailing zeros, and excludes overflow and + subnormal values outside the normal IEEE Double range. Range checks compare + the original decimal against the exact bounds using integer arithmetic; + JavaScript does not parse or round the decimal. These deliberately + conservative limits apply even if Win32 Extended could hold more digits. + High-precision/out-of-range values are rejected with a manual-type-selection + hint, rather than truncating the input. Scientific notation remains unsupported. +- Paging requires integer tokens: counts fit signed 32-bit `Integer`, and + offsets fit non-negative signed `Int64`. Fractional or scientific paging + literals are rejected even when their mathematical value is an integer. + +The converter prioritizes readable Delphi code while avoiding known unsafe +conversions. **Binary floating point is approximate and does not guarantee +exact SQL DECIMAL semantics.** Original decimal digits reach the Delphi +compiler without JavaScript reformatting; the compiler then applies ordinary +floating-point rounding. Insignificant trailing zeros and SQL decimal scale +are not preserved. Exact parameter types cannot be inferred without schema +and server information. Choose an appropriate Delphi type manually when +needed, such as Currency or TBcd for exact decimal parameters, or explicit +`TValue.From(...)` when a stable Double binding type is required. +There is no automatic BCD mode. Database/provider coercions and limits still +apply; inspect parameterized `Compile.Sql` and its bindings for your application. + ## Validation `npm test` checks conversion across all four dialects, aliases and JOIN argument order, condition grouping, string escaping, NULL handling, paging, rejected -constructs, and emitted method names against the Delphi interface. +constructs, emitted method names against the Delphi interface, exact numeric +boundaries, generated smoke fixtures and overlapping asynchronous conversions. `npm run test:site`, after building, checks local links, heading anchors, assets and compatibility with a project URL subpath. Delphi compilation is a separate check and requires an available Delphi compiler. + +### Generated Delphi compilation smoke tests + +From the repository root, run: + +```powershell +./tools/test_converter_smoke.ps1 -Platform Both +``` + +This regenerates four console projects under `build/converter-smoke/` through +the production converter, then compiles and executes them using Delphi's +`dcc32` and `dcc64`. Supply `-BdsRoot` if the compiler is not on PATH. It covers +basic SELECT/WHERE, joins and aliases, nested anonymous callbacks, IN/BETWEEN/ +LIKE/NULL, GROUP BY/HAVING, ordering, paging, integer boundaries and ordinary floating-point +bindings for every input dialect. Runtime assertions check SQL generation, +binding counts, Integer/Int64 types and values, and Double/Extended binding +types and approximate values. The floating-point check prints the actual +binding type and uses a relative tolerance of 1E-14; it does not assert exact +decimal arithmetic or a specific platform-dependent real-literal overload. +No database connection or FireDAC is needed for these checks. + +The fixtures are generated from `website/smoke-cases.mjs`, not copied examples. +To generate them without compiling, run `npm run smoke:generate` in `website/`. +The generated files are ignored build artifacts. JavaScript tests exercise the +generation on CI; the GitHub Pages workflow does not require Delphi and does +not claim to validate Delphi compilation. + +With Community Edition, open each generated `.dproj` in the Delphi IDE and +build for Windows 32-bit and Windows 64-bit. + +The executables are written to the `Win32/` and `Win64/` subdirectories of +`build/converter-smoke/`. Project files derive from the repository's working +`test/QueryBuilder.Tests.dproj`, retaining its Base configuration groups, +sanitized project name, IDE metadata and target/UserTools imports. Only project +identity, relative paths and test-specific unit references are adapted. Compiler +options (`DCC_*`) are placed in the conditional Base property group: Delphi's +IDE needs this configuration scope to resolve the executable when pressing F9, +even though MSBuild also accepts unconditional compiler options. Generated +sources and project files use Windows CRLF line endings. No +debugger host-application override is used for these console executables. +Reload the project in the IDE after regenerating it. Then run: + +```powershell +./tools/test_converter_smoke.ps1 -Platform Both -TestsOnly +``` + +This verifies that the fixture sources still match current converter output +and refuses executables older than their source or the library units. A missing +executable, rejected compilation, or failed runtime assertion fails the command. +When the installed license rejects command-line compilation, generating fixtures +and passing JavaScript checks alone is **not** proof of Delphi compilation. diff --git a/tools/test_converter_smoke.ps1 b/tools/test_converter_smoke.ps1 new file mode 100644 index 0000000..331894a --- /dev/null +++ b/tools/test_converter_smoke.ps1 @@ -0,0 +1,49 @@ +param( + [ValidateSet('Win32', 'Win64', 'Both')][string]$Platform = 'Both', + [string]$BdsRoot = $env:BDS, + [switch]$TestsOnly +) +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$generator = Join-Path $repoRoot 'website\generate-smoke.mjs' +if ($TestsOnly) { & node $generator --check } else { & node $generator } +if ($LASTEXITCODE -ne 0) { throw 'Smoke fixture generation/verification failed.' } +$fixtureRoot = Join-Path $repoRoot 'build\converter-smoke' +if (-not $BdsRoot -and -not $TestsOnly) { + $BdsRoot = Split-Path -Parent (Split-Path -Parent (Get-Command dcc32.exe -ErrorAction Stop).Source) +} +$platforms = if ($Platform -eq 'Both') { @('Win32', 'Win64') } else { @($Platform) } +$failures = @() +$libraryTimestamp = (Get-ChildItem -LiteralPath (Join-Path $repoRoot 'src') -Filter '*.pas' | Sort-Object LastWriteTime -Descending | Select-Object -First 1).LastWriteTime +foreach ($target in $platforms) { + $outDir = Join-Path $fixtureRoot $target + $dcuDir = Join-Path $outDir 'dcu' + New-Item -ItemType Directory -Force $dcuDir | Out-Null + foreach ($dialect in @('MySQL', 'PostgreSQL', 'TransactSQL', 'SQLite')) { + $project = "ConverterSmoke$dialect" + $source = Join-Path $fixtureRoot "$project.dpr" + $exe = Join-Path $outDir "$project.exe" + if (-not $TestsOnly) { + $compilerName = if ($target -eq 'Win32') { 'dcc32.exe' } else { 'dcc64.exe' } + $compiler = Join-Path $BdsRoot "bin\$compilerName" + $rtlPath = Join-Path $BdsRoot "lib\$target\release" + $started = Get-Date + & $compiler -B "-U$rtlPath;$repoRoot\src" "-I$repoRoot\src" '-NSSystem;Xml;Data;Winapi' "-E$outDir" "-NU$dcuDir" $source 2>&1 | + Tee-Object -FilePath (Join-Path $outDir "$project-build.log") + if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $exe) -or (Get-Item -LiteralPath $exe).LastWriteTime -lt $started) { + $failures += "$target/${dialect}: no successful compilation (see build log)" + continue + } + } + if (-not (Test-Path -LiteralPath $exe) -or (Get-Item -LiteralPath $exe).LastWriteTime -lt (Get-Item -LiteralPath $source).LastWriteTime -or (Get-Item -LiteralPath $exe).LastWriteTime -lt $libraryTimestamp) { + $failures += "$target/${dialect}: missing or outdated executable; rebuild in Delphi" + continue + } + & $exe 2>&1 | Tee-Object -FilePath (Join-Path $outDir "$project-tests.log") + if ($LASTEXITCODE -ne 0) { $failures += "$target/${dialect}: runtime binding assertions failed" } + } +} +if ($failures.Count) { + throw (($failures -join "`n") + "`nA Delphi edition with command-line compilation is required. With Community Edition, build all generated .dproj projects for Win32 and Win64 in the IDE, then run this script with -TestsOnly.") +} +Write-Output 'All requested generated Delphi compilation and runtime smoke checks passed.' diff --git a/website/app.mjs b/website/app.mjs index 6c49ed9..e8673e4 100644 --- a/website/app.mjs +++ b/website/app.mjs @@ -1,4 +1,5 @@ import { convert } from './converter.mjs'; +import { createConversionController } from './conversion-state.mjs'; const $ = id => document.getElementById(id); const examples = { basic: 'SELECT Id, Title\nFROM Books\nWHERE AuthorId = 42\nORDER BY Title;', @@ -6,31 +7,17 @@ const examples = { group: "SELECT Id, Title\nFROM Books\nWHERE (AuthorId = 42 OR AuthorId = 7)\n AND Price BETWEEN 10 AND 50\n AND DeletedAt IS NULL\nORDER BY Title DESC;", paging: 'SELECT Id, Title\nFROM Books\nORDER BY Title, Id\nLIMIT 20 OFFSET 40;', }; -let revision = 0; -function invalidate() { - revision++; - $('delphi').value = ''; - $('copy').disabled = true; - $('status').textContent = 'Ready to convert.'; - $('status').className = ''; -} -async function run() { - invalidate(); - const current = revision; - $('convert').disabled = true; - $('status').textContent = 'Converting…'; - try { - const code = await convert($('sql').value, $('dialect').value); - if (current !== revision) return; +const { invalidate, run } = createConversionController({ + convert, + readInput: () => ({ sql: $('sql').value, dialect: $('dialect').value }), + render: ({ busy, code, message, error }) => { + $('convert').disabled = busy; $('delphi').value = code; - $('copy').disabled = false; - $('status').textContent = 'Converted. Values use the library’s parameterized API.'; - } catch (error) { - if (current !== revision) return; - $('status').textContent = error.message; - $('status').className = 'error'; - } finally { $('convert').disabled = false; } -} + $('copy').disabled = busy || !code; + $('status').textContent = message; + $('status').className = error ? 'error' : ''; + }, +}); $('convert').addEventListener('click', run); $('sql').addEventListener('input', invalidate); $('dialect').addEventListener('change', invalidate); @@ -40,8 +27,17 @@ $('load-example').addEventListener('click', () => { invalidate(); }); $('copy').addEventListener('click', async () => { - try { await navigator.clipboard.writeText($('delphi').value); $('status').textContent = 'Delphi code copied.'; } - catch { $('delphi').focus(); $('delphi').select(); $('status').textContent = 'Select the output and copy it with Ctrl+C (or ⌘C).'; } + const code = $('delphi').value; + if (!code || $('copy').disabled) return; + const stillCurrent = () => $('delphi').value === code && !$('copy').disabled; + try { + await navigator.clipboard.writeText(code); + if (stillCurrent()) $('status').textContent = 'Delphi code copied.'; + } catch { + if (!stillCurrent()) return; + $('delphi').focus(); $('delphi').select(); + $('status').textContent = 'Select the output and copy it with Ctrl+C (or ⌘C).'; + } }); $('sql').addEventListener('keydown', event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); run(); } diff --git a/website/build.mjs b/website/build.mjs index 89832aa..6a2f520 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -37,7 +37,7 @@ function shell(title, body, source, toc = []) { ${escape(title)} · QueryBuilder4Delphi
QueryBuilder4DelphiGitHub ↗
-
+
${body}
${toc.length ? `` : ''}
diff --git a/website/conversion-state.mjs b/website/conversion-state.mjs new file mode 100644 index 0000000..c03e608 --- /dev/null +++ b/website/conversion-state.mjs @@ -0,0 +1,28 @@ +// Each run owns its result and loading state until input invalidates it. +export function createConversionController({ convert, readInput, render }) { + let revision = 0; + let busy = false; + function show(state) { busy = state.busy; render(state); } + function invalidate() { + revision++; + show({ busy: false, code: '', message: 'Ready to convert.', error: false }); + } + async function run() { + // The keyboard shortcut follows the same rule as the disabled button. + if (busy) return; + const current = ++revision; + const { sql, dialect } = readInput(); + show({ busy: true, code: '', message: 'Converting…', error: false }); + try { + const code = await convert(sql, dialect); + if (current !== revision) return; + show({ busy: false, code, message: 'Converted. Values use the library’s parameterized API.', error: false }); + } catch (error) { + if (current !== revision) return; + const message = typeof error?.message === 'string' && error.message ? error.message : + typeof error === 'string' && error ? error : 'Unexpected conversion error. Please check your SQL and try again.'; + show({ busy: false, code: '', message, error: true }); + } + } + return { invalidate, run }; +} diff --git a/website/converter.html b/website/converter.html index 96d9dda..d224f1b 100644 --- a/website/converter.html +++ b/website/converter.html @@ -7,5 +7,5 @@

SQL in. Delphi out.

WHERE AuthorId = 42 ORDER BY Title;

Ready to convert.

-

What can I convert?

One SELECT statement with table and column aliases, DISTINCT, INNER/LEFT/RIGHT JOIN with one column comparison, CROSS JOIN, grouped AND/OR conditions, column comparisons, LIKE, IN, BETWEEN, IS NULL, GROUP BY, simple HAVING, ORDER BY and literal paging values. SQL Server TOP and OFFSET/FETCH are also supported.

CTEs, unions, subqueries, aggregate/function expressions, complex JOIN conditions, placeholders, quoted identifiers containing spaces or punctuation, and dialect-specific extensions are rejected. No partial code or raw SQL fallback is emitted. Numbers are limited to 15 significant digits. Zero row limits and MySQL string literals with backslash escapes are rejected because their meaning cannot be preserved reliably.

The output is a complete BuildQuery: IQuery function. Compile it with your chosen TSqlDialect in Delphi; the converter does not execute SQL or run the Delphi compiler. PostgreSQL unquoted identifiers are folded to lowercase. SQL comments are not included in the output.

+

What can I convert?

One SELECT statement with table and column aliases, DISTINCT, INNER/LEFT/RIGHT JOIN with one column comparison, CROSS JOIN, grouped AND/OR conditions, column comparisons, LIKE, IN, BETWEEN, IS NULL, GROUP BY, simple HAVING, ORDER BY and literal paging values. SQL Server TOP and OFFSET/FETCH are also supported.

CTEs, unions, subqueries, aggregate/function expressions, complex JOIN conditions, placeholders, quoted identifiers containing spaces or punctuation, and dialect-specific extensions are rejected. No partial code or raw SQL fallback is emitted. Zero row limits and MySQL string literals with backslash escapes are rejected because their meaning cannot be preserved reliably.

Ordinary decimals produce natural Delphi literals such as 19.99, without BCD wrappers or extra imports. Decimals are limited to 15 significant digits (ignoring insignificant zeros) within the normal Double range; high-precision values, subnormal values and scientific notation are rejected. Binary floating-point parameters do not guarantee exact SQL DECIMAL semantics. Exact parameter types depend on your schema: choose Currency, TBcd or another Delphi type manually when needed. Signed integer values retain exact Integer/Int64 validation.

The output is a complete BuildQuery: IQuery function. Compile it with your chosen TSqlDialect in Delphi; the converter does not execute SQL or run the Delphi compiler. PostgreSQL unquoted identifiers are folded to lowercase. SQL comments are not included in the output.

diff --git a/website/converter.mjs b/website/converter.mjs index 12edf99..cb7cb93 100644 --- a/website/converter.mjs +++ b/website/converter.mjs @@ -1,4 +1,5 @@ // The parser only reads SQL. Generated code uses the library's parameterized API. +import { numericLiteral, pagingLiteral } from './numbers.mjs'; const dialects = { MySQL: () => import('node-sql-parser/build/mysql.js'), PostgreSQL: () => import('node-sql-parser/build/postgresql.js'), @@ -36,18 +37,15 @@ function table(node) { } function literal(node, literals) { if (!node) unsupported('Missing values'); + if (node.type === 'number' || node.type === 'unary_expr') { + return numericLiteral(numericText(node, literals)); + } check(node, ['type', 'value', 'loc'], 'Value'); if (['single_quote_string', 'string'].includes(node.type)) { - if (!literals.has(node.value)) unsupported('This string literal syntax'); - return delphiString(literals.get(node.value)); + if (!literals.strings.has(node.value)) unsupported('This string literal syntax'); + return delphiString(literals.strings.get(node.value)); } if (['bool', 'boolean'].includes(node.type)) return node.value ? 'True' : 'False'; - if (node.type === 'number') { - const value = Number(node.value); - if (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER || String(node.value).replace(/[^0-9]/g, '').replace(/^0+/, '').length > 15) unsupported('Numbers requiring more than 15 significant digits'); - if (Number.isInteger(value) && (value > 2147483647 || value < -2147483648)) return `Int64(${value})`; - return String(value); - } unsupported('Parameters, NULL values in lists, or non-scalar values (use literal values for conversion)'); } const comparisons = ['=', '!=', '<>', '<', '>', '<=', '>=']; @@ -81,7 +79,7 @@ function predicate(node, method = 'Where', indent = ' ', depth = 0, literals) // Validate the scalar before choosing an idiomatic string helper. These // helpers add only their boundary wildcards and do not escape the value. literal(node.right, literals); - const pattern = literals.get(node.right.value); + const pattern = literals.strings.get(node.right.value); if (typeof pattern !== 'string') unsupported('LIKE with a non-string pattern'); const simple = pattern.match(/^(%?)([^%_\\[\]]+)(%?)$/); let suffix = 'Like'; @@ -94,9 +92,21 @@ function predicate(node, method = 'Where', indent = ' ', depth = 0, literals) } return `${indent}.${method}(${col}, ${delphiString(op.toLowerCase())}, ${literal(node.right, literals)})`; } -function integer(node, max) { - if (node?.type !== 'number' || !Number.isSafeInteger(Number(node.value)) || Number(node.value) < 0 || Number(node.value) > max) unsupported('Non-literal or out-of-range paging values'); - return Number(node.value); +function numericText(node, literals) { + if (node?.type === 'unary_expr' && ['+', '-'].includes(node.operator)) { + check(node, ['type', 'operator', 'expr', 'parentheses', 'loc'], 'Signed number'); + const text = numericText(node.expr, literals); + return node.operator === '+' ? text : text.startsWith('-') ? text.slice(1) : '-' + text; + } + if (node?.type !== 'number') unsupported('Non-literal numeric values'); + check(node, ['type', 'value', 'loc'], 'Number'); + // The parser only sees small unique integer slots, never the user's numbers. + const text = literals.numbers.get(String(Math.abs(node.value))); + if (text == null) unsupported('Unrecognized numeric syntax'); + return (node.value < 0 ? '-' : '') + text; +} +function integer(node, max, literals) { + return pagingLiteral(numericText(node, literals), max); } export async function convert(sql, dialect = 'MySQL') { if (!dialects[dialect]) unsupported('This SQL dialect'); @@ -107,20 +117,19 @@ export async function convert(sql, dialect = 'MySQL') { let ast; // Preserve SQL literal values ourselves: the parser decodes backslash escapes // even in dialects where backslashes are ordinary characters. - const literals = new Map(); - sql = sql.replace(/--[^\r\n]*|#[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:\]\]|[^\]])*\]|'(?:''|[^'])*'|(?:\b\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/g, (token, offset) => { + const literals = { strings: new Map(), numbers: new Map() }; + sql = sql.replace(/--[^\r\n]*|#[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:\]\]|[^\]])*\]|'(?:''|[^'])*'|[A-Za-z_][A-Za-z0-9_$]*|(?:\b\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/g, (token, offset) => { if (dialect === 'MySQL' && token.startsWith('/*!')) unsupported('MySQL executable comments'); if (/^(?:\d|\.\d)/.test(token)) { - const significant = token.split(/[eE]/)[0].replace('.', '').replace(/^0+/, ''); - if (significant.length > 15) unsupported('Numbers requiring more than 15 significant digits'); - if (Number(token) === 0 && /[1-9]/.test(significant)) unsupported('Numbers below the supported numeric range'); - return token; + const slot = String(7000000 + literals.numbers.size); + literals.numbers.set(slot, token); + return slot; } if (!token.startsWith("'")) return token; if (offset > 0 && /[A-Za-z0-9_$]/.test(sql[offset - 1])) unsupported('Prefixed string literals'); if (dialect === 'MySQL' && token.includes('\\')) unsupported('MySQL string literals with backslash escapes (SQL mode dependent)'); - const marker = `QBD-LITERAL-${literals.size}`; - literals.set(marker, token.slice(1, -1).replaceAll("''", "'")); + const marker = `QBD-LITERAL-${literals.strings.size}`; + literals.strings.set(marker, token.slice(1, -1).replaceAll("''", "'")); return `'${marker}'`; }); // PostgreSQL folds unquoted identifiers to lowercase. Preserve quoted tokens, @@ -174,19 +183,19 @@ export async function convert(sql, dialect = 'MySQL') { if (ast.top) { check(ast.top, ['value', 'percent', 'with_ties'], 'TOP'); if (ast.top.percent || ast.top.with_ties) unsupported('TOP PERCENT/WITH TIES'); - const count = integer({ type: 'number', value: ast.top.value }, 2147483647); - if (count === 0) unsupported('TOP 0 (the library treats Limit(0) as unlimited)'); - lines.push(` .Limit(${count})`); + const count = integer({ type: 'number', value: ast.top.value }, 2147483647n, literals); + if (count.value === 0n) unsupported('TOP 0 (the library treats Limit(0) as unlimited)'); + lines.push(` .Limit(${count.code})`); } if (ast.limit?.offset || ast.limit?.fetch) { check(ast.limit, ['offset', 'fetch'], 'Paging'); if (ast.top) unsupported('TOP combined with OFFSET/FETCH'); if (ast.limit.fetch) { - const count = integer(ast.limit.fetch.value, 2147483647); - if (!count) unsupported('FETCH 0'); - lines.push(` .Limit(${count})`); + const count = integer(ast.limit.fetch.value, 2147483647n, literals); + if (count.value === 0n) unsupported('FETCH 0'); + lines.push(` .Limit(${count.code})`); } - if (ast.limit.offset) lines.push(` .Offset(${integer(ast.limit.offset.value, Number.MAX_SAFE_INTEGER)})`); + if (ast.limit.offset) lines.push(` .Offset(${integer(ast.limit.offset.value, 9223372036854775807n, literals).code})`); } else if (meaningful(ast.limit)) { check(ast.limit, ['value', 'seperator'], 'Paging'); const values = ast.limit.value; @@ -194,10 +203,10 @@ export async function convert(sql, dialect = 'MySQL') { const offsetFirst = ast.limit.seperator === ','; const count = values[offsetFirst ? 1 : 0]; const offset = values.length === 2 ? values[offsetFirst ? 0 : 1] : null; - const limit = integer(count, 2147483647); - if (limit === 0) unsupported('LIMIT 0 (the library treats Limit(0) as unlimited)'); - lines.push(` .Limit(${limit})`); - if (offset) lines.push(` .Offset(${integer(offset, Number.MAX_SAFE_INTEGER)})`); + const limit = integer(count, 2147483647n, literals); + if (limit.value === 0n) unsupported('LIMIT 0 (the library treats Limit(0) as unlimited)'); + lines.push(` .Limit(${limit.code})`); + if (offset) lines.push(` .Offset(${integer(offset, 9223372036854775807n, literals).code})`); } return `uses\n QueryBuilder4Delphi.Query.Core,\n QueryBuilder4Delphi.Query;\n\nfunction BuildQuery: IQuery;\nbegin\n${lines.join('\n')};\nend;\n`; } diff --git a/website/generate-smoke.mjs b/website/generate-smoke.mjs new file mode 100644 index 0000000..bac2451 --- /dev/null +++ b/website/generate-smoke.mjs @@ -0,0 +1,137 @@ +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { createHash } from 'node:crypto'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { convert } from './converter.mjs'; +import { smokeCases, smokeDialects } from './smoke-cases.mjs'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +export const smokeOutput = path.join(root, 'build/converter-smoke'); +export const smokeProjectTemplate = path.join(root, 'test/QueryBuilder.Tests.dproj'); +export async function generateSmokeProjects() { + const files = new Map(); + // Reuse the IDE-tested console project's complete configuration/inheritance + // structure, instead of maintaining a reduced, MSBuild-only approximation. + const projectTemplate = await readFile(smokeProjectTemplate, 'utf8'); + for (const [dialect, outputDialect] of Object.entries(smokeDialects)) { + const imports = new Set(['System.SysUtils', 'System.Rtti']); + const functions = []; + const calls = []; + for (const fixture of smokeCases) { + const sql = typeof fixture.sql === 'function' ? fixture.sql(dialect) : fixture.sql; + const code = await convert(sql, dialect); + const [uses, unitList] = code.match(/^uses\n([\s\S]*?);\n\n/); + unitList.split(',').forEach(unit => imports.add(unit.trim())); + functions.push(`// ${fixture.name}: ${sql}\n${code.slice(uses.length).replace('function BuildQuery:', `function Build${fixture.name}:`)}`); + calls.push(` S := Check('${fixture.name}', Build${fixture.name}, TSqlDialect.${outputDialect}, ${fixture.bindings});`); + for (const [index, value] of (fixture.integerValues || []).entries()) { + const isInt64 = BigInt(value) < -2147483648n || BigInt(value) > 2147483647n; + calls.push(` CheckInteger(S.Bindings[${index}], '${value}', ${isInt64 ? 'True' : 'False'});`); + } + for (const [index, value] of (fixture.decimalValues || []).entries()) { + calls.push(` CheckFloat(S.Bindings[${index}], '${value}');`); + } + } + const name = `ConverterSmoke${dialect}`; + // Stable project identity is required by the Delphi IDE, not just MSBuild. + const id = createHash('sha256').update(name).digest('hex').slice(0, 32).toUpperCase(); + const projectGuid = `{${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}}`; + files.set(`${name}.dpr`, `// Generated by website/generate-smoke.mjs. Do not edit.\nprogram ${name};\n\n{$APPTYPE CONSOLE}\n\nuses\n ${[...imports].join(',\n ')};\n\n${functions.join('\n')} +function Check(const Name: string; const Query: IQuery; + Dialect: TSqlDialect; ExpectedBindings: Integer): ISqlResult; +begin + Result := Query.Compile(Dialect); + if Trim(Result.Sql) = '' then + raise Exception.Create(Name + ': empty SQL'); + if Result.Bindings.Count <> ExpectedBindings then + raise Exception.Create(Name + ': wrong binding count'); + Writeln(Name + ': compiled SQL and checked bindings'); +end; + +procedure CheckInteger(const Value: TValue; const Expected: string; IsInt64: Boolean); +begin + if IsInt64 then + begin + if not Value.IsType then + raise Exception.Create('Expected Int64 binding'); + if IntToStr(Value.AsInt64) <> Expected then + raise Exception.Create('Int64 value changed'); + end + else + begin + if not Value.IsType then + raise Exception.Create('Expected Integer binding'); + if IntToStr(Value.AsInteger) <> Expected then + raise Exception.Create('Integer value changed'); + end; +end; + +procedure CheckFloat(const Value: TValue; const Expected: string); +var + Actual, ExpectedValue: Extended; +begin + // TValue has Double and Extended implicit conversions. Natural real literals + // may select either, depending on compiler/platform; never Integer or BCD. + if not (Value.IsType or Value.IsType) then + raise Exception.Create('Expected a Double or Extended floating-point binding'); + Actual := Value.AsExtended; + ExpectedValue := StrToFloat(Expected, TFormatSettings.Invariant); + if ExpectedValue = 0 then + begin + if Actual <> 0 then + raise Exception.Create('Expected a zero floating-point value'); + end + else if Abs(Actual / ExpectedValue - 1) > 1E-14 then + raise Exception.Create('Floating-point value exceeds the comparison tolerance'); + Writeln('Floating-point binding: ' + Value.TypeInfo.Name); +end; + +var + S: ISqlResult; +begin + try +${calls.join('\n')} + Writeln('${dialect}: ${smokeCases.length} generated functions passed'); + except + on E: Exception do + begin + Writeln(E.ClassName + ': ' + E.Message); + Halt(1); + end; + end; +end. +`); + let project = projectTemplate + .replace(/[^<]+<\/ProjectGuid>/, `${projectGuid}`) + .replaceAll('QueryBuilder.Tests', name) + .replaceAll('QueryBuilder_Tests', name) + .replace(/[^<]*<\/DCC_UnitSearchPath>/, '..\\..\\src;$(DCC_UnitSearchPath)') + .replace(/[^<]*<\/DCC_IncludePath>/, '..\\..\\src;$(DCC_IncludePath)') + .replace(/[^<]*<\/DCC_ExeOutput>/, '.\\$(Platform)') + .replace(/[^<]*<\/DCC_DcuOutput>/, '.\\$(Platform)\\dcu') + .replace(/^.* match[0]).join(''); + project = project.replace(/^.*[^<]+<\/SanitizedProjectName>\r?\n)/, `$1${compilerOptions}`); + files.set(`${name}.dproj`, project); + } + // These are Windows Delphi IDE artifacts. Avoid IDE line-ending conversion + // prompts and keep regeneration/checks identical on Windows and CI. + return new Map([...files].map(([name, source]) => [name, source.replace(/\r?\n/g, '\r\n')])); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const checkOnly = process.argv.includes('--check'); + const files = await generateSmokeProjects(); + if (!checkOnly) await mkdir(smokeOutput, { recursive: true }); + for (const [name, source] of files) { + const file = path.join(smokeOutput, name); + const current = await readFile(file, 'utf8').catch(() => null); + if (current === source) continue; + if (checkOnly) throw new Error(`Stale or missing fixture: ${file}. Run npm run smoke:generate and rebuild in Delphi.`); + await writeFile(file, source); + } + console.log(`${checkOnly ? 'Verified' : 'Generated'} ${Object.keys(smokeDialects).length} Delphi smoke projects (${smokeCases.length} functions each) in ${smokeOutput}`); +} diff --git a/website/numbers.mjs b/website/numbers.mjs new file mode 100644 index 0000000..bb327d0 --- /dev/null +++ b/website/numbers.mjs @@ -0,0 +1,42 @@ +const minInt64 = -9223372036854775808n; +const maxInt64 = 9223372036854775807n; +const reject = detail => { throw new Error(`${detail} No code was generated.`); }; + +// Original SQL text, never a JavaScript floating-point value, enters here. +export function numericLiteral(text) { + if (/e/i.test(text)) reject('Scientific notation is not supported. Use ordinary decimal notation within the supported range or choose the Delphi parameter type manually.'); + if (/^-?\d+$/.test(text)) { + const value = BigInt(text); + if (value < minInt64 || value > maxInt64) reject('Integer literal is outside the signed Delphi Int64 range. Choose an appropriate decimal or unsigned Delphi type manually.'); + if (value === minInt64) return 'Low(Int64)'; + if (value === -2147483648n) return 'Low(Integer)'; + return value < -2147483648n || value > 2147483647n ? `Int64(${value})` : String(value); + } + const decimal = text.match(/^(-?)(\d*)\.(\d*)$/); + if (!decimal || !(decimal[2] || decimal[3])) reject('Unsupported numeric literal.'); + const integral = decimal[2].replace(/^0+/, '') || '0'; + const fraction = decimal[3].replace(/0+$/, ''); + const digits = (integral + fraction).replace(/^0+/, ''); + // Standard floating-point output is approximate. Limit input precision rather + // than silently rounding a high-precision decimal down to fit the default. + if (digits.replace(/0+$/, '').length > 15) reject('Decimal literals with more than 15 significant digits require manual type selection, such as Currency or TBcd for exact decimal values.'); + if (digits) { + const order = integral !== '0' ? integral.length - 1 : -(fraction.search(/[1-9]/) + 1); + const rangeError = 'Decimal literal is outside the supported normal Double range (subnormal values are excluded). Choose the Delphi numeric type manually.'; + if (order < -308 || order > 308) reject(rangeError); + // Compare decimal rationals against IEEE Double bounds using integers only. + // This also bounds Win32 output when the compiler selects Extended. + const numerator = BigInt(digits); + const denominator = 10n ** BigInt(fraction.length); + const maxDouble = ((1n << 53n) - 1n) << 971n; + if (numerator > maxDouble * denominator || numerator * (1n << 1022n) < denominator) reject(rangeError); + } + // A decimal point keeps 1. and 1.000 in the floating-point family, not Integer. + return `${decimal[1]}${integral}.${fraction || '0'}`; +} + +export function pagingLiteral(text, max) { + if (!/^\d+$/.test(text) || BigInt(text) > max) reject('Paging requires a non-negative integer literal within the Delphi parameter range.'); + const value = BigInt(text); + return { value, code: value > 2147483647n ? `Int64(${value})` : String(value) }; +} diff --git a/website/package.json b/website/package.json index 976a0f6..b127774 100644 --- a/website/package.json +++ b/website/package.json @@ -4,7 +4,8 @@ "type": "module", "scripts": { "build": "node build.mjs", - "test": "node --test test/converter.test.mjs", + "test": "node --test test/converter.test.mjs test/numbers.test.mjs test/conversion-state.test.mjs test/delphi-smoke.test.mjs", + "smoke:generate": "node generate-smoke.mjs", "test:site": "node --test test/site.test.mjs", "preview": "node preview.mjs" }, diff --git a/website/smoke-cases.mjs b/website/smoke-cases.mjs new file mode 100644 index 0000000..e6cf8b5 --- /dev/null +++ b/website/smoke-cases.mjs @@ -0,0 +1,15 @@ +// Every fixture is regenerated through the production converter, for each dialect. +export const smokeDialects = { + MySQL: 'MySql', PostgreSQL: 'PostgreSql', TransactSQL: 'MSSql', SQLite: 'Sqlite', +}; +export const smokeCases = [ + { name: 'Basic', sql: 'SELECT Id, Title FROM Books WHERE AuthorId = 42', bindings: 1 }, + { name: 'Joins', sql: 'SELECT b.Id, b.Title, a.Name AS AuthorName FROM Books b LEFT JOIN Authors a ON a.Id = b.AuthorId WHERE b.Price >= 10', bindings: 1 }, + { name: 'Nested', sql: 'SELECT Id FROM Books WHERE (Id = 1 OR Id = 2) AND (AuthorId = 7 OR Price > 10)', bindings: 4 }, + { name: 'Predicates', sql: "SELECT Id FROM Books WHERE Id IN (1, 2) AND Price BETWEEN 10 AND 50 AND Title LIKE 'Delphi%' AND DeletedAt IS NULL", bindings: 5 }, + { name: 'Having', sql: 'SELECT AuthorId FROM Books WHERE Price > 10 GROUP BY AuthorId HAVING AuthorId IN (7, 8) AND AuthorId BETWEEN 1 AND 9', bindings: 5 }, + { name: 'Paging', sql: dialect => dialect === 'TransactSQL' ? 'SELECT Id FROM Books ORDER BY Title DESC, Id OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY' : 'SELECT Id FROM Books ORDER BY Title DESC, Id LIMIT 20 OFFSET 40', bindings: 2 }, + { name: 'IntegerBounds', sql: 'SELECT Id FROM Books WHERE Id IN (2147483647, -2147483648, 2147483648, -2147483649, 9007199254740993, 9223372036854775807, -9223372036854775808)', bindings: 7, integerValues: ['2147483647', '-2147483648', '2147483648', '-2147483649', '9007199254740993', '9223372036854775807', '-9223372036854775808'] }, + { name: 'Decimals', sql: 'SELECT Id FROM Books WHERE Price IN (0.1, 19.99, 1.2300, .125, 1., -0.000000000000000001)', bindings: 6, decimalValues: ['0.1', '19.99', '1.2300', '0.125', '1.0', '-0.000000000000000001'] }, + { name: 'Variants', sql: dialect => `SELECT b.Id FROM Books b INNER JOIN Authors a ON a.Id = b.AuthorId ${dialect === 'SQLite' ? 'LEFT JOIN Publishers p ON p.Id = b.PublisherId INNER JOIN Languages l ON l.Id = b.LanguageId' : 'RIGHT JOIN Publishers p ON p.Id = b.PublisherId CROSS JOIN Languages l'} WHERE b.Title NOT LIKE '%draft%' OR b.Title LIKE 'A_B%' GROUP BY b.Id HAVING b.Id NOT BETWEEN 1 AND 2 OR b.Id IS NOT NULL`, bindings: 4 }, +]; diff --git a/website/test/conversion-state.test.mjs b/website/test/conversion-state.test.mjs new file mode 100644 index 0000000..06c8a05 --- /dev/null +++ b/website/test/conversion-state.test.mjs @@ -0,0 +1,76 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createConversionController } from '../conversion-state.mjs'; + +function fixture() { + const pending = []; + const renders = []; + let input = { sql: 'first', dialect: 'MySQL' }; + const controller = createConversionController({ + convert: (sql, dialect) => { + const deferred = Promise.withResolvers(); + pending.push({ ...deferred, sql, dialect }); + return deferred.promise; + }, + readInput: () => input, + render: state => renders.push(state), + }); + return { controller, pending, renders, state: () => renders.at(-1), change: next => { input = { ...input, ...next }; controller.invalidate(); } }; +} +for (const rejectOlder of [false, true]) { + test(`older ${rejectOlder ? 'error' : 'success'} cannot end a newer run's loading state`, async () => { + const f = fixture(); + const first = f.controller.run(); + f.change({ sql: 'second', dialect: 'SQLite' }); + const second = f.controller.run(); + assert.deepEqual(f.pending.map(p => [p.sql, p.dialect]), [['first', 'MySQL'], ['second', 'SQLite']]); + const before = f.renders.length; + if (rejectOlder) f.pending[0].reject(new Error('stale error')); else f.pending[0].resolve('stale code'); + await first; + assert.equal(f.renders.length, before); + assert.deepEqual(f.state(), { busy: true, code: '', message: 'Converting…', error: false }); + f.pending[1].resolve('latest code'); await second; + assert.equal(f.state().code, 'latest code'); assert.equal(f.state().busy, false); + }); +} +test('latest result remains when older work settles last', async () => { + const f = fixture(); const first = f.controller.run(); + f.change({ sql: 'second' }); const second = f.controller.run(); + f.pending[1].resolve('latest'); await second; + f.pending[0].reject(new Error('older')); await first; + assert.equal(f.state().code, 'latest'); assert.equal(f.state().error, false); +}); +test('changing SQL or dialect clears output and cancels the current loading state', async () => { + for (const changed of [{ sql: 'changed' }, { dialect: 'PostgreSQL' }]) { + const f = fixture(); const first = f.controller.run(); + f.change(changed); + assert.equal(f.state().code, ''); assert.equal(f.state().busy, false); + const before = f.renders.length; + f.pending[0].resolve('obsolete'); await first; + assert.equal(f.renders.length, before); + const next = f.controller.run(); f.pending[1].resolve('new'); await next; + f.change(changed); assert.equal(f.state().code, ''); + } +}); +test('repeated shortcuts during the same run behave like a disabled Convert button', async () => { + const f = fixture(); const first = f.controller.run(); + await f.controller.run(); await f.controller.run(); + assert.equal(f.pending.length, 1); + f.pending[0].resolve('code'); await first; +}); +test('parser failures leave no output and allow a retry', async () => { + for (const error of [new Error('Parser failed'), 'Unexpected failure', null, { message: '' }]) { + const f = fixture(); const first = f.controller.run(); + f.pending[0].reject(error); await first; + assert.equal(f.state().busy, false); assert.equal(f.state().code, ''); + assert.equal(f.state().error, true); assert.ok(f.state().message); + const next = f.controller.run(); f.pending[1].resolve('recovered'); await next; + assert.equal(f.state().code, 'recovered'); assert.equal(f.state().error, false); + } +}); +test('synchronous parser exceptions also recover the controls', async () => { + let state; + const controller = createConversionController({ convert: () => { throw new Error('broken'); }, readInput: () => ({ sql: 'x', dialect: 'MySQL' }), render: value => { state = value; } }); + await controller.run(); + assert.equal(state.busy, false); assert.equal(state.error, true); assert.equal(state.message, 'broken'); +}); diff --git a/website/test/converter.test.mjs b/website/test/converter.test.mjs index 2e02c7f..fa65f99 100644 --- a/website/test/converter.test.mjs +++ b/website/test/converter.test.mjs @@ -100,13 +100,11 @@ test('reject statements and clauses that would otherwise silently lose meaning', 'SELECT b.Id FROM Books b JOIN Authors a ON a.Id=b.AuthorId AND a.Id>0', 'SELECT Id FROM Books WHERE Id = NULL', 'SELECT Id FROM Books WHERE Id = ?', 'SELECT Id FROM Books ORDER BY Id + 1', 'SELECT Id FROM Books GROUP BY Id WITH ROLLUP', - 'SELECT Id FROM Books WHERE Id = 9007199254740993', 'SELECT `odd.column` FROM Books', 'SELECT * FROM Books LIMIT -1', 'SELECT * FROM Books LIMIT 0', 'SELECT /*! DISTINCT */ Id FROM Books', - 'SELECT Id FROM Books WHERE Id = 100000000000000.000001', 'SELECT Id FROM Books WHERE Id = 1e-324', String.raw`SELECT * FROM Books WHERE Title = 'a\nb'`, - ]) await assert.rejects(convert(query), /not supported|Cannot parse/, query); + ]) await assert.rejects(convert(query), /not supported|Cannot parse|Paging requires/, query); await assert.rejects(convert('SELECT TOP 10 PERCENT Id FROM Books', 'TransactSQL'), /not supported/); await assert.rejects(convert('SELECT TOP 0 Id FROM Books', 'TransactSQL'), /not supported/); await assert.rejects(convert("SELECT * FROM Books WHERE Title = E'abc'", 'PostgreSQL'), /not supported/); diff --git a/website/test/delphi-smoke.test.mjs b/website/test/delphi-smoke.test.mjs new file mode 100644 index 0000000..52d1f11 --- /dev/null +++ b/website/test/delphi-smoke.test.mjs @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { generateSmokeProjects, smokeProjectTemplate } from '../generate-smoke.mjs'; +import { readFile } from 'node:fs/promises'; +import { smokeCases, smokeDialects } from '../smoke-cases.mjs'; +test('Delphi smoke fixtures are regenerated from every supported dialect and feature case', async () => { + const files = await generateSmokeProjects(); + assert.equal(files.size, Object.keys(smokeDialects).length * 2); + for (const dialect of Object.keys(smokeDialects)) { + const program = files.get(`ConverterSmoke${dialect}.dpr`); + for (const fixture of smokeCases) { + assert.ok(program.includes(`function Build${fixture.name}: IQuery;`), `${dialect}: ${fixture.name}`); + assert.ok(program.includes(`S := Check('${fixture.name}', Build${fixture.name}`)); + } + for (const check of ['CheckInteger(S.Bindings[4]', "CheckFloat(S.Bindings[1], '19.99')", 'function(Q: IQuery): IQuery', 'Value.IsType or Value.IsType']) assert.ok(program.includes(check), `${dialect}: ${check}`); + for (const bcd of ['Data.FmtBcd', 'StrToBcd', 'TValue.From']) assert.ok(!program.includes(bcd)); + assert.ok(program.includes('0.1, 19.99, 1.23, 0.125, 1.0, -0.000000000000000001')); + assert.ok(!program.includes('function BuildQuery:')); + assert.ok(program.includes('if Result.Bindings.Count <> ExpectedBindings then')); + assert.ok(!program.includes('Length(Result.Bindings)')); + assert.ok(!/(?3')); + } +}); +test('Delphi IDE projects have stable, unique GUIDs and console platform metadata', async () => { + const files = await generateSmokeProjects(); + const regenerated = await generateSmokeProjects(); + const guids = new Set(); + for (const dialect of Object.keys(smokeDialects)) { + const name = `ConverterSmoke${dialect}`; + const project = files.get(`${name}.dproj`); + const guid = project.match(/(\{[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}\})<\/ProjectGuid>/)?.[1]; + assert.ok(guid, `${name}: missing or invalid project GUID`); + assert.ok(!guids.has(guid), `${name}: duplicate project GUID`); + guids.add(guid); + assert.equal(project, regenerated.get(`${name}.dproj`)); + assert.ok(project.includes('Console')); + assert.ok(project.includes(`${name}.dpr`)); + for (const platform of ['Win32', 'Win64']) assert.ok(project.includes(`True`)); + assert.ok(!project.includes('Debugger_HostApplication')); + } +}); +test('smoke project configuration retains the working console project structure', async () => { + const template = await readFile(smokeProjectTemplate, 'utf8'); + const files = await generateSmokeProjects(); + const groups = xml => [...xml.matchAll(//g)].map(match => match[1] || ''); + const imports = xml => [...xml.matchAll(/]*\/>/g)].map(match => match[0]); + for (const dialect of Object.keys(smokeDialects)) { + const name = `ConverterSmoke${dialect}`; + const project = files.get(`${name}.dproj`); + assert.deepEqual(groups(project), groups(template)); + assert.deepEqual(imports(project), imports(template)); + const baseOptions = project.match(/([\s\S]*?)<\/PropertyGroup>/)?.[1]; + assert.ok(baseOptions?.includes(''), 'IDE launch must resolve the configured executable output'); + assert.ok(!project.split('')[0].includes('${name}`)); + assert.ok(project.includes('.\\$(Platform)')); + assert.ok(project.includes('.\\$(Platform)\\dcu')); + assert.ok(project.includes('..\\..\\src;$(DCC_UnitSearchPath)')); + assert.ok(!project.includes('DUnitX')); + assert.ok(!project.includes(' { + for (const [sql, delphi] of values) { + const code = await convert(`SELECT * FROM t WHERE a = ${sql}`, dialect); + assert.ok(code.includes(`.Where('a', '=', ${delphi})`), `${sql}: ${code}`); + assert.ok(!code.includes('Data.FmtBcd')); + } + }); + test(`${dialect}: ordinary decimals produce natural Delphi literals`, async () => { + for (const [sql, output] of [ + ['0.1', '0.1'], ['19.99', '19.99'], ['1.2300', '1.23'], ['1.000', '1.0'], ['.125', '0.125'], + ['-0.000000000000000001', '-0.000000000000000001'], + ['0001.0200', '1.02'], ['1.', '1.0'], ['0.000', '0.0'], ['- 19.990', '-19.99'], + ['0.123456789012345', '0.123456789012345'], + ]) { + const code = await convert(`SELECT * FROM t WHERE a = ${sql}`, dialect); + assert.ok(code.includes(`.Where('a', '=', ${output})`), code); + for (const extra of ['TValue.From', 'StrToBcd', 'Data.FmtBcd', 'System.Rtti', 'System.SysUtils']) assert.ok(!code.includes(extra), code); + } + }); + test(`${dialect}: precise numbers in lists, ranges and HAVING`, async () => { + const code = await convert('SELECT a FROM t WHERE a IN (9007199254740993, -9223372036854775808) AND a BETWEEN 0.100 AND 1.2500 GROUP BY a HAVING a > 0.050', dialect); + assert.ok(code.includes(".WhereIn('a', [Int64(9007199254740993), Low(Int64)])")); + assert.ok(code.includes(".WhereBetween('a', 0.1, 1.25)")); + assert.ok(code.includes(".Having('a', '>', 0.05)")); + }); + test(`${dialect}: rejects unrepresentable integers and ambiguous scientific values`, async () => { + for (const value of ['9223372036854775808', '-9223372036854775809']) await assert.rejects(convert(`SELECT * FROM t WHERE a = ${value}`, dialect), /signed Delphi Int64 range/); + for (const value of ['1e3', '-1E-20', '1e-324', '1e309', '0e0']) await assert.rejects(convert(`SELECT * FROM t WHERE a = ${value}`, dialect), /Scientific notation is not supported/); + for (const value of ['0.1234567890123456', '100000000000000.000001', '9007199254740993.0', '12345678901234567890123456789012.3']) await assert.rejects(convert(`SELECT * FROM t WHERE a = ${value}`, dialect), /15 significant digits.*Currency or TBcd/); + for (const value of ['0.' + '0'.repeat(309) + '1', '1' + '0'.repeat(309) + '.0']) await assert.rejects(convert(`SELECT * FROM t WHERE a = ${value}`, dialect), /normal Double range/); + }); +} +test('decimal safety is based on significant digits, not insignificant zeros', () => { + assert.equal(numericLiteral('123456789012345.0000000'), '123456789012345.0'); + assert.equal(numericLiteral('0.0000000000000000001'), '0.0000000000000000001'); + assert.equal(numericLiteral('000.123450000000000000000'), '0.12345'); + assert.throws(() => numericLiteral('0.1234567890123456'), /15 significant digits/); +}); +test('normal Double range checks use exact decimal bounds', () => { + const small = '0.' + '0'.repeat(307); + const largeZeros = '0'.repeat(294) + '.0'; + assert.equal(numericLiteral(small + '222507385850721'), small + '222507385850721'); + assert.throws(() => numericLiteral(small + '22250738585072'), /normal Double range/); + assert.equal(numericLiteral('179769313486231' + largeZeros), '179769313486231' + largeZeros); + assert.throws(() => numericLiteral('179769313486232' + largeZeros), /normal Double range/); +}); +test('numeric token preservation does not alter strings, comments or identifiers', async () => { + const code = await convert("SELECT a2, `price$20` FROM `t42$123` WHERE a2 = '1.2300 and 9999999999999999999999' AND a2 > 9007199254740993 /* 1e999 */"); + assert.ok(code.includes("'1.2300 and 9999999999999999999999'")); + assert.ok(code.includes('Int64(9007199254740993)')); + assert.ok(code.includes("TQuery.Create('t42$123')")); + assert.ok(code.includes("'price$20'")); +}); +test('paging is checked from exact integer text', async () => { + assert.match(await convert('SELECT a FROM t ORDER BY a LIMIT 20 OFFSET 9223372036854775807'), /\.Offset\(Int64\(9223372036854775807\)\)/); + for (const suffix of ['LIMIT 1.0', 'LIMIT 1e1', 'LIMIT 2147483648', 'LIMIT 20 OFFSET 9223372036854775808']) await assert.rejects(convert(`SELECT a FROM t ${suffix}`), /Paging requires/); +}); From 2c090ef263758620f9d91738013bcfbbb4ea397a Mon Sep 17 00:00:00 2001 From: Christoph Auer Date: Sat, 31 Oct 2026 20:06:00 +0100 Subject: [PATCH 3/3] Add highlighted editors and improve documentation navigation --- .github/workflows/pages.yml | 2 + .gitignore | 2 + docs/WEBSITE.md | 30 + website/app.mjs | 25 +- website/build.mjs | 17 +- website/converter.html | 5 +- website/delphi-tokens.mjs | 36 ++ website/editors.mjs | 59 ++ website/navigation.mjs | 29 + website/package-lock.json | 180 ++++++ website/package.json | 10 +- website/playwright.config.mjs | 17 + website/preview.mjs | 8 +- website/style.css | 824 +++++++++++++++++++++++++- website/test/browser/website.spec.mjs | 130 ++++ website/test/delphi-tokens.test.mjs | 32 + 16 files changed, 1353 insertions(+), 53 deletions(-) create mode 100644 website/delphi-tokens.mjs create mode 100644 website/editors.mjs create mode 100644 website/playwright.config.mjs create mode 100644 website/test/browser/website.spec.mjs create mode 100644 website/test/delphi-tokens.test.mjs diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 7562ae7..7533851 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -42,6 +42,8 @@ jobs: - run: npm test - run: npm run build - run: npm run test:site + - run: npx playwright install --with-deps chromium + - run: npm run test:browser - uses: actions/upload-pages-artifact@v4 with: path: website/dist diff --git a/.gitignore b/.gitignore index 7ca5f8c..cfa970f 100644 --- a/.gitignore +++ b/.gitignore @@ -87,3 +87,5 @@ tools/oracle/obj/ build/ website/node_modules/ website/dist/ +website/test-results/ +website/playwright-report/ diff --git a/docs/WEBSITE.md b/docs/WEBSITE.md index 790d7c6..e6ea25a 100644 --- a/docs/WEBSITE.md +++ b/docs/WEBSITE.md @@ -33,6 +33,36 @@ The build bundles all browser dependencies locally; no CDN, backend, database, AI API, or analytics service is required. Only the selected dialect's parser is loaded. SQL input is processed in memory and is neither uploaded nor persisted. +The converter uses CodeMirror 6, with dialect-specific SQL highlighting and a +small Delphi lexical highlighter (`website/delphi-tokens.mjs`). The generic +legacy Pascal mode was evaluated; it does not distinguish Delphi types and +calls, and treats line-leading `#` character codes as preprocessor text. +The Delphi highlighter handles generated code, doubled-quote strings, character +codes and multiline comments; it is not a complete Delphi parser or validator. +The output editor is read-only and supports selection and copying. Ctrl+Enter +(or ⌘Enter) converts; Tab indents SQL, and Escape followed by Tab leaves the +editor. Input remains limited to 50,000 characters. + +Primary documentation links stay visible. Secondary pages live in a native +**Advanced** details group that opens automatically for its active page. On +mobile, this remains a single horizontally scrolling row; a right-edge fade +indicates hidden links and disappears at the end. The current page scrolls into +view on load without moving the document vertically. + +Browser interaction and responsive checks run with: + +```sh +npm run build +npx playwright install chromium # Linux/macOS; Windows uses installed Edge +npm run test:browser +``` + +These tests start a separate local server at port 4174 and mount the site at +`/QueryBuilder4Delphi/`. They cover editing, read-only output, copy/fallback, +conversion shortcuts, invalidation/errors, navigation groups, mobile overflow, +focus and reduced motion at 1920, 1366, 768, 320, 375 and 390 pixels. CI uses +Chromium. Browser tooling is development-only; it is not shipped to visitors. + ## GitHub Pages deployment 1. Merge the website files and `.github/workflows/pages.yml` into `main`. diff --git a/website/app.mjs b/website/app.mjs index e8673e4..708958b 100644 --- a/website/app.mjs +++ b/website/app.mjs @@ -1,5 +1,6 @@ import { convert } from './converter.mjs'; import { createConversionController } from './conversion-state.mjs'; +import { createEditors } from './editors.mjs'; const $ = id => document.getElementById(id); const examples = { basic: 'SELECT Id, Title\nFROM Books\nWHERE AuthorId = 42\nORDER BY Title;', @@ -7,39 +8,39 @@ const examples = { group: "SELECT Id, Title\nFROM Books\nWHERE (AuthorId = 42 OR AuthorId = 7)\n AND Price BETWEEN 10 AND 50\n AND DeletedAt IS NULL\nORDER BY Title DESC;", paging: 'SELECT Id, Title\nFROM Books\nORDER BY Title, Id\nLIMIT 20 OFFSET 40;', }; +const editors = createEditors({ + sqlHost: $('sql'), delphiHost: $('delphi'), initialSql: $('initial-sql').textContent, + dialect: $('dialect').value, onChange: () => invalidate(), onConvert: () => run(), +}); const { invalidate, run } = createConversionController({ convert, - readInput: () => ({ sql: $('sql').value, dialect: $('dialect').value }), + readInput: () => ({ sql: editors.readSql(), dialect: $('dialect').value }), render: ({ busy, code, message, error }) => { $('convert').disabled = busy; - $('delphi').value = code; + editors.setOutput(code); $('copy').disabled = busy || !code; $('status').textContent = message; $('status').className = error ? 'error' : ''; }, }); $('convert').addEventListener('click', run); -$('sql').addEventListener('input', invalidate); -$('dialect').addEventListener('change', invalidate); +$('dialect').addEventListener('change', () => { editors.setDialect($('dialect').value); invalidate(); }); $('load-example').addEventListener('click', () => { - $('sql').value = $('example').value === 'paging' && $('dialect').value === 'TransactSQL' - ? 'SELECT TOP 20 Id, Title\nFROM Books\nORDER BY Title, Id;' : examples[$('example').value]; + editors.setSql($('example').value === 'paging' && $('dialect').value === 'TransactSQL' + ? 'SELECT TOP 20 Id, Title\nFROM Books\nORDER BY Title, Id;' : examples[$('example').value]); invalidate(); }); $('copy').addEventListener('click', async () => { - const code = $('delphi').value; + const code = editors.readOutput(); if (!code || $('copy').disabled) return; - const stillCurrent = () => $('delphi').value === code && !$('copy').disabled; + const stillCurrent = () => editors.readOutput() === code && !$('copy').disabled; try { await navigator.clipboard.writeText(code); if (stillCurrent()) $('status').textContent = 'Delphi code copied.'; } catch { if (!stillCurrent()) return; - $('delphi').focus(); $('delphi').select(); + editors.selectOutput(); $('status').textContent = 'Select the output and copy it with Ctrl+C (or ⌘C).'; } }); -$('sql').addEventListener('keydown', event => { - if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); run(); } -}); run(); diff --git a/website/build.mjs b/website/build.mjs index 6a2f520..71faf1e 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -22,7 +22,7 @@ export function linkTo(href, source) { } const menu = [ ['README.md', 'Overview'], ['converter.html', 'SQL → Delphi'], - ['docs/EXAMPLES.md', 'Examples'], ['docs/API.md', 'API & limitations'], + ['docs/EXAMPLES.md', 'Examples'], ['docs/API.md', 'API reference'], ['docs/OBJECT_MAPPING.md', 'Object mapping'], ['docs/PORTING.md', 'Porting'], ['docs/VALIDATION.md', 'Validation'], ['docs/XML_DOCUMENTATION.md', 'XML documentation'], ['docs/MAPPING_PERFORMANCE.md', 'Mapping performance'], ['CHANGELOG.md', 'Changelog'], @@ -32,12 +32,15 @@ function shell(title, body, source, toc = []) { const filename = target(source); const prefix = path.posix.relative(path.posix.dirname(filename), '.') || '.'; const relative = to => path.posix.relative(path.posix.dirname(filename), to); + const navLink = ([file, label]) => `${label}`; + const advanced = menu.slice(5); + const expanded = advanced.some(([file]) => file === source); return ` ${escape(title)} · QueryBuilder4Delphi
QueryBuilder4DelphiGitHub ↗
-
+
${body}
${toc.length ? `` : ''}
@@ -74,10 +77,14 @@ await cp(path.join(site, 'style.css'), path.join(output, 'assets/style.css')); await cp(path.join(site, 'favicon.svg'), path.join(output, 'assets/favicon.svg')); await cp(path.join(site, 'node_modules/highlight.js/styles/github-dark.css'), path.join(output, 'assets/highlight.css')); const licenses = []; -for (const name of ['node-sql-parser', 'big-integer', 'highlight.js']) { - const dependency = path.join(site, 'node_modules', name); +const lock = JSON.parse(await readFile(path.join(site, 'package-lock.json'), 'utf8')); +for (const [location, entry] of Object.entries(lock.packages)) { + if (!location || entry.dev) continue; + const dependency = path.join(site, location); const pkg = JSON.parse(await readFile(path.join(dependency, 'package.json'), 'utf8')); - licenses.push(`${name} ${pkg.version}\n${await readFile(path.join(dependency, 'LICENSE'), 'utf8')}`); + const license = (await readdir(dependency)).find(file => /^license(?:\.(?:txt|md))?$/i.test(file)); + if (!license) throw new Error(`Missing license file: ${pkg.name}`); + licenses.push(`${pkg.name} ${pkg.version}\n${await readFile(path.join(dependency, license), 'utf8')}`); } await writeFile(path.join(output, 'assets/third-party-licenses.txt'), licenses.join('\n\n---\n\n')); await writeFile(path.join(output, '.nojekyll'), ''); diff --git a/website/converter.html b/website/converter.html index d224f1b..facc920 100644 --- a/website/converter.html +++ b/website/converter.html @@ -2,10 +2,11 @@

SQL in. Delphi out.

Turn a SELECT query into fluent QueryBuilder4Delphi code. Everything runs in your browser; your SQL stays on your device.

-
SELECT
+ORDER BY Title;
02 Delphi output
+

Ctrl+Enter (⌘Enter) to convert · Tab to indent · Escape, then Tab to leave the SQL editor.

Ready to convert.

What can I convert?

One SELECT statement with table and column aliases, DISTINCT, INNER/LEFT/RIGHT JOIN with one column comparison, CROSS JOIN, grouped AND/OR conditions, column comparisons, LIKE, IN, BETWEEN, IS NULL, GROUP BY, simple HAVING, ORDER BY and literal paging values. SQL Server TOP and OFFSET/FETCH are also supported.

CTEs, unions, subqueries, aggregate/function expressions, complex JOIN conditions, placeholders, quoted identifiers containing spaces or punctuation, and dialect-specific extensions are rejected. No partial code or raw SQL fallback is emitted. Zero row limits and MySQL string literals with backslash escapes are rejected because their meaning cannot be preserved reliably.

Ordinary decimals produce natural Delphi literals such as 19.99, without BCD wrappers or extra imports. Decimals are limited to 15 significant digits (ignoring insignificant zeros) within the normal Double range; high-precision values, subnormal values and scientific notation are rejected. Binary floating-point parameters do not guarantee exact SQL DECIMAL semantics. Exact parameter types depend on your schema: choose Currency, TBcd or another Delphi type manually when needed. Signed integer values retain exact Integer/Int64 validation.

The output is a complete BuildQuery: IQuery function. Compile it with your chosen TSqlDialect in Delphi; the converter does not execute SQL or run the Delphi compiler. PostgreSQL unquoted identifiers are folded to lowercase. SQL comments are not included in the output.

diff --git a/website/delphi-tokens.mjs b/website/delphi-tokens.mjs new file mode 100644 index 0000000..0e155e4 --- /dev/null +++ b/website/delphi-tokens.mjs @@ -0,0 +1,36 @@ +// A small lexical highlighter, not a Delphi parser or semantic validator. +// The legacy Pascal mode does not distinguish Delphi types/calls and treats +// line-leading # character codes as preprocessor text. Handle these explicitly. +const keywords = new Set(('and array as asm begin case class const constructor destructor div do downto else end except exports file finalization finally for function goto helper if implementation in inherited initialization inline interface is label library mod nil not object of on operator or out packed private procedure program property protected public published raise record repeat resourcestring self set shl shr strict string then threadvar to try type unit until uses var virtual while with xor').split(' ')); +const types = new Set('boolean byte cardinal char currency double extended integer int64 nativeint nativeuint pointer real shortint single smallint string tvalue tbcd uint64 variant widechar word'.split(' ')); + +export const delphiTokens = { + startState: () => ({ comment: null }), + token(stream, state) { + if (state.comment) { + while (!stream.eol()) { + if (stream.match(state.comment)) { state.comment = null; break; } + stream.next(); + } + return 'comment'; + } + if (stream.eatSpace()) return null; + if (stream.match('//')) { stream.skipToEnd(); return 'comment'; } + if (stream.match('(*')) { state.comment = '*)'; return 'comment'; } + if (stream.match('{')) { state.comment = '}'; return 'comment'; } + if (stream.match(/'(?:[^']|'')*'/)) return 'string'; + if (stream.match(/#(?:\$[\da-f]+|\d+)/i)) return 'string'; + if (stream.match(/(?:\$[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)/i)) return 'number'; + const word = stream.match(/[a-z_][\w]*/i); + if (word) { + const name = word[0].toLowerCase(); + if (types.has(name) || /^[IT][A-Z]\w*$/.test(word[0])) return 'typeName'; + if (keywords.has(name)) return 'keyword'; + if (stream.match(/^\s*(?:<[^<>;\r\n]+>)?\s*\(/, false)) return 'variableName.function'; + return 'variableName'; + } + if (stream.match(/[:=+*/<>@^\-]+/)) return 'operator'; + stream.next(); + return null; + }, +}; diff --git a/website/editors.mjs b/website/editors.mjs new file mode 100644 index 0000000..61f966e --- /dev/null +++ b/website/editors.mjs @@ -0,0 +1,59 @@ +import { EditorState } from '@codemirror/state'; +import { EditorView, keymap, lineNumbers, highlightActiveLine, drawSelection } from '@codemirror/view'; +import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands'; +import { StreamLanguage, HighlightStyle, syntaxHighlighting, indentOnInput } from '@codemirror/language'; +import { sql, MySQL, PostgreSQL, MSSQL, SQLite } from '@codemirror/lang-sql'; +import { Compartment } from '@codemirror/state'; +import { tags } from '@lezer/highlight'; +import { delphiTokens } from './delphi-tokens.mjs'; + +const colors = HighlightStyle.define([ + { tag: tags.keyword, color: '#ffab99' }, + { tag: tags.string, color: '#b3ef91' }, + { tag: tags.number, color: '#91c9ff' }, + { tag: tags.comment, color: '#91a58e', fontStyle: 'italic' }, + { tag: tags.operator, color: '#ddd4a1' }, + { tag: tags.typeName, color: '#95d9ce' }, + { tag: tags.function(tags.variableName), color: '#d6b5fa' }, +]); +const dialects = { MySQL, PostgreSQL, TransactSQL: MSSQL, SQLite }; + +export function createEditors({ sqlHost, delphiHost, initialSql, dialect, onChange, onConvert }) { + const language = new Compartment(); + const common = [ + lineNumbers(), drawSelection(), history(), + syntaxHighlighting(colors), + EditorView.theme({}, { dark: true }), + keymap.of([...defaultKeymap, ...historyKeymap]), + ]; + const input = new EditorView({ + parent: sqlHost, + state: EditorState.create({ doc: initialSql, extensions: [ + keymap.of([{ key: 'Mod-Enter', run: () => { onConvert(); return true; } }, indentWithTab]), + ...common, highlightActiveLine(), indentOnInput(), + language.of(sql({ dialect: dialects[dialect] })), + EditorView.contentAttributes.of({ 'aria-label': 'SQL input', 'aria-describedby': 'editor-help', spellcheck: 'false' }), + EditorState.transactionFilter.of(tr => tr.newDoc.length > 50000 ? [] : tr), + EditorView.updateListener.of(update => { if (update.docChanged) onChange(); }), + ] }), + }); + const output = new EditorView({ + parent: delphiHost, + state: EditorState.create({ extensions: [ + ...common, StreamLanguage.define(delphiTokens), + EditorState.readOnly.of(true), EditorView.editable.of(false), + EditorView.contentAttributes.of({ 'aria-label': 'Generated Delphi code', 'aria-readonly': 'true', tabindex: '0', role: 'textbox' }), + ] }), + }); + const replace = (view, value) => { + if (view.state.doc.toString() !== value) view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } }); + }; + return { + readSql: () => input.state.doc.toString(), + readOutput: () => output.state.doc.toString(), + setSql: value => replace(input, value), + setOutput: value => replace(output, value), + setDialect: value => input.dispatch({ effects: language.reconfigure(sql({ dialect: dialects[value] })) }), + selectOutput: () => { output.focus(); output.dispatch({ selection: { anchor: 0, head: output.state.doc.length } }); }, + }; +} diff --git a/website/navigation.mjs b/website/navigation.mjs index d8273d7..adfba70 100644 --- a/website/navigation.mjs +++ b/website/navigation.mjs @@ -1,5 +1,34 @@ // Native anchor navigation keeps URLs, keyboard access and browser history intact. // CSS provides smooth scrolling, with an immediate fallback for reduced motion. +const documentationNav = document.querySelector('.sidebar nav'); +const navFrame = document.querySelector('.nav-scroll'); +const advanced = document.querySelector('.advanced-nav'); +const mobile = matchMedia('(max-width: 680px)'); +let navScheduled = false; +function updateOverflow() { + navScheduled = false; + navFrame.classList.toggle('has-more', mobile.matches && documentationNav.scrollWidth - documentationNav.clientWidth - documentationNav.scrollLeft > 2); +} +function scheduleOverflow() { + if (!navScheduled) { navScheduled = true; requestAnimationFrame(updateOverflow); } +} +function revealActive() { + if (mobile.matches) { + const active = documentationNav.querySelector('[aria-current="page"]'); + if (active) documentationNav.scrollLeft += active.getBoundingClientRect().left - documentationNav.getBoundingClientRect().left - (documentationNav.clientWidth - active.offsetWidth) / 2; + } + scheduleOverflow(); +} +advanced.addEventListener('toggle', () => { + advanced.querySelector('summary').setAttribute('aria-expanded', String(advanced.open)); + scheduleOverflow(); +}); +documentationNav.addEventListener('scroll', scheduleOverflow, { passive: true }); +new ResizeObserver(scheduleOverflow).observe(documentationNav); +mobile.addEventListener('change', revealActive); +window.addEventListener('pageshow', revealActive); +revealActive(); + const backToTop = document.querySelector('.back-to-top'); const links = [...document.querySelectorAll('.toc nav a')]; const sections = links.map(link => ({ diff --git a/website/package-lock.json b/website/package-lock.json index a6d3197..b7a4b91 100644 --- a/website/package-lock.json +++ b/website/package-lock.json @@ -6,15 +6,102 @@ "": { "name": "querybuilder4delphi-website", "dependencies": { + "@codemirror/commands": "^6.11.1", + "@codemirror/lang-sql": "^6.10.0", + "@codemirror/language": "^6.13.1", + "@codemirror/state": "^6.7.6", + "@codemirror/view": "^6.43.15", + "@lezer/highlight": "^1.2.5", "github-slugger": "^2.0.0", "highlight.js": "^11.12.0", "marked": "^18.1.2", "node-sql-parser": "^5.4.0" }, "devDependencies": { + "@playwright/test": "^1.64.1", "esbuild": "^0.28.2" } }, + "node_modules/@codemirror/autocomplete": { + "version": "6.20.4", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz", + "integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@codemirror/commands": { + "version": "6.11.1", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz", + "integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.7.0", + "@codemirror/view": "^6.27.0", + "@lezer/common": "^1.1.0" + } + }, + "node_modules/@codemirror/lang-sql": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz", + "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==", + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@codemirror/language": { + "version": "6.13.1", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz", + "integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/streamparser": "^6.0.0", + "@codemirror/view": "^6.23.0", + "@lezer/common": "^1.5.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" + } + }, + "node_modules/@codemirror/state": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", + "license": "MIT", + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/streamparser": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz", + "integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==", + "license": "MIT" + }, + "node_modules/@codemirror/view": { + "version": "6.43.15", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz", + "integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.7.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -457,6 +544,52 @@ "node": ">=18" } }, + "node_modules/@lezer/common": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.5.tgz", + "integrity": "sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==", + "license": "MIT" + }, + "node_modules/@lezer/highlight": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz", + "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.3.0" + } + }, + "node_modules/@lezer/lr": { + "version": "1.4.12", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.12.tgz", + "integrity": "sha512-On9HU4oMMiHPMkQDgoTnGahjgG5n/MkN38CgG77sMraKLL+3JBbeQNi1FcCXV9QRqwF9/BUXP3caHyJC1fBOTQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", + "license": "MIT" + }, + "node_modules/@playwright/test": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@types/pegjs": { "version": "0.10.6", "resolved": "https://registry.npmjs.org/@types/pegjs/-/pegjs-0.10.6.tgz", @@ -472,6 +605,12 @@ "node": ">=0.6" } }, + "node_modules/crelt": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", + "license": "MIT" + }, "node_modules/esbuild": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", @@ -553,6 +692,47 @@ "engines": { "node": ">=8" } + }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/style-mod": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz", + "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", + "license": "MIT" + }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "license": "MIT" } } } diff --git a/website/package.json b/website/package.json index b127774..d6dcda7 100644 --- a/website/package.json +++ b/website/package.json @@ -4,18 +4,26 @@ "type": "module", "scripts": { "build": "node build.mjs", - "test": "node --test test/converter.test.mjs test/numbers.test.mjs test/conversion-state.test.mjs test/delphi-smoke.test.mjs", + "test": "node --test test/converter.test.mjs test/numbers.test.mjs test/conversion-state.test.mjs test/delphi-smoke.test.mjs test/delphi-tokens.test.mjs", + "test:browser": "playwright test", "smoke:generate": "node generate-smoke.mjs", "test:site": "node --test test/site.test.mjs", "preview": "node preview.mjs" }, "dependencies": { + "@codemirror/commands": "^6.11.1", + "@codemirror/lang-sql": "^6.10.0", + "@codemirror/language": "^6.13.1", + "@codemirror/state": "^6.7.6", + "@codemirror/view": "^6.43.15", + "@lezer/highlight": "^1.2.5", "github-slugger": "^2.0.0", "highlight.js": "^11.12.0", "marked": "^18.1.2", "node-sql-parser": "^5.4.0" }, "devDependencies": { + "@playwright/test": "^1.64.1", "esbuild": "^0.28.2" } } diff --git a/website/playwright.config.mjs b/website/playwright.config.mjs new file mode 100644 index 0000000..14ac85f --- /dev/null +++ b/website/playwright.config.mjs @@ -0,0 +1,17 @@ +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './test/browser', + fullyParallel: true, + workers: 2, + use: { + channel: process.platform === 'win32' ? 'msedge' : undefined, + baseURL: 'http://127.0.0.1:4174/QueryBuilder4Delphi/', + viewport: { width: 1366, height: 900 }, + }, + webServer: { + command: 'node preview.mjs', + env: { PORT: '4174', BASE_PATH: '/QueryBuilder4Delphi/' }, + url: 'http://127.0.0.1:4174/QueryBuilder4Delphi/', + }, +}); diff --git a/website/preview.mjs b/website/preview.mjs index fa56af5..2e36b8e 100644 --- a/website/preview.mjs +++ b/website/preview.mjs @@ -4,12 +4,16 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'dist'); const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.svg': 'image/svg+xml' }; +const port = Number(process.env.PORT || 4173); +const basePath = process.env.BASE_PATH || '/'; http.createServer(async (req, res) => { try { - const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + const requested = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + if (!requested.startsWith(basePath)) throw new Error('Not found'); + const pathname = '/' + requested.slice(basePath.length); const file = path.resolve(root, '.' + pathname + (pathname.endsWith('/') ? 'index.html' : '')); if (!file.startsWith(root + path.sep) || !(await stat(file)).isFile()) throw new Error('Not found'); res.setHeader('Content-Type', `${types[path.extname(file)] || 'application/octet-stream'}; charset=utf-8`); res.end(await readFile(file)); } catch { res.writeHead(404); res.end('Not found'); } -}).listen(4173, '127.0.0.1', () => console.log('Local: http://127.0.0.1:4173')); +}).listen(port, '127.0.0.1', () => console.log(`Local: http://127.0.0.1:${port}${basePath}`)); diff --git a/website/style.css b/website/style.css index c7b50d4..4a2d9f4 100644 --- a/website/style.css +++ b/website/style.css @@ -1,9 +1,664 @@ -@import url('./highlight.css'); -:root{color-scheme:dark;--bg:#111714;--panel:#18201b;--line:#303d33;--text:#e5ece5;--muted:#a0b2a3;--accent:#b3ef91;font-family:Inter,Segoe UI,Arial,sans-serif;font-size:16px;line-height:1.65}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}a{color:var(--accent);text-underline-offset:4px}a:hover{color:#d5ffc1}header{height:82px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 38px;gap:20px}header>a:last-child{font-size:.9rem;color:var(--muted)}.brand{display:flex;align-items:center;color:var(--text);text-decoration:none;font-size:1.12rem;font-weight:650;letter-spacing:-.4px}.logo{background:var(--accent);color:#172317;display:inline-flex;align-items:center;justify-content:center;width:39px;height:39px;border-radius:9px;margin-right:13px;font-family:monospace;font-size:27px}.logo span{font-size:24px}.muted{color:var(--muted);font-weight:400}.layout{display:grid;grid-template-columns:245px minmax(0,1fr) 190px;max-width:1700px;margin:auto}.sidebar{padding:40px 24px;border-right:1px solid var(--line)}.sidebar nav{display:flex;flex-direction:column;gap:5px}.sidebar nav a{color:var(--muted);padding:8px 12px;border-radius:6px;text-decoration:none;font-size:.9rem}.sidebar nav a:hover,.sidebar nav a[aria-current]{background:#263629;color:var(--accent)}.eyebrow{font-size:.69rem;letter-spacing:1.8px;color:var(--muted);font-weight:700}.sidebar .eyebrow{margin-left:12px}.sidebar-note{font-size:.8rem;line-height:1.8;color:var(--text);margin:45px 12px 0;padding-top:20px;border-top:1px solid var(--line)}.sidebar-note span{color:var(--muted)}main{min-width:0;padding:42px 48px 24px}h1{font-size:2.8rem;line-height:1.15;letter-spacing:-1.5px;font-weight:650;margin:10px 0 28px}h2{font-size:1.65rem;letter-spacing:-.5px;margin:2.3rem 0 1rem}h3{margin:1.8rem 0 .7rem}h1,h2,h3,h4{scroll-margin-top:24px}p{margin:0 0 1.1rem}.documentation{max-width:1050px}.documentation h1{font-size:2.5rem}.documentation p,.documentation li{color:#c1cec2}.documentation strong{color:var(--text)}.documentation li{margin:.4rem 0}.documentation img{max-width:100%}.documentation table{display:block;overflow:auto;border-collapse:collapse;font-size:.9rem;margin:24px 0}.documentation th,.documentation td{padding:10px 14px;border:1px solid var(--line);text-align:left}.documentation th{background:var(--panel)}code,textarea{font-family:Consolas,SFMono-Regular,monospace;font-size:.86rem}p code,li code,td code{background:#263129;padding:2px 5px;border-radius:4px;color:#ceeabb}.code-block{border:1px solid var(--line);border-radius:8px;overflow:hidden;margin:20px 0;background:#141c17}.code-language{display:block;padding:7px 16px;border-bottom:1px solid var(--line);font-size:.7rem;letter-spacing:.5px;color:var(--muted)}pre{padding:17px 20px;overflow:auto;line-height:1.65;margin:0}pre .hljs{background:transparent}blockquote{border-left:3px solid var(--accent);padding-left:20px;margin-left:0}.anchor{opacity:0;font-size:.8em;margin-left:10px;text-decoration:none}h1:hover .anchor,h2:hover .anchor,h3:hover .anchor,.anchor:focus{opacity:1}.toc{padding:46px 20px 20px 0}.toc nav{display:flex;flex-direction:column;gap:10px}.toc a{font-size:.76rem;text-decoration:none;color:var(--muted)}footer{border-top:1px solid var(--line);margin-top:54px;padding:22px 0;color:var(--muted);font-size:.75rem}footer a{color:var(--muted)}.converter-page{grid-column:2/4;padding-right:40px}.converter-page h1{font-size:clamp(2.5rem,4vw,4.25rem);margin:16px 0 20px}.accent{color:var(--accent)}.lead{max-width:700px;color:var(--muted);font-size:1.05rem}.toolbar{display:flex;flex-wrap:wrap;align-items:end;gap:16px;margin:32px 0 20px}.toolbar label{display:flex;flex-direction:column;gap:6px;font-size:.77rem;color:var(--muted)}select,button{font:inherit;border:1px solid var(--line);border-radius:6px;color:var(--text);background:var(--panel);padding:9px 14px;font-size:.85rem}select{min-width:165px}button{cursor:pointer}button:hover{border-color:var(--accent)}button:disabled{opacity:.45;cursor:default}button:focus-visible,select:focus-visible,a:focus-visible,textarea:focus-visible{outline:2px solid var(--accent);outline-offset:3px}.editors{display:grid;grid-template-columns:1fr 1fr;gap:18px}.editor-panel{border:1px solid var(--line);border-radius:9px;overflow:hidden;background:#141c17;min-width:0}.panel-heading{height:58px;display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--line);font-size:.7rem;color:var(--muted);gap:12px}.panel-heading strong{font-size:.83rem;color:var(--text);margin-left:9px;font-weight:500}.panel-heading button{font-size:.72rem;padding:4px 9px}textarea{display:block;resize:vertical;min-height:390px;width:100%;border:0;border-radius:0;background:transparent;color:#d6ebcd;padding:20px;line-height:1.8;tab-size:2}#delphi{color:#becddd}.convert-actions{display:flex;align-items:center;gap:20px;margin:20px 0 34px}.convert-actions p{margin:0;font-size:.83rem;color:var(--muted);overflow-wrap:anywhere}.primary{background:var(--accent);color:#14220f;font-weight:650;border-color:var(--accent);white-space:nowrap}.primary span{margin-left:20px}.convert-actions .error{color:#ffa89a}.support{border-top:1px solid var(--line);padding-top:24px;max-width:960px}.support h2{font-size:1.2rem;margin:0 0 12px}.support p{color:var(--muted);font-size:.85rem}.skip{position:absolute;top:-60px;left:12px;background:var(--accent);color:#111;padding:8px;z-index:2}.skip:focus{top:10px}@media(min-width:1500px){textarea{min-height:450px}}@media(max-width:1150px){.layout{grid-template-columns:210px minmax(0,1fr)}.toc{display:none}.converter-page{grid-column:2}main{padding:32px}.sidebar{padding:28px 15px}.editors{grid-template-columns:1fr}textarea{min-height:280px}}@media(max-width:680px){header{height:70px;padding:0 18px}.brand{font-size:.95rem}.logo{width:30px;height:32px;font-size:23px;margin-right:8px}.layout{display:block}.sidebar{border-right:0;border-bottom:1px solid var(--line);padding:14px 18px}.sidebar .eyebrow,.sidebar-note{display:none}.sidebar nav{flex-direction:row;overflow:auto}.sidebar nav a{white-space:nowrap;font-size:.8rem;padding:6px 10px}main,.converter-page{padding:30px 20px 12px}h1,.documentation h1{font-size:2rem}.convert-actions{align-items:start;flex-direction:column;gap:12px}.toolbar{gap:10px}.toolbar label{flex:1}.toolbar select{width:100%;min-width:120px}.documentation ul{padding-left:22px}pre{padding:14px}.anchor{opacity:1}} +@import url("./highlight.css"); +/* Shared palette and page layout. */ +:root { + color-scheme: dark; + --bg: #111714; + --panel: #18201b; + --line: #303d33; + --text: #e5ece5; + --muted: #a0b2a3; + --accent: #b3ef91; + font-family: + Inter, + Segoe UI, + Arial, + sans-serif; + font-size: 16px; + line-height: 1.65; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + background: var(--bg); + color: var(--text); +} +a { + color: var(--accent); + text-underline-offset: 4px; +} +a:hover { + color: #d5ffc1; +} +header { + height: 82px; + border-bottom: 1px solid var(--line); + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 38px; + gap: 20px; +} +header > a:last-child { + font-size: 0.9rem; + color: var(--muted); +} +.brand { + display: flex; + align-items: center; + color: var(--text); + text-decoration: none; + font-size: 1.12rem; + font-weight: 650; + letter-spacing: -0.4px; +} +.logo { + background: var(--accent); + color: #172317; + display: inline-flex; + align-items: center; + justify-content: center; + width: 39px; + height: 39px; + border-radius: 9px; + margin-right: 13px; + font-family: monospace; + font-size: 27px; +} +.logo span { + font-size: 24px; +} +.muted { + color: var(--muted); + font-weight: 400; +} +.layout { + display: grid; + grid-template-columns: 245px minmax(0, 1fr) 190px; + max-width: 1700px; + margin: auto; +} +.sidebar { + padding: 40px 24px; + border-right: 1px solid var(--line); +} +.sidebar nav { + display: flex; + flex-direction: column; + gap: 5px; +} +.sidebar nav a { + cursor: pointer; + color: var(--muted); + padding: 8px 12px; + border-radius: 6px; + text-decoration: none; + font-size: 0.9rem; +} +.sidebar nav a:hover, +.sidebar nav a[aria-current] { + background: #263629; + color: var(--accent); +} +.eyebrow { + font-size: 0.69rem; + letter-spacing: 1.8px; + color: var(--muted); + font-weight: 700; +} +.sidebar .eyebrow { + margin-left: 12px; +} +.sidebar-note { + font-size: 0.8rem; + line-height: 1.8; + color: var(--text); + margin: 45px 12px 0; + padding-top: 20px; + border-top: 1px solid var(--line); +} +.sidebar-note span { + color: var(--muted); +} +main { + min-width: 0; + padding: 42px 48px 24px; +} +h1 { + font-size: 2.8rem; + line-height: 1.15; + letter-spacing: -1.5px; + font-weight: 650; + margin: 10px 0 28px; +} +h2 { + font-size: 1.65rem; + letter-spacing: -0.5px; + margin: 2.3rem 0 1rem; +} +h3 { + margin: 1.8rem 0 0.7rem; +} +h1, +h2, +h3, +h4 { + scroll-margin-top: 24px; +} +p { + margin: 0 0 1.1rem; +} +.documentation { + max-width: 1050px; +} +.documentation h1 { + font-size: 2.5rem; +} +.documentation p, +.documentation li { + color: #c1cec2; +} +.documentation strong { + color: var(--text); +} +.documentation :is(p, li, td) { overflow-wrap: anywhere; } +.documentation li { + margin: 0.4rem 0; +} +.documentation img { + max-width: 100%; +} +.documentation table { + display: block; + overflow: auto; + border-collapse: collapse; + font-size: 0.9rem; + margin: 24px 0; +} +.documentation th, +.documentation td { + padding: 10px 14px; + border: 1px solid var(--line); + text-align: left; +} +.documentation th { + background: var(--panel); +} +code { + font-family: Consolas, SFMono-Regular, monospace; + font-size: 0.86rem; +} +p code, +li code, +td code { + background: #263129; + padding: 2px 5px; + border-radius: 4px; + color: #ceeabb; +} +.code-block { + border: 1px solid var(--line); + border-radius: 8px; + overflow: hidden; + margin: 20px 0; + background: #141c17; +} +.code-language { + display: block; + padding: 7px 16px; + border-bottom: 1px solid var(--line); + font-size: 0.7rem; + letter-spacing: 0.5px; + color: var(--muted); +} +pre { + padding: 17px 20px; + overflow: auto; + line-height: 1.65; + margin: 0; +} +pre .hljs { + background: transparent; +} +blockquote { + border-left: 3px solid var(--accent); + padding-left: 20px; + margin-left: 0; +} +.anchor { + opacity: 0; + font-size: 0.8em; + margin-left: 10px; + text-decoration: none; +} +h1:hover .anchor, +h2:hover .anchor, +h3:hover .anchor, +.anchor:focus { + opacity: 1; +} +.toc { + padding: 46px 20px 20px 0; +} +.toc nav { + display: flex; + flex-direction: column; + gap: 10px; +} +.toc a { + cursor: pointer; + font-size: 0.76rem; + text-decoration: none; + color: var(--muted); +} +footer { + border-top: 1px solid var(--line); + margin-top: 54px; + padding: 22px 0; + color: var(--muted); + font-size: 0.75rem; +} +footer a { + color: var(--muted); +} +.converter-page { + grid-column: 2/4; + padding-right: 40px; +} +.converter-page h1 { + font-size: clamp(2.5rem, 4vw, 4.25rem); + margin: 16px 0 20px; +} +.accent { + color: var(--accent); +} +.lead { + max-width: 700px; + color: var(--muted); + font-size: 1.05rem; +} +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 16px; + margin: 32px 0 20px; +} +.toolbar label { + display: flex; + flex-direction: column; + gap: 6px; + font-size: 0.77rem; + color: var(--muted); +} +select, +button { + font: inherit; + border: 1px solid var(--line); + border-radius: 6px; + color: var(--text); + background: var(--panel); + padding: 9px 14px; + font-size: 0.85rem; +} +select { + min-width: 165px; +} +button { + cursor: pointer; +} +button:hover { + border-color: var(--accent); +} +button:disabled { + opacity: 0.45; + cursor: default; +} +button:focus-visible, +select:focus-visible, +a:focus-visible, +summary:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 3px; +} +.editors { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 18px; +} +.editor-panel { + border: 1px solid var(--line); + border-radius: 9px; + overflow: hidden; + background: #141c17; + min-width: 0; +} +.panel-heading { + height: 58px; + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px; + border-bottom: 1px solid var(--line); + font-size: 0.7rem; + color: var(--muted); + gap: 12px; +} +.panel-heading strong { + font-size: 0.83rem; + color: var(--text); + margin-left: 9px; + font-weight: 500; +} +.panel-heading button { + font-size: 0.72rem; + padding: 4px 9px; +} + +.convert-actions { + display: flex; + align-items: center; + gap: 20px; + margin: 20px 0 34px; +} +.convert-actions p { + margin: 0; + font-size: 0.83rem; + color: var(--muted); + overflow-wrap: anywhere; +} +.primary { + background: var(--accent); + color: #14220f; + font-weight: 650; + border-color: var(--accent); + white-space: nowrap; +} +.primary span { + margin-left: 20px; +} +.convert-actions .error { + color: #ffa89a; +} +.support { + border-top: 1px solid var(--line); + padding-top: 24px; + max-width: 960px; +} +.support h2 { + font-size: 1.2rem; + margin: 0 0 12px; +} +.support p { + color: var(--muted); + font-size: 0.85rem; +} +.skip { + position: absolute; + top: -60px; + left: 12px; + background: var(--accent); + color: #111; + padding: 8px; + z-index: 2; +} +.skip:focus { + top: 10px; +} + +@media (max-width: 1150px) { + .layout { + grid-template-columns: 210px minmax(0, 1fr); + } + .toc { + display: none; + } + .converter-page { + grid-column: 2; + } + main { + padding: 32px; + } + .sidebar { + padding: 28px 15px; + } + .editors { + grid-template-columns: 1fr; + } +} +@media (max-width: 680px) { + header { + height: 70px; + padding: 0 18px; + } + .brand { + font-size: 0.95rem; + } + .logo { + width: 30px; + height: 32px; + font-size: 23px; + margin-right: 8px; + } + .layout { + display: block; + } + .sidebar { + border-right: 0; + border-bottom: 1px solid var(--line); + padding: 14px 18px; + } + .sidebar .eyebrow, + .sidebar-note { + display: none; + } + .sidebar nav { + flex-direction: row; + overflow: auto; + } + .sidebar nav a { + white-space: nowrap; + font-size: 0.8rem; + padding: 6px 10px; + } + main, + .converter-page { + padding: 30px 20px 12px; + } + h1, + .documentation h1 { + font-size: 2rem; + } + .convert-actions { + align-items: start; + flex-direction: column; + gap: 12px; + } + .toolbar { + gap: 10px; + } + .toolbar label { + flex: 1; + } + .toolbar select { + width: 100%; + min-width: 120px; + } + .documentation ul { + padding-left: 22px; + } + pre { + padding: 14px; + } + .anchor { + opacity: 1; + } +} + +/* Documentation hierarchy. Native details retains keyboard support. */ +.nav-scroll { + position: relative; + min-width: 0; +} +.advanced-nav summary { + padding: 8px 12px; + color: var(--muted); + font-size: 0.9rem; + border-radius: 6px; + cursor: pointer; +} +.advanced-nav summary:hover { + color: var(--accent); + background: #263629; +} +.advanced-links { + display: flex; + flex-direction: column; + gap: 5px; + padding-left: 12px; +} +.advanced-nav[open] summary { + margin-bottom: 5px; +} + +/* Locally bundled code editors. Content scrolls inside the panel. */ +.editor-help { + color: var(--muted); + font-size: 0.75rem; + margin: 12px 0 0; +} +.editor-panel { + --editor-height: 390px; +} +.editor-panel:focus-within { + outline: 2px solid var(--accent); + outline-offset: 3px; +} +.code-editor .cm-editor { + height: var(--editor-height); + background: #141c17; + color: #d6ebcd; +} +.code-editor .cm-editor.cm-focused { + outline: none; +} +.code-editor .cm-scroller { + font: + 0.86rem/1.8 Consolas, + SFMono-Regular, + monospace; + overflow: auto; +} +.code-editor .cm-content { + padding: 16px 0; + caret-color: var(--accent); +} +.code-editor .cm-line { + padding: 0 16px; +} +.code-editor .cm-gutters { + background: #141c17; + color: #718575; + border-right: 1px solid var(--line); +} +.code-editor .cm-activeLine { + background: rgb(179 239 145 / 4%); +} +.code-editor .cm-selectionBackground, +.code-editor .cm-focused .cm-selectionBackground, +.code-editor .cm-content ::selection { + background: #355139 !important; +} +.code-editor .cm-cursor { + border-left-color: var(--accent); +} +.code-editor .cm-content:focus-visible { + outline: none; +} +#delphi .cm-content { + cursor: text; +} +@media (min-width: 1500px) { + .editor-panel { + --editor-height: 450px; + } +} +@media (max-width: 1150px) { + .editor-panel { + --editor-height: 280px; + } +} +@media (max-width: 680px) { + .sidebar nav { + align-items: center; + scrollbar-width: thin; + } + .sidebar nav > a, + .advanced-nav { + flex: 0 0 auto; + } + .advanced-nav { + white-space: nowrap; + display: flex; + align-items: center; + } + .advanced-nav::details-content { + display: contents; + } + .advanced-nav:not([open]) .advanced-links { + display: none; + } + .sidebar nav :is(a, summary):focus-visible { + outline-offset: -2px; + } + .advanced-nav summary { + display: inline-block; + margin: 0; + padding: 6px 10px; + font-size: 0.8rem; + } + .advanced-nav summary::before { + content: "▸"; + margin-right: 7px; + } + .advanced-nav[open] summary::before { + content: "▾"; + } + .advanced-nav[open] summary { + margin: 0; + } + .advanced-links { + display: inline-flex; + flex-direction: row; + padding-left: 0; + gap: 5px; + } + .nav-scroll::after { + content: ""; + position: absolute; + inset: 0 0 0 auto; + width: 32px; + background: linear-gradient(to right, transparent, var(--bg)); + opacity: 0; + pointer-events: none; + } + .nav-scroll.has-more::after { + opacity: 1; + } +} + +/* Sticky navigation, anchor feedback and reduced motion. */ +:root { + --header-height: 82px; + --scroll-offset: 106px; +} + +html { + scroll-behavior: smooth; + scroll-padding-top: var(--scroll-offset); +} -/* Keep orientation while reading long guides. */ -:root { --header-height: 82px; --scroll-offset: 106px; } -html { scroll-behavior: smooth; scroll-padding-top: var(--scroll-offset); } header { position: sticky; top: 0; @@ -12,7 +667,9 @@ header { backdrop-filter: blur(16px); box-shadow: 0 6px 24px rgb(0 0 0 / 8%); } -.sidebar, .toc { + +.sidebar, +.toc { position: sticky; top: var(--header-height); align-self: start; @@ -21,16 +678,54 @@ header { scrollbar-width: thin; scrollbar-color: var(--line) transparent; } -.sidebar { min-height: calc(100dvh - var(--header-height)); } -.sidebar nav a, .toc a, button, .back-to-top { - transition: background-color 160ms ease, color 160ms ease, border-color 160ms ease, box-shadow 160ms ease; + +.sidebar { + min-height: calc(100dvh - var(--header-height)); +} + +.sidebar nav a, +.toc a, +button, +.back-to-top { + transition: + background-color 160ms ease, + color 160ms ease, + border-color 160ms ease, + box-shadow 160ms ease; +} + +.toc nav { + gap: 3px; + border-left: 1px solid var(--line); +} + +.toc a { + padding: 7px 10px 7px 14px; + border-left: 2px solid transparent; + margin-left: -1px; + border-radius: 0 5px 5px 0; +} + +.toc a:hover { + background: rgb(179 239 145 / 5%); + color: var(--text); +} + +.toc a[aria-current="location"] { + color: var(--accent); + border-left-color: var(--accent); + background: rgb(179 239 145 / 7%); +} + +main { + animation: page-arrive 260ms ease-out both; } -.toc nav { gap: 3px; border-left: 1px solid var(--line); } -.toc a { padding: 7px 10px 7px 14px; border-left: 2px solid transparent; margin-left: -1px; border-radius: 0 5px 5px 0; } -.toc a:hover { background: rgb(179 239 145 / 5%); color: var(--text); } -.toc a[aria-current="location"] { color: var(--accent); border-left-color: var(--accent); background: rgb(179 239 145 / 7%); } -main { animation: page-arrive 260ms ease-out both; } -.documentation :is(h1,h2,h3,h4):target { animation: section-arrive 900ms ease-out; border-radius: 6px; } + +.documentation :is(h1, h2, h3, h4):target { + animation: section-arrive 900ms ease-out; + border-radius: 6px; +} + .back-to-top { position: fixed; right: 28px; @@ -47,22 +742,89 @@ main { animation: page-arrive 260ms ease-out both; } box-shadow: 0 8px 28px rgb(0 0 0 / 25%); color: var(--accent); text-decoration: none; - font-size: .8rem; + font-size: 0.8rem; animation: page-arrive 180ms ease-out; } -.back-to-top[hidden] { display: none; } -.back-to-top span { font-size: 1.1rem; line-height: 1; } -.back-to-top:hover { background: #30452d; border-color: var(--accent); box-shadow: 0 8px 28px rgb(0 0 0 / 35%); } -.skip { position: fixed; z-index: 20; } -@keyframes page-arrive { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } } -@keyframes section-arrive { from { background: rgb(179 239 145 / 16%); box-shadow: 0 0 0 8px rgb(179 239 145 / 8%); } to { background: transparent; box-shadow: 0 0 0 8px transparent; } } -@media(max-width:680px) { - :root { --header-height: 70px; --scroll-offset: 150px; } - .sidebar { min-height: 0; max-height: none; overflow: visible; z-index: 9; background: rgb(17 23 20 / 96%); backdrop-filter: blur(12px); } - .back-to-top { right: 18px; bottom: 18px; padding: 9px 13px; } -} -@media(prefers-reduced-motion:reduce) { - html { scroll-behavior: auto; } - main, .documentation :is(h1,h2,h3,h4):target, .back-to-top { animation: none; } - .sidebar nav a, .toc a, button, .back-to-top { transition: none; } + +.back-to-top[hidden] { + display: none; +} + +.back-to-top span { + font-size: 1.1rem; + line-height: 1; +} + +.back-to-top:hover { + background: #30452d; + border-color: var(--accent); + box-shadow: 0 8px 28px rgb(0 0 0 / 35%); +} + +.skip { + position: fixed; + z-index: 20; +} + +@keyframes page-arrive { + from { + opacity: 0; + transform: translateY(6px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +@keyframes section-arrive { + from { + background: rgb(179 239 145 / 16%); + box-shadow: 0 0 0 8px rgb(179 239 145 / 8%); + } + to { + background: transparent; + box-shadow: 0 0 0 8px transparent; + } +} + +@media (max-width: 680px) { + :root { + --header-height: 70px; + --scroll-offset: 150px; + } + + .sidebar { + min-height: 0; + max-height: none; + overflow: visible; + z-index: 9; + background: rgb(17 23 20 / 96%); + backdrop-filter: blur(12px); + } + + .back-to-top { + right: 18px; + bottom: 18px; + padding: 9px 13px; + } +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + + main, + .documentation :is(h1, h2, h3, h4):target, + .back-to-top { + animation: none; + } + + .sidebar nav a, + .toc a, + button, + .back-to-top { + transition: none; + } } diff --git a/website/test/browser/website.spec.mjs b/website/test/browser/website.spec.mjs new file mode 100644 index 0000000..36cfc7b --- /dev/null +++ b/website/test/browser/website.spec.mjs @@ -0,0 +1,130 @@ +import { test, expect } from '@playwright/test'; + +test('editors highlight, edit, invalidate, convert, remain read-only and copy', async ({ page, context }) => { + const errors = []; + const externalRequests = []; + page.on('pageerror', error => errors.push(error.message)); + page.on('request', request => { if (!request.url().startsWith('http://127.0.0.1:4174/')) externalRequests.push(request.url()); }); + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + await page.goto('converter.html'); + const input = page.getByRole('textbox', { name: 'SQL input', exact: true }); + const output = page.getByRole('textbox', { name: 'Generated Delphi code' }); + const copy = page.getByRole('button', { name: 'Copy code' }); + await expect(output).toContainText('function BuildQuery'); + await expect(input.locator('span').first()).toBeVisible(); + await expect(output.locator('span').first()).toBeVisible(); + await expect(output).toHaveAttribute('contenteditable', 'false'); + await expect(output).toHaveAttribute('aria-readonly', 'true'); + const generated = await output.innerText(); + await output.focus(); + await page.keyboard.type('must not edit'); + expect(await output.innerText()).toBe(generated); + await copy.click(); + await expect(page.getByRole('status')).toHaveText('Delphi code copied.'); + expect(await page.evaluate(() => navigator.clipboard.readText())).toContain('function BuildQuery'); + await input.fill("SELECT *\nFROM test\nWHERE a LIKE 'foo%'"); + await expect(output).toHaveText(''); + await expect(copy).toBeDisabled(); + await input.press('Control+Enter'); + await expect(output).toContainText("WhereStarts('a', 'foo')"); + await page.getByLabel('Input dialect').selectOption('PostgreSQL'); + await expect(output).toHaveText(''); + await page.getByRole('button', { name: 'Convert to Delphi' }).click(); + await expect(output).toContainText('BuildQuery'); + await input.fill('DELETE FROM test'); + await input.press('Control+Enter'); + await expect(page.getByRole('status')).toHaveClass('error'); + await expect(copy).toBeDisabled(); + await page.getByRole('button', { name: 'Load example' }).click(); + await expect(input).toContainText('SELECT'); + await input.press('Control+End'); + await input.press('Enter'); + await input.press('Tab'); + await expect(input).toBeFocused(); + await input.press('Escape'); + await input.press('Tab'); + await expect(input).not.toBeFocused(); + expect(errors).toEqual([]); + expect(externalRequests).toEqual([]); +}); + +test('copy fallback selects the read-only output', async ({ page }) => { + await page.addInitScript(() => Object.defineProperty(navigator, 'clipboard', { value: { writeText: () => Promise.reject(new Error('denied')) } })); + await page.goto('converter.html'); + await page.getByRole('button', { name: 'Copy code' }).click(); + await expect(page.getByRole('status')).toContainText('Ctrl+C'); + await expect(page.getByRole('textbox', { name: 'Generated Delphi code' })).toBeFocused(); + expect(await page.evaluate(() => getSelection().toString())).toContain('function BuildQuery'); +}); + +test('navigation has one active page and a keyboard-accessible Advanced group', async ({ page }) => { + await page.goto('index.html'); + const nav = page.getByRole('navigation', { name: 'Documentation', exact: true }); + await expect(nav.locator('[aria-current="page"]')).toHaveText('Overview'); + await expect(nav.locator('details')).not.toHaveAttribute('open'); + const summary = nav.locator('summary'); + await summary.focus(); + await summary.press('Enter'); + await expect(summary).toHaveAttribute('aria-expanded', 'true'); + await nav.getByRole('link', { name: 'Porting', exact: true }).click(); + await expect(nav.locator('details')).toHaveAttribute('open', ''); + await expect(nav.locator('[aria-current="page"]')).toHaveText('Porting'); + await expect(nav.locator('summary')).toHaveAttribute('aria-expanded', 'true'); +}); + +for (const width of [1920, 1366, 768, 320, 375, 390]) { + test(`layout and navigation at ${width}px under the Pages subpath`, async ({ page }) => { + await page.setViewportSize({ width, height: 900 }); + await page.goto('docs/WEBSITE.html'); + const nav = page.getByRole('navigation', { name: 'Documentation', exact: true }); + const active = nav.locator('[aria-current="page"]'); + await expect(active).toHaveText('Website maintenance'); + await expect(nav.locator('details')).toHaveAttribute('open', ''); + const overflow = await page.evaluate(() => [...document.querySelectorAll('header,main,main p, main code')].filter(el => el.getBoundingClientRect().right > innerWidth).map(el => `${el.tagName}: ${el.textContent.slice(0,80)}`)); + expect(overflow).toEqual([]); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + if (width <= 680) { + const bounds = await active.boundingBox(); + expect(bounds.x).toBeGreaterThanOrEqual(0); + expect(bounds.x + bounds.width).toBeLessThanOrEqual(width); + await nav.evaluate(node => { node.scrollLeft = 0; }); + await expect(page.locator('.nav-scroll')).toHaveClass(/has-more/); + await nav.evaluate(node => { node.scrollLeft = node.scrollWidth; }); + await expect(page.locator('.nav-scroll')).not.toHaveClass(/has-more/); + const sidebar = await page.locator('.sidebar').boundingBox(); + const main = await page.locator('main').boundingBox(); + expect(main.y).toBeGreaterThanOrEqual(sidebar.y + sidebar.height); + } + await page.goto('converter.html'); + await expect(page.getByRole('textbox', { name: 'Generated Delphi code' })).toContainText('BuildQuery'); + const panels = await page.locator('.editor-panel').all(); + const first = await panels[0].boundingBox(), second = await panels[1].boundingBox(); + if (width > 1150) expect(second.x).toBeGreaterThan(first.x + first.width); + else expect(second.y).toBeGreaterThan(first.y + first.height); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + if (width <= 680) { + const before = await nav.boundingBox(); + const summary = nav.locator('summary'); + await summary.focus(); + await summary.press('Enter'); + await expect(summary).toHaveAttribute('aria-expanded', 'true'); + expect((await nav.boundingBox()).height).toBe(before.height); + await nav.evaluate(node => { node.scrollLeft = node.scrollWidth; }); + const lastLink = nav.getByRole('link', { name: 'Website maintenance' }); + const lastBounds = await lastLink.boundingBox(); + expect(lastBounds.x).toBeGreaterThanOrEqual(0); + expect(lastBounds.x + lastBounds.width).toBeLessThanOrEqual(width); + } + await page.locator('main').evaluate(el => Promise.all(el.getAnimations().map(animation => animation.finished))); + await page.screenshot({ path: `test-results/converter-${width}.png`, fullPage: true }); + }); +} + +test('reduced motion and editor keyboard focus', async ({ page }) => { + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.goto('converter.html'); + expect(await page.locator('html').evaluate(el => getComputedStyle(el).scrollBehavior)).toBe('auto'); + expect(await page.locator('main').evaluate(el => getComputedStyle(el).animationName)).toBe('none'); + await page.getByRole('textbox', { name: 'SQL input', exact: true }).focus(); + expect(await page.locator('.editor-panel').first().evaluate(el => getComputedStyle(el).outlineStyle)).toBe('solid'); +}); diff --git a/website/test/delphi-tokens.test.mjs b/website/test/delphi-tokens.test.mjs new file mode 100644 index 0000000..deb1a2f --- /dev/null +++ b/website/test/delphi-tokens.test.mjs @@ -0,0 +1,32 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { StringStream } from '@codemirror/language'; +import { delphiTokens } from '../delphi-tokens.mjs'; + +function tokenize(source) { + const state = delphiTokens.startState(), tokens = []; + for (const line of source.split('\n')) { + const stream = new StringStream(line, 2, 2); + while (!stream.eol()) { + stream.start = stream.pos; + const type = delphiTokens.token(stream, state); + assert.ok(stream.pos > stream.start); + if (type) tokens.push([stream.current(), type]); + } + } + return tokens; +} + +test('Delphi highlighting recognizes generated syntax, types and generic calls', () => { + const tokens = tokenize("function BuildQuery: IQuery;\nbegin\n Result := TValue.From(42);\nend;"); + for (const token of [['function', 'keyword'], ['IQuery', 'typeName'], ['TValue', 'typeName'], ['From', 'variableName.function'], ['Int64', 'typeName'], [':=', 'operator'], ['42', 'number']]) assert.ok(tokens.some(t => t[0] === token[0] && t[1] === token[1]), token.join(':')); +}); +test('Delphi strings include doubled quotes and character codes', () => { + const tokens = tokenize("'O''Reilly'#10#$0D"); + assert.deepEqual(tokens, [["'O''Reilly'", 'string'], ['#10', 'string'], ['#$0D', 'string']]); +}); +test('Delphi comments retain state across lines and end correctly', () => { + const tokens = tokenize('// line\n{ brace\n comment } begin (* block\n comment *) end'); + assert.ok(tokens.filter(t => t[1] === 'comment').length >= 5); + assert.deepEqual(tokens.filter(t => t[1] === 'keyword'), [['begin', 'keyword'], ['end', 'keyword']]); +});