Merge pull request #212 from poli0981/fix/sonarcloud

fix(quality): clear the 44 open SonarCloud issues
This commit is contained in:
poli0981 authored and GitHub committed 2026-10-22 15:09:24 +07:00
commit e33462b462
28 files changed
+162 -92

No files matched your search

+5 -2
View File
@@ -35,7 +35,10 @@ jobs:
with:
node-version-file: .node-version
cache: npm
- run: npm ci
# No dependency lifecycle scripts, in every workflow. The only packages
# that have one (esbuild, workerd, fsevents) take their native binary
# from optionalDependencies; the script only double-checks it.
- run: npm ci --ignore-scripts
# `tsc` must be TypeScript 7 (@typescript/native). The `typescript` alias
# (@typescript/typescript6, the API typescript-eslint loads) pulls in
# TypeScript 6 as @typescript/old, which ships a `tsc` too — npm links the
@@ -100,4 +103,4 @@ jobs:
# Validates wrangler.jsonc and bundles the Worker exactly as Workers
# Builds will — without deploying anything.
- name: Dry-run the Cloudflare deploy
run: npx wrangler deploy --dry-run --outdir .wrangler/dry-run
run: npm run cf:check
+2 -3
View File
@@ -29,7 +29,7 @@ jobs:
# Release artifacts are built from a clean install: a cache written
# by any other workflow must not be able to feed into them.
package-manager-cache: false
- run: npm ci
- run: npm ci --ignore-scripts
- run: npm run typecheck
- run: npm run test:run
- run: npm run check:version
@@ -79,8 +79,7 @@ jobs:
toolchain: stable
targets: aarch64-linux-android,armv7-linux-androideabi,i686-linux-android,x86_64-linux-android
- run: npm ci
- run: npm ci --ignore-scripts
- name: Install Tauri CLI
run: cargo install tauri-cli --version "^2" --locked
+2 -2
View File
@@ -33,7 +33,7 @@ jobs:
# Release artifacts are built from a clean install: a cache written
# by any other workflow must not be able to feed into them.
package-manager-cache: false
- run: npm ci
- run: npm ci --ignore-scripts
- run: npm run typecheck
- run: npm run test:run
- run: npm run check:version
@@ -114,7 +114,7 @@ jobs:
libayatana-appindicator3-dev \
librsvg2-dev \
patchelf
- run: npm ci
- run: npm ci --ignore-scripts
- uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -52,7 +52,7 @@ jobs:
with:
node-version-file: .node-version
cache: npm
- run: npm ci
- run: npm ci --ignore-scripts
- run: npm run build
- name: rustfmt
working-directory: src-tauri
+15 -8
View File
@@ -79,17 +79,24 @@ export function rewriteHref(href: string, fromFile: string): string {
* hyphen, which also rules out any markup ending up in an attribute.
*/
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, "-")
.replace(/^-+|-+$/g, "");
return (
text
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, "-")
// The line above leaves at most one hyphen in a row.
.replace(/^-|-$/g, "")
);
}
function stripInlineMarkdown(text: string): string {
return text
.replace(/[`*_~]/g, "")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.trim();
return (
text
.replace(/[`*_~]/g, "")
// Neither part may contain `[`, so a failed match is never re-scanned
// from a later `[` inside it (linear even on unbalanced brackets).
.replace(/\[([^[\]]+)\]\([^)[]*\)/g, "$1")
.trim()
);
}
export function renderMarkdown(source: string, fromFile: string): { title: string; html: string } {
+4 -4
View File
@@ -58,10 +58,10 @@ function readRepoFile(file: string): string {
/** The year HEAD was committed, or this UTC year when git is unavailable. */
export function headCommitYear(): number {
try {
const iso = execFileSync("git", ["log", "-1", "--format=%cI"], {
cwd: ROOT,
encoding: "utf8",
});
const options = { cwd: ROOT, encoding: "utf8" } as const;
// A dev/CI script: `git` is whichever one the developer's PATH or the CI
// image provides, by design — there is no fixed install path to pin.
const iso = execFileSync("git", ["log", "-1", "--format=%cI"], options); // NOSONAR
const year = Number(iso.trim().slice(0, 4));
if (Number.isInteger(year) && year >= 2000) return year;
} catch {
+4 -3
View File
@@ -38,8 +38,9 @@ const ALLOWED = new Set([
/** SPDX expression → allowed? `OR` needs one side, `AND` needs both. */
export function licenseAllowed(expression: string): boolean {
const expr = expression.trim().replace(/^\((.*)\)$/, "$1");
if (/\sOR\s/i.test(expr)) return expr.split(/\s+OR\s+/i).some(licenseAllowed);
if (/\sAND\s/i.test(expr)) return expr.split(/\s+AND\s+/i).every(licenseAllowed);
// Split on the bare operator; each part is trimmed by the recursive call.
if (/\sOR\s/i.test(expr)) return expr.split(/\sOR\s/i).some(licenseAllowed);
if (/\sAND\s/i.test(expr)) return expr.split(/\sAND\s/i).every(licenseAllowed);
return ALLOWED.has(expr);
}
@@ -110,7 +111,7 @@ export function directCrates(toml: string): string[] {
const name = inDependencies ? /^([A-Za-z0-9_-]+)\s*=/.exec(line)?.[1] : undefined;
if (name) names.add(name);
}
return [...names].sort();
return [...names].sort(compareCodeUnits);
}
/**
@@ -5,7 +5,11 @@
<!-- AndroidTV support -->
<uses-feature android:name="android.software.leanback" android:required="false" />
<!-- allowBackup="false": the app's data (localStorage in the WebView) stays
on the device and is never copied to Google Drive backups. Users move
it to a new phone with the app's own Backup & Restore file. -->
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.yt_desc_gen"
+11 -9
View File
@@ -55,21 +55,23 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
// Best-effort: pull the in-app logger lazily so the boundary stays
// importable from non-React entry points. We never let the logger
// itself throw a secondary error — if the log store is missing we
// fall back to the browser console.
try {
// Dynamic import dodges a circular dep with files that themselves
// import ErrorBoundary, e.g. when the boundary is mounted in
// main.tsx before the store has registered.
void import("@utils/logger").then(({ logger }) => {
// fall back to the browser console. (A try/catch could not catch
// that: the import rejects asynchronously.)
//
// Dynamic import dodges a circular dep with files that themselves
// import ErrorBoundary, e.g. when the boundary is mounted in
// main.tsx before the store has registered.
void import("@utils/logger")
.then(({ logger }) => {
logger.error(
"errorBoundary",
`[${this.props.label ?? "app"}] ${error.message}`,
info.componentStack ?? error.stack ?? "",
);
})
.catch(() => {
console.error("ErrorBoundary caught:", error, info);
});
} catch {
console.error("ErrorBoundary caught:", error, info);
}
this.props.onError?.(error, info);
}
+16 -1
View File
@@ -1,4 +1,4 @@
import type { ReactNode } from "react";
import type { ReactNode, RefObject } from "react";
import { useTranslation } from "react-i18next";
import { Dialog, VisuallyHidden } from "radix-ui";
import { X } from "lucide-react";
@@ -15,6 +15,12 @@ interface ModalProps {
/** Max width: sm 24rem · md 32rem (default) · lg 42rem · xl 56rem. */
size?: "sm" | "md" | "lg" | "xl";
className?: string;
/**
* Where focus lands when the dialog opens. Without it, Radix focuses the
* first focusable element (the close button). Use this instead of an
* `autoFocus` attribute on the target.
*/
initialFocusRef?: RefObject<HTMLElement | null>;
}
const SIZES = { sm: "max-w-sm", md: "max-w-lg", lg: "max-w-2xl", xl: "max-w-4xl" } as const;
@@ -34,6 +40,7 @@ export function Modal({
footer,
size = "md",
className,
initialFocusRef,
}: ModalProps) {
const { t } = useTranslation("ui");
return (
@@ -41,6 +48,14 @@ export function Modal({
<Dialog.Portal>
<Dialog.Overlay className="bg-overlay animate-fade-in fixed inset-0 z-50 backdrop-blur-[2px]" />
<Dialog.Content
onOpenAutoFocus={
initialFocusRef
? (event) => {
event.preventDefault();
initialFocusRef.current?.focus();
}
: undefined
}
className={clsx(
"bg-surface-1 border-border shadow-pop animate-pop-in rounded-panel fixed top-1/2 left-1/2 z-50 flex max-h-[min(88dvh,52rem)] w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col border",
"focus:outline-none",
+12 -3
View File
@@ -1,4 +1,4 @@
import { useMemo, useState } from "react";
import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Search } from "lucide-react";
import { Modal } from "./Modal";
@@ -24,6 +24,9 @@ const SHORTCUTS = [
export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) {
const { t } = useTranslation("ui");
const [query, setQuery] = useState("");
// The search box gets focus when the modal opens (through Radix, not an
// `autoFocus` attribute).
const searchRef = useRef<HTMLInputElement>(null);
// A closed modal has no filter. Deriving this rather than resetting `query`
// in an effect means a re-open always starts fresh without an extra render
@@ -41,18 +44,24 @@ export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) {
}, [activeQuery, t]);
return (
<Modal open={open} onClose={onClose} title={t("shortcuts.title")} size="sm">
<Modal
open={open}
onClose={onClose}
title={t("shortcuts.title")}
size="sm"
initialFocusRef={searchRef}
>
<div className="flex flex-col gap-3">
<label className="border-border bg-surface-0 focus-within:border-accent focus-within:ring-accent/25 h-control rounded-control flex items-center gap-2 border px-3 transition-colors focus-within:ring-2">
<Search className="text-text-muted size-4 shrink-0" aria-hidden="true" />
<input
ref={searchRef}
type="search"
value={activeQuery}
onChange={(e) => setQuery(e.target.value)}
placeholder={t("shortcuts.searchPlaceholder")}
aria-label={t("shortcuts.searchPlaceholder")}
className="text-text-primary placeholder:text-text-muted w-full bg-transparent text-sm outline-none"
autoFocus
/>
</label>
{filtered.length === 0 ? (
+5 -2
View File
@@ -140,8 +140,11 @@ export const PLATFORMS: readonly PlatformConfig[] = [
tagName: "Android",
label: "Google Play",
urlPrefix: "https://play.google.com/store/apps/details?id=",
// `id=` first or after other parameters (`?hl=en&id=…`).
urlPattern: /^https:\/\/play\.google\.com\/store\/apps\/details\?(?:[^\s]*&)?id=[\w.]+[^\s]*$/i,
// `id=` first or after other parameters (`?hl=en&id=…`). The lookahead
// finds the parameter (each `&`-separated step is unambiguous), then one
// `\S*$` scan checks the rest — linear, where `[^\s]*&` + `[^\s]*$` was not.
urlPattern:
/^https:\/\/play\.google\.com\/store\/apps\/details\?(?=(?:[^\s&]*&)*id=[\w.])\S*$/i,
},
{
id: "appstore",
+14 -9
View File
@@ -461,15 +461,20 @@ export const CPU_SUGGESTIONS: readonly string[] = [
* Text it doesn't recognise is only trimmed and de-duplicated of spaces.
*/
export function cleanCpuName(raw: string): string {
return raw
.replace(/\((?:R|TM|C)\)|[®™©]/gi, "")
.replace(/^\s*\d{1,2}(?:st|nd|rd|th)\s+Gen\s+/i, "")
.replace(/\s+CPU\s*@\s*[\d.]+\s*[GM]Hz\b/i, "")
.replace(/\s+@\s*[\d.]+\s*[GM]Hz\b/i, "")
.replace(/\s+\d{1,3}-Core\s+Processor\b/i, "")
.replace(/\s+(?:with\s+Radeon(?:\s+\w+)?\s+Graphics|Processor)\s*$/i, "")
.replace(/\s{2,}/g, " ")
.trim();
return (
raw
.replace(/\((?:R|TM|C)\)|[®™©]/gi, "")
// From here on every whitespace run is a single character, so the
// patterns below need only `\s` / `\s?`. A leading `\s+` would be
// re-tried at every position of a long run (quadratic).
.replace(/\s{2,}/g, " ")
.replace(/^\s*\d{1,2}(?:st|nd|rd|th)\s+Gen\s+/i, "")
.replace(/\sCPU\s?@\s?[\d.]+\s?[GM]Hz\b/i, "")
.replace(/\s@\s?[\d.]+\s?[GM]Hz\b/i, "")
.replace(/\s\d{1,3}-Core\sProcessor\b/i, "")
.replace(/\s(?:with\sRadeon(?:\s\w+)?\sGraphics|Processor)\s?$/i, "")
.trim()
);
}
/**
+3 -1
View File
@@ -58,5 +58,7 @@ export function withoutEmptyChannel(text: string, language: SupportedLanguage):
let out = text;
for (const pattern of [...DROP[language], ENGLISH]) out = out.replace(pattern, "");
out = out.split(CHANNEL_SLOT).join(FALLBACK[language]);
return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+([.,!?。!?])/g, "$1");
// After the first replace no run of spaces/tabs is longer than one, so the
// second needs no `+` (which would make it quadratic on long runs).
return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]([.,!?。!?])/g, "$1");
}
+6 -2
View File
@@ -26,8 +26,12 @@ export function youtubeTagsLength(tags: readonly string[]): number {
*/
const COMPOSITE_NAME_BUDGET = YT_LIMITS.SINGLE_TAG_MAX - 9;
// The match may only start right before a run of `:`/whitespace (or at the
// start), never inside one — a leading `[:\s]+` alone would be re-tried at
// every position of a long run (quadratic). Group 1 keeps the character before
// the run; the caller puts it back with "$1".
const QUALIFIER_SUFFIX_RE =
/[:\s]+(?:Definitive|Complete|Collector'?s?|Deluxe|Game\s+of\s+the\s+Year|GOTY|Ultimate|Special|Anniversary|Remastered|Remake|Enhanced|HD)(?:\s+(?:Edition|Cut|Version))?\s*$/i;
/(^|[^:\s])[:\s]+(?:Definitive|Complete|Collector'?s?|Deluxe|Game\s+of\s+the\s+Year|GOTY|Ultimate|Special|Anniversary|Remastered|Remake|Enhanced|HD)(?:\s+(?:Edition|Cut|Version))?\s*$/i;
/**
* Strips characters that YouTube treats as tag delimiters (`,` `;` `|`) plus
@@ -57,7 +61,7 @@ export function tagFriendlyGameName(name: string, budget: number): string {
let prev: string;
do {
prev = n;
n = n.replace(QUALIFIER_SUFFIX_RE, "").trim();
n = n.replace(QUALIFIER_SUFFIX_RE, "$1").trim();
} while (n !== prev);
if (n.length <= budget) return n;
+8 -4
View File
@@ -25,9 +25,13 @@ export interface TimelineEntry {
* frames `:FF` dropped, as editors export them), an optional `]` / `)`,
* an optional separator (`-`, `–`, `—`, `:`, `|`, `•`) and the label.
* "[0:00] Intro", "0:00 - Intro" and "00:00:00:12 Intro" all parse.
*
* Match it against `line.trimEnd()`: the label runs to the end of the line,
* and trimming first (rather than a lazy label + `\s*$`) keeps the match
* linear on long runs of spaces.
*/
const LINE_RE =
/^\s*[[(]?((?:\d{1,2}:)?\d{1,2}:\d{2})(?::\d{2})?[\])]?\s*(?:[-–—:|•·]\s*)?(\S.*?)\s*$/u;
/^\s*[[(]?((?:\d{1,2}:)?\d{1,2}:\d{2})(?::\d{2})?[\])]?\s*(?:[-–—:|•·]\s*)?(\S.*)$/u;
// Keyword patterns. Order matters — "final boss" must be tried before "boss".
// Each regex captures the optional number group when applicable.
@@ -128,7 +132,7 @@ export function parseTimeline(raw: string): TimelineEntry[] {
for (const line of lines) {
if (!line.trim()) continue;
const lineMatch = line.match(LINE_RE);
const lineMatch = LINE_RE.exec(line.trimEnd());
if (!lineMatch) {
// Not a `time label` line — keep the raw text so nothing disappears.
entries.push({ time: "", rawLabel: line.trim() });
@@ -152,7 +156,7 @@ export function parseTimeline(raw: string): TimelineEntry[] {
for (let i = 1; i < m.length - 1; i++) {
const g = m[i];
if (g && /^\d+$/.test(g)) {
entry.number = parseInt(g, 10);
entry.number = Number.parseInt(g, 10);
break;
}
}
@@ -200,7 +204,7 @@ export function renderTimeline(
// Collapse the trailing whitespace that creeps in when a numbered
// keyword pattern (`"Boss {{n}}"`) interpolates with an empty `n`.
const translated = t(`timeline.keywords.${entry.keyword}`, { n: numberVar })
.replace(/\s+$/u, "")
.trimEnd()
.replace(/\s{2,}/gu, " ");
const withRest = entry.rest ? `${translated} ${entry.rest}` : translated;
rendered.push(`${entry.time} ${withRest}`);
+2 -1
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { ensureLanguagesLoaded, hasLanguageBundles } from "@i18n/index";
import type { SupportedLanguage } from "@engine/types";
import { compareCodeUnits } from "@utils/sort";
/**
* Returns true once every requested language has its locale bundles in
@@ -17,7 +18,7 @@ export function useLanguagesReady(langs: readonly SupportedLanguage[]): boolean
// Stable identity for the requested set — callers pass fresh array
// literals on every render.
const key = useMemo(
() => [...new Set(joined ? joined.split(",") : [])].sort().join(","),
() => [...new Set(joined ? joined.split(",") : [])].sort(compareCodeUnits).join(","),
[joined],
);
const [readyKey, setReadyKey] = useState<string | null>(() =>
+2 -2
View File
@@ -101,8 +101,8 @@ export function BatchPage() {
: t(rangeResult.error ?? "", rangeResult.errorParams);
const generate = () => {
const start = parseInt(startPart) || 1;
const end = parseInt(endPart) || start;
const start = Number.parseInt(startPart) || 1;
const end = Number.parseInt(endPart) || start;
const outputs: BatchResult[] = [];
for (let i = start; i <= Math.min(end, start + 99); i++) {
+3 -1
View File
@@ -141,7 +141,9 @@ export function PlaylistPage() {
status,
contentType,
totalVideos:
totalVideosValidation.valid && totalVideos.trim() ? parseInt(totalVideos) : undefined,
totalVideosValidation.valid && totalVideos.trim()
? Number.parseInt(totalVideos)
: undefined,
storeLinks: editor.storeLinks,
playlistNote: customNote,
droppedReasons,
+2 -2
View File
@@ -155,8 +155,8 @@ export function SocialPage() {
};
const bulkGenerate = () => {
const start = parseInt(startPart) || 1;
const end = parseInt(endPart) || start;
const start = Number.parseInt(startPart) || 1;
const end = Number.parseInt(endPart) || start;
const rows: BulkRow[] = [];
// Loop-invariant English translator for the bilingual content-warnings
// block — `en` is eagerly bundled, so it needs no readiness gate.
+5 -3
View File
@@ -930,11 +930,13 @@ export function liftLegacyEndingString(raw: string): EndingEntry[] {
// Match optional "Ending" prefix + number + optional ": rest" tail.
// Case-insensitive on the keyword; localised variants ("kết thúc",
// "エンディング", "结局") are accepted too. Anything else → name-only.
const m = trimmed.match(
/^(?:ending|kết\s+thúc|エンディング|final|엔딩|结局)\s*(\d+)\s*(?::\s*(.+))?\s*$/i,
// `trimmed` has no trailing whitespace, so the pattern needs no `\s*$`; and
// no two `\s*` sit next to each other, which would backtrack quadratically.
const m = /^(?:ending|kết\s+thúc|エンディング|final|엔딩|结局)\s*(\d+)(?:\s*:\s*(\S.*))?$/i.exec(
trimmed,
);
if (m) {
const num = parseInt(m[1] ?? "", 10);
const num = Number.parseInt(m[1] ?? "", 10);
const name = (m[2] ?? "").trim();
if (Number.isFinite(num)) {
return [{ number: num, name }];
+4 -2
View File
@@ -74,7 +74,7 @@ export function migrateProfilesState(persistedState: unknown, version: number):
if (!persistedState || typeof persistedState !== "object") return persistedState;
const state = persistedState as { profiles?: Array<Record<string, unknown>> };
if (!Array.isArray(state.profiles)) return persistedState;
state.profiles = state.profiles.map((p) => {
const profiles = state.profiles.map((p) => {
if (!p || typeof p !== "object") return p;
let next = p;
if (version < 1 && typeof next.thirdPartyAdText !== "string") {
@@ -90,7 +90,9 @@ export function migrateProfilesState(persistedState: unknown, version: number):
if (version < 3) next = { ...next, rig: migrateRig(next.rig) };
return next;
});
return persistedState;
// A new object rather than the mutated input: both callers (persist and
// backup restore) use the return value.
return { ...state, profiles };
}
export const useProfileStore = create<ProfileState>()(
+3 -3
View File
@@ -50,9 +50,9 @@ function parseFileDate(name: string): Date | null {
}
const datePart = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length);
if (!/^\d{8}$/.test(datePart)) return null;
const y = parseInt(datePart.slice(0, 4), 10);
const m = parseInt(datePart.slice(4, 6), 10) - 1;
const d = parseInt(datePart.slice(6, 8), 10);
const y = Number.parseInt(datePart.slice(0, 4), 10);
const m = Number.parseInt(datePart.slice(4, 6), 10) - 1;
const d = Number.parseInt(datePart.slice(6, 8), 10);
return new Date(y, m, d);
}
+9 -16
View File
@@ -1,28 +1,21 @@
/**
* Generate a RFC 4122 v4 UUID.
*
* `crypto.randomUUID()` is the fast path, but it only exists in Chrome/WebView
* **92+** — older Android System WebViews (e.g. the Chromium 91 that ships with
* some emulator images, or any device whose WebView hasn't been updated) don't
* have it. Because `generateId()` runs at module load (e.g. the log store's
* `CURRENT_SESSION_ID`), an unguarded `crypto.randomUUID()` would throw during
* boot and black-screen the whole app on those WebViews. Fall back to a manual
* v4 built on `crypto.getRandomValues` (present since Chrome 11), and finally
* `Math.random` only if even that is missing.
* `crypto.randomUUID()` is the fast path, but it only exists in secure
* contexts (HTTPS, localhost) and in Chromium 92+. Because `generateId()` runs
* at module load (e.g. the log store's `CURRENT_SESSION_ID`), an unguarded
* call would throw during boot wherever it is missing. Fall back to a v4 built
* on `crypto.getRandomValues`, which every engine the app supports has — and
* never to `Math.random`, which is not a source of unique IDs.
*/
export function generateId(): string {
const c: Crypto | undefined = typeof globalThis !== "undefined" ? globalThis.crypto : undefined;
const c = globalThis.crypto;
if (c && typeof c.randomUUID === "function") {
if (typeof c.randomUUID === "function") {
return c.randomUUID();
}
const bytes = new Uint8Array(16);
if (c && typeof c.getRandomValues === "function") {
c.getRandomValues(bytes);
} else {
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
}
const bytes = c.getRandomValues(new Uint8Array(16));
// RFC 4122 §4.4: set the version (4) and variant (10xx) bits.
// (`?? 0` only satisfies noUncheckedIndexedAccess — index 6/8 always exist.)
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
+2 -1
View File
@@ -1,5 +1,6 @@
import { readFileSync } from "fs";
import { resolve } from "path";
import { compareCodeUnits } from "@utils/sort";
interface LocaleSchema {
ui: Record<string, string[]>;
@@ -17,5 +18,5 @@ export const LOCALE_SCHEMA = JSON.parse(
/** The leaf keys under one parent path, sorted; empty when the path is missing. */
export function schemaKeys(namespace: keyof LocaleSchema, parent: string): string[] {
return [...(LOCALE_SCHEMA[namespace][parent] ?? [])].sort();
return [...(LOCALE_SCHEMA[namespace][parent] ?? [])].sort(compareCodeUnits);
}
+7 -5
View File
@@ -13,9 +13,9 @@ describe("generateId", () => {
expect(generateId()).toMatch(V4);
});
it("falls back to a valid v4 UUID when crypto.randomUUID is missing (Android WebView < 92)", () => {
// Chromium 91 has getRandomValues but not randomUUID — the exact gap that
// black-screened the app at boot before the fallback existed.
it("falls back to a valid v4 UUID when crypto.randomUUID is missing", () => {
// Insecure contexts (and Chromium < 92) have getRandomValues but not
// randomUUID — the gap that once black-screened the app at boot.
const real = globalThis.crypto;
vi.stubGlobal("crypto", {
getRandomValues: (a: Uint8Array<ArrayBuffer>) => real.getRandomValues(a),
@@ -23,9 +23,11 @@ describe("generateId", () => {
expect(generateId()).toMatch(V4);
});
it("falls back to a valid v4 UUID when crypto is entirely absent", () => {
it("refuses to make up an ID when there is no crypto at all", () => {
// No Math.random fallback: an ID that is not random is worse than an
// error. Every engine the app supports has crypto.getRandomValues.
vi.stubGlobal("crypto", undefined);
expect(generateId()).toMatch(V4);
expect(() => generateId()).toThrow(TypeError);
});
it("produces unique values across many calls", () => {
+5 -1
View File
@@ -22,7 +22,11 @@ const KEY_LABEL = "ytg-gate-v1";
function toBase64Url(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
// Base64 pads with at most two `=`; a bounded quantifier stays linear.
return btoa(binary)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/={1,2}$/, "");
}
function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null {
+6 -1
View File
@@ -128,7 +128,12 @@ async function handleVerify(request: Request, env: Env, deps: Deps, url: URL): P
* when the path is not a legal path at all.
*/
export function legalAssetPath(url: URL): string | null {
const trimmed = url.pathname.replace(/\/+$/, "");
// Drop trailing slashes with a loop: `/\/+$/` is re-tried at every slash of
// a long run and goes quadratic on a path like "/legal//////…x".
const path = url.pathname;
let end = path.length;
while (end > 0 && path[end - 1] === "/") end--;
const trimmed = path.slice(0, end);
if (trimmed === "/legal") return "/legal/";
if (!trimmed.startsWith("/legal/")) return null;
const id = /^\/legal\/([a-z-]+)$/.exec(trimmed)?.[1];