This commit is contained in:
2025-05-09 05:30:08 +02:00
parent 7bb10e7df4
commit 73367bad9e
5322 changed files with 1266973 additions and 313 deletions

View File

@@ -0,0 +1,274 @@
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { render } from '@testing-library/react';
import { pdfjs } from '../index.test.js';
import TextLayer from './TextLayer.js';
import failingPage from '../../../../__mocks__/_failing_page.js';
import { loadPDF, makeAsyncCallback, muteConsole, restoreConsole } from '../../../../test-utils.js';
import PageContext from '../PageContext.js';
import type { PDFPageProxy } from 'pdfjs-dist';
import type { TextContent } from 'pdfjs-dist/types/src/display/api.js';
import type { PageContextType } from '../shared/types.js';
const pdfFile = loadPDF('./../../__mocks__/_pdf.pdf');
const untaggedPdfFile = loadPDF('./../../__mocks__/_untagged.pdf');
function renderWithContext(children: React.ReactNode, context: Partial<PageContextType>) {
const { rerender, ...otherResult } = render(
<PageContext.Provider value={context as PageContextType}>{children}</PageContext.Provider>,
);
return {
...otherResult,
rerender: (nextChildren: React.ReactNode, nextContext: Partial<PageContextType> = context) =>
rerender(
<PageContext.Provider value={nextContext as PageContextType}>
{nextChildren}
</PageContext.Provider>,
),
};
}
function getTextItems(container: HTMLElement) {
const wrapper = container.firstElementChild as HTMLDivElement;
return wrapper.querySelectorAll('[role="presentation"]');
}
describe('TextLayer', () => {
// Loaded page
let page: PDFPageProxy;
let page2: PDFPageProxy;
// Loaded page text items
let desiredTextItems: TextContent['items'];
let desiredTextItems2: TextContent['items'];
beforeAll(async () => {
const pdf = await pdfjs.getDocument({ data: pdfFile.arrayBuffer }).promise;
page = await pdf.getPage(1);
const textContent = await page.getTextContent();
desiredTextItems = textContent.items;
page2 = await pdf.getPage(2);
const textContent2 = await page2.getTextContent();
desiredTextItems2 = textContent2.items;
});
describe('loading', () => {
it('loads text content and calls onGetTextSuccess callback properly', async () => {
const { func: onGetTextSuccess, promise: onGetTextSuccessPromise } = makeAsyncCallback();
renderWithContext(<TextLayer />, {
onGetTextSuccess,
page,
});
expect.assertions(1);
await expect(onGetTextSuccessPromise).resolves.toMatchObject([{ items: desiredTextItems }]);
});
it('calls onGetTextError when failed to load text content', async () => {
const { func: onGetTextError, promise: onGetTextErrorPromise } = makeAsyncCallback();
muteConsole();
renderWithContext(<TextLayer />, {
onGetTextError,
page: failingPage,
});
expect.assertions(1);
await expect(onGetTextErrorPromise).resolves.toMatchObject([expect.any(Error)]);
restoreConsole();
});
it('replaces text content properly', async () => {
const { func: onGetTextSuccess, promise: onGetTextSuccessPromise } = makeAsyncCallback();
const { rerender } = renderWithContext(<TextLayer />, {
onGetTextSuccess,
page,
});
expect.assertions(2);
await expect(onGetTextSuccessPromise).resolves.toMatchObject([
{
items: desiredTextItems,
},
]);
const { func: onGetTextSuccess2, promise: onGetTextSuccessPromise2 } = makeAsyncCallback();
rerender(<TextLayer />, {
onGetTextSuccess: onGetTextSuccess2,
page: page2,
});
await expect(onGetTextSuccessPromise2).resolves.toMatchObject([
{
items: desiredTextItems2,
},
]);
});
it('throws an error when placed outside Page', () => {
muteConsole();
expect(() => render(<TextLayer />)).toThrow();
restoreConsole();
});
});
describe('rendering', () => {
it('renders text content properly', async () => {
const { func: onRenderTextLayerSuccess, promise: onRenderTextLayerSuccessPromise } =
makeAsyncCallback();
const { container } = renderWithContext(<TextLayer />, { onRenderTextLayerSuccess, page });
expect.assertions(1);
await onRenderTextLayerSuccessPromise;
const textItems = getTextItems(container);
expect(textItems).toHaveLength(desiredTextItems.length);
});
it('renders text content properly given customTextRenderer', async () => {
const { func: onRenderTextLayerSuccess, promise: onRenderTextLayerSuccessPromise } =
makeAsyncCallback();
const customTextRenderer = vi.fn();
const { container } = renderWithContext(<TextLayer />, {
customTextRenderer,
onRenderTextLayerSuccess,
page,
});
expect.assertions(1);
await onRenderTextLayerSuccessPromise;
const textItems = getTextItems(container);
expect(textItems).toHaveLength(desiredTextItems.length);
});
it('maps textContent items to actual TextLayer children properly', async () => {
const { func: onRenderTextLayerSuccess, promise: onRenderTextLayerSuccessPromise } =
makeAsyncCallback();
const { container, rerender } = renderWithContext(<TextLayer />, {
onRenderTextLayerSuccess,
page,
});
expect.assertions(1);
await onRenderTextLayerSuccessPromise;
const textItems = getTextItems(container);
const { func: onRenderTextLayerSuccess2, promise: onRenderTextLayerSuccessPromise2 } =
makeAsyncCallback();
const customTextRenderer = (item: { str: string }) => item.str;
rerender(<TextLayer />, {
customTextRenderer,
onRenderTextLayerSuccess: onRenderTextLayerSuccess2,
page,
});
await onRenderTextLayerSuccessPromise2;
const textItems2 = getTextItems(container);
expect(textItems).toEqual(textItems2);
});
it('calls customTextRenderer with necessary arguments', async () => {
const { func: onRenderTextLayerSuccess, promise: onRenderTextLayerSuccessPromise } =
makeAsyncCallback();
const customTextRenderer = vi.fn();
const { container } = renderWithContext(<TextLayer />, {
customTextRenderer,
onRenderTextLayerSuccess,
page,
});
expect.assertions(3);
await onRenderTextLayerSuccessPromise;
const textItems = getTextItems(container);
expect(textItems).toHaveLength(desiredTextItems.length);
expect(customTextRenderer).toHaveBeenCalledTimes(desiredTextItems.length);
expect(customTextRenderer).toHaveBeenCalledWith(
expect.objectContaining({
str: expect.any(String),
itemIndex: expect.any(Number),
}),
);
});
it('renders text content properly given customTextRenderer', async () => {
const { func: onRenderTextLayerSuccess, promise: onRenderTextLayerSuccessPromise } =
makeAsyncCallback();
const customTextRenderer = () => 'Test value';
const { container } = renderWithContext(<TextLayer />, {
customTextRenderer,
onRenderTextLayerSuccess,
page,
});
expect.assertions(1);
await onRenderTextLayerSuccessPromise;
expect(container).toHaveTextContent('Test value');
});
it('renders text content properly given customTextRenderer and untagged document', async () => {
const { func: onRenderTextLayerSuccess, promise: onRenderTextLayerSuccessPromise } =
makeAsyncCallback();
const customTextRenderer = () => 'Test value';
const untaggedDoc = await pdfjs.getDocument({ data: untaggedPdfFile.arrayBuffer }).promise;
const untaggedPage = await untaggedDoc.getPage(1);
const { container } = renderWithContext(<TextLayer />, {
customTextRenderer,
onRenderTextLayerSuccess,
page: untaggedPage,
});
expect.assertions(1);
await onRenderTextLayerSuccessPromise;
expect(container).toHaveTextContent('Test value');
});
});
});

View File

@@ -0,0 +1,14 @@
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"lines": 86,
"statements": 85.93,
"functions": 82.43,
"branches": 76.06,
"exclude": [
"coverage",
"example",
"test"
]
}

View File

@@ -0,0 +1,252 @@
/**
* @fileoverview Require spaces around infix operators
* @author Michael Ficarra
* @deprecated in ESLint v8.53.0
*/
"use strict";
const { isEqToken } = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "10.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin-js",
url: "https://eslint.style/packages/js",
},
rule: {
name: "space-infix-ops",
url: "https://eslint.style/rules/js/space-infix-ops",
},
},
],
},
type: "layout",
docs: {
description: "Require spacing around infix operators",
recommended: false,
url: "https://eslint.org/docs/latest/rules/space-infix-ops",
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
int32Hint: {
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
messages: {
missingSpace: "Operator '{{operator}}' must be spaced.",
},
},
create(context) {
const int32Hint = context.options[0]
? context.options[0].int32Hint === true
: false;
const sourceCode = context.sourceCode;
/**
* Returns the first token which violates the rule
* @param {ASTNode} left The left node of the main node
* @param {ASTNode} right The right node of the main node
* @param {string} op The operator of the main node
* @returns {Object} The violator token or null
* @private
*/
function getFirstNonSpacedToken(left, right, op) {
const operator = sourceCode.getFirstTokenBetween(
left,
right,
token => token.value === op,
);
const prev = sourceCode.getTokenBefore(operator);
const next = sourceCode.getTokenAfter(operator);
if (
!sourceCode.isSpaceBetweenTokens(prev, operator) ||
!sourceCode.isSpaceBetweenTokens(operator, next)
) {
return operator;
}
return null;
}
/**
* Reports an AST node as a rule violation
* @param {ASTNode} mainNode The node to report
* @param {Object} culpritToken The token which has a problem
* @returns {void}
* @private
*/
function report(mainNode, culpritToken) {
context.report({
node: mainNode,
loc: culpritToken.loc,
messageId: "missingSpace",
data: {
operator: culpritToken.value,
},
fix(fixer) {
const previousToken =
sourceCode.getTokenBefore(culpritToken);
const afterToken = sourceCode.getTokenAfter(culpritToken);
let fixString = "";
if (culpritToken.range[0] - previousToken.range[1] === 0) {
fixString = " ";
}
fixString += culpritToken.value;
if (afterToken.range[0] - culpritToken.range[1] === 0) {
fixString += " ";
}
return fixer.replaceText(culpritToken, fixString);
},
});
}
/**
* Check if the node is binary then report
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function checkBinary(node) {
const leftNode = node.left.typeAnnotation
? node.left.typeAnnotation
: node.left;
const rightNode = node.right;
// search for = in AssignmentPattern nodes
const operator = node.operator || "=";
const nonSpacedNode = getFirstNonSpacedToken(
leftNode,
rightNode,
operator,
);
if (nonSpacedNode) {
if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) {
report(node, nonSpacedNode);
}
}
}
/**
* Check if the node is conditional
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function checkConditional(node) {
const nonSpacedConsequentNode = getFirstNonSpacedToken(
node.test,
node.consequent,
"?",
);
const nonSpacedAlternateNode = getFirstNonSpacedToken(
node.consequent,
node.alternate,
":",
);
if (nonSpacedConsequentNode) {
report(node, nonSpacedConsequentNode);
}
if (nonSpacedAlternateNode) {
report(node, nonSpacedAlternateNode);
}
}
/**
* Check if the node is a variable
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function checkVar(node) {
const leftNode = node.id.typeAnnotation
? node.id.typeAnnotation
: node.id;
const rightNode = node.init;
if (rightNode) {
const nonSpacedNode = getFirstNonSpacedToken(
leftNode,
rightNode,
"=",
);
if (nonSpacedNode) {
report(node, nonSpacedNode);
}
}
}
return {
AssignmentExpression: checkBinary,
AssignmentPattern: checkBinary,
BinaryExpression: checkBinary,
LogicalExpression: checkBinary,
ConditionalExpression: checkConditional,
VariableDeclarator: checkVar,
PropertyDefinition(node) {
if (!node.value) {
return;
}
/*
* Because of computed properties and type annotations, some
* tokens may exist between `node.key` and `=`.
* Therefore, find the `=` from the right.
*/
const operatorToken = sourceCode.getTokenBefore(
node.value,
isEqToken,
);
const leftToken = sourceCode.getTokenBefore(operatorToken);
const rightToken = sourceCode.getTokenAfter(operatorToken);
if (
!sourceCode.isSpaceBetweenTokens(
leftToken,
operatorToken,
) ||
!sourceCode.isSpaceBetweenTokens(operatorToken, rightToken)
) {
report(node, operatorToken);
}
},
};
},
};

View File

@@ -0,0 +1,36 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Resolver")} Resolver */
/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
/**
* @param {Resolver} resolver resolver
* @param {ResolveRequest} request string
* @returns {string} inner request
*/
module.exports = function getInnerRequest(resolver, request) {
if (
typeof request.__innerRequest === "string" &&
request.__innerRequest_request === request.request &&
request.__innerRequest_relativePath === request.relativePath
)
return request.__innerRequest;
/** @type {string|undefined} */
let innerRequest;
if (request.request) {
innerRequest = request.request;
if (/^\.\.?(?:\/|$)/.test(innerRequest) && request.relativePath) {
innerRequest = resolver.join(request.relativePath, innerRequest);
}
} else {
innerRequest = request.relativePath;
}
request.__innerRequest_request = request.request;
request.__innerRequest_relativePath = request.relativePath;
return (request.__innerRequest = /** @type {string} */ (innerRequest));
};

View File

@@ -0,0 +1,3 @@
import * as React from 'react';
export declare const matchContext: React.Context<string | undefined>;
export declare const dummyMatchContext: React.Context<string | undefined>;

View File

@@ -0,0 +1 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.dequal={})}(this,(function(e){var t=Object.prototype.hasOwnProperty;e.dequal=function e(r,n){var o,i;if(r===n)return!0;if(r&&n&&(o=r.constructor)===n.constructor){if(o===Date)return r.getTime()===n.getTime();if(o===RegExp)return r.toString()===n.toString();if(o===Array){if((i=r.length)===n.length)for(;i--&&e(r[i],n[i]););return-1===i}if(!o||"object"==typeof r){for(o in i=0,r){if(t.call(r,o)&&++i&&!t.call(n,o))return!1;if(!(o in n)||!e(r[o],n[o]))return!1}return Object.keys(n).length===i}}return r!=r&&n!=n}}));

View File

@@ -0,0 +1 @@
{"version":3,"names":["_core","require","exports","getDynamicImportSource","node","source","arguments","t","isStringLiteral","isTemplateLiteral","template","expression","ast","buildDynamicImport","deferToThen","wrapWithPromise","builder","specifier","isCallExpression","quasis","length","specifierToString","identifier","templateLiteral","templateElement","raw"],"sources":["../src/dynamic-import.ts"],"sourcesContent":["// Heavily inspired by\n// https://github.com/airbnb/babel-plugin-dynamic-import-node/blob/master/src/utils.js\n\nimport { types as t, template } from \"@babel/core\";\n\nif (!process.env.BABEL_8_BREAKING && !USE_ESM && !IS_STANDALONE) {\n // eslint-disable-next-line no-restricted-globals\n exports.getDynamicImportSource = function getDynamicImportSource(\n node: t.CallExpression,\n ): t.StringLiteral | t.TemplateLiteral {\n const [source] = node.arguments;\n\n return t.isStringLiteral(source) || t.isTemplateLiteral(source)\n ? source\n : (template.expression.ast`\\`\\${${source}}\\`` as t.TemplateLiteral);\n };\n}\n\nexport function buildDynamicImport(\n node: t.CallExpression | t.ImportExpression,\n deferToThen: boolean,\n wrapWithPromise: boolean,\n builder: (specifier: t.Expression) => t.Expression,\n): t.Expression {\n const specifier = t.isCallExpression(node) ? node.arguments[0] : node.source;\n\n if (\n t.isStringLiteral(specifier) ||\n (t.isTemplateLiteral(specifier) && specifier.quasis.length === 0)\n ) {\n if (deferToThen) {\n return template.expression.ast`\n Promise.resolve().then(() => ${builder(specifier)})\n `;\n } else return builder(specifier);\n }\n\n const specifierToString = t.isTemplateLiteral(specifier)\n ? t.identifier(\"specifier\")\n : t.templateLiteral(\n [t.templateElement({ raw: \"\" }), t.templateElement({ raw: \"\" })],\n [t.identifier(\"specifier\")],\n );\n\n if (deferToThen) {\n return template.expression.ast`\n (specifier =>\n new Promise(r => r(${specifierToString}))\n .then(s => ${builder(t.identifier(\"s\"))})\n )(${specifier})\n `;\n } else if (wrapWithPromise) {\n return template.expression.ast`\n (specifier =>\n new Promise(r => r(${builder(specifierToString)}))\n )(${specifier})\n `;\n } else {\n return template.expression.ast`\n (specifier => ${builder(specifierToString)})(${specifier})\n `;\n }\n}\n"],"mappings":";;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAEiE;EAE/DC,OAAO,CAACC,sBAAsB,GAAG,SAASA,sBAAsBA,CAC9DC,IAAsB,EACe;IACrC,MAAM,CAACC,MAAM,CAAC,GAAGD,IAAI,CAACE,SAAS;IAE/B,OAAOC,WAAC,CAACC,eAAe,CAACH,MAAM,CAAC,IAAIE,WAAC,CAACE,iBAAiB,CAACJ,MAAM,CAAC,GAC3DA,MAAM,GACLK,cAAQ,CAACC,UAAU,CAACC,GAAG,QAAQP,MAAM,KAA2B;EACvE,CAAC;AACH;AAEO,SAASQ,kBAAkBA,CAChCT,IAA2C,EAC3CU,WAAoB,EACpBC,eAAwB,EACxBC,OAAkD,EACpC;EACd,MAAMC,SAAS,GAAGV,WAAC,CAACW,gBAAgB,CAACd,IAAI,CAAC,GAAGA,IAAI,CAACE,SAAS,CAAC,CAAC,CAAC,GAAGF,IAAI,CAACC,MAAM;EAE5E,IACEE,WAAC,CAACC,eAAe,CAACS,SAAS,CAAC,IAC3BV,WAAC,CAACE,iBAAiB,CAACQ,SAAS,CAAC,IAAIA,SAAS,CAACE,MAAM,CAACC,MAAM,KAAK,CAAE,EACjE;IACA,IAAIN,WAAW,EAAE;MACf,OAAOJ,cAAQ,CAACC,UAAU,CAACC,GAAG;AACpC,uCAAuCI,OAAO,CAACC,SAAS,CAAC;AACzD,OAAO;IACH,CAAC,MAAM,OAAOD,OAAO,CAACC,SAAS,CAAC;EAClC;EAEA,MAAMI,iBAAiB,GAAGd,WAAC,CAACE,iBAAiB,CAACQ,SAAS,CAAC,GACpDV,WAAC,CAACe,UAAU,CAAC,WAAW,CAAC,GACzBf,WAAC,CAACgB,eAAe,CACf,CAAChB,WAAC,CAACiB,eAAe,CAAC;IAAEC,GAAG,EAAE;EAAG,CAAC,CAAC,EAAElB,WAAC,CAACiB,eAAe,CAAC;IAAEC,GAAG,EAAE;EAAG,CAAC,CAAC,CAAC,EAChE,CAAClB,WAAC,CAACe,UAAU,CAAC,WAAW,CAAC,CAC5B,CAAC;EAEL,IAAIR,WAAW,EAAE;IACf,OAAOJ,cAAQ,CAACC,UAAU,CAACC,GAAG;AAClC;AACA,6BAA6BS,iBAAiB;AAC9C,uBAAuBL,OAAO,CAACT,WAAC,CAACe,UAAU,CAAC,GAAG,CAAC,CAAC;AACjD,UAAUL,SAAS;AACnB,KAAK;EACH,CAAC,MAAM,IAAIF,eAAe,EAAE;IAC1B,OAAOL,cAAQ,CAACC,UAAU,CAACC,GAAG;AAClC;AACA,6BAA6BI,OAAO,CAACK,iBAAiB,CAAC;AACvD,UAAUJ,SAAS;AACnB,KAAK;EACH,CAAC,MAAM;IACL,OAAOP,cAAQ,CAACC,UAAU,CAACC,GAAG;AAClC,sBAAsBI,OAAO,CAACK,iBAAiB,CAAC,KAAKJ,SAAS;AAC9D,KAAK;EACH;AACF","ignoreList":[]}

View File

@@ -0,0 +1,64 @@
/*
@license
Rollup.js v4.39.0
Wed, 02 Apr 2025 04:49:00 GMT - commit 5c001245779063abac3899aa9d25294ab003581b
https://github.com/rollup/rollup
Released under the MIT License.
*/
const getLogFilter = filters => {
if (filters.length === 0)
return () => true;
const normalizedFilters = filters.map(filter => filter.split('&').map(subFilter => {
const inverted = subFilter.startsWith('!');
if (inverted)
subFilter = subFilter.slice(1);
const [key, ...value] = subFilter.split(':');
return { inverted, key: key.split('.'), parts: value.join(':').split('*') };
}));
return (log) => {
nextIntersectedFilter: for (const intersectedFilters of normalizedFilters) {
for (const { inverted, key, parts } of intersectedFilters) {
const isFilterSatisfied = testFilter(log, key, parts);
if (inverted ? isFilterSatisfied : !isFilterSatisfied) {
continue nextIntersectedFilter;
}
}
return true;
}
return false;
};
};
const testFilter = (log, key, parts) => {
let rawValue = log;
for (let index = 0; index < key.length; index++) {
if (!rawValue) {
return false;
}
const part = key[index];
if (!(part in rawValue)) {
return false;
}
rawValue = rawValue[part];
}
let value = typeof rawValue === 'object' ? JSON.stringify(rawValue) : String(rawValue);
if (parts.length === 1) {
return value === parts[0];
}
if (!value.startsWith(parts[0])) {
return false;
}
const lastPartIndex = parts.length - 1;
for (let index = 1; index < lastPartIndex; index++) {
const part = parts[index];
const position = value.indexOf(part);
if (position === -1) {
return false;
}
value = value.slice(position + part.length);
}
return value.endsWith(parts[lastPartIndex]);
};
export { getLogFilter };

View File

@@ -0,0 +1,34 @@
# shebang-command [![Build Status](https://travis-ci.org/kevva/shebang-command.svg?branch=master)](https://travis-ci.org/kevva/shebang-command)
> Get the command from a shebang
## Install
```
$ npm install shebang-command
```
## Usage
```js
const shebangCommand = require('shebang-command');
shebangCommand('#!/usr/bin/env node');
//=> 'node'
shebangCommand('#!/bin/bash');
//=> 'bash'
```
## API
### shebangCommand(string)
#### string
Type: `string`
String containing a shebang.

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _classNameTDZError;
function _classNameTDZError(name) {
throw new ReferenceError('Class "' + name + '" cannot be referenced in computed property keys.');
}
//# sourceMappingURL=classNameTDZError.js.map

View File

@@ -0,0 +1,237 @@
import { jsxs, Fragment, jsx } from "react/jsx-runtime";
import * as React from "react";
import invariant from "tiny-invariant";
import warning from "tiny-warning";
import { isNotFound, rootRouteId, pick, isRedirect, createControlledPromise, getLocationChangeInfo } from "@tanstack/router-core";
import { CatchBoundary, ErrorComponent } from "./CatchBoundary.js";
import { useRouterState } from "./useRouterState.js";
import { useRouter } from "./useRouter.js";
import { CatchNotFound } from "./not-found.js";
import { matchContext } from "./matchContext.js";
import { SafeFragment } from "./SafeFragment.js";
import { renderRouteNotFound } from "./renderRouteNotFound.js";
import { ScrollRestoration } from "./scroll-restoration.js";
const Match = React.memo(function MatchImpl({
matchId
}) {
var _a, _b;
const router = useRouter();
const routeId = useRouterState({
select: (s) => {
var _a2;
return (_a2 = s.matches.find((d) => d.id === matchId)) == null ? void 0 : _a2.routeId;
}
});
invariant(
routeId,
`Could not find routeId for matchId "${matchId}". Please file an issue!`
);
const route = router.routesById[routeId];
const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent;
const pendingElement = PendingComponent ? /* @__PURE__ */ jsx(PendingComponent, {}) : null;
const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent;
const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch;
const routeNotFoundComponent = route.isRoot ? (
// If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component
route.options.notFoundComponent ?? ((_a = router.options.notFoundRoute) == null ? void 0 : _a.options.component)
) : route.options.notFoundComponent;
const ResolvedSuspenseBoundary = (
// If we're on the root route, allow forcefully wrapping in suspense
(!route.isRoot || route.options.wrapInSuspense) && (route.options.wrapInSuspense ?? PendingComponent ?? ((_b = route.options.errorComponent) == null ? void 0 : _b.preload)) ? React.Suspense : SafeFragment
);
const ResolvedCatchBoundary = routeErrorComponent ? CatchBoundary : SafeFragment;
const ResolvedNotFoundBoundary = routeNotFoundComponent ? CatchNotFound : SafeFragment;
const resetKey = useRouterState({
select: (s) => s.loadedAt
});
const parentRouteId = useRouterState({
select: (s) => {
var _a2;
const index = s.matches.findIndex((d) => d.id === matchId);
return (_a2 = s.matches[index - 1]) == null ? void 0 : _a2.routeId;
}
});
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(matchContext.Provider, { value: matchId, children: /* @__PURE__ */ jsx(ResolvedSuspenseBoundary, { fallback: pendingElement, children: /* @__PURE__ */ jsx(
ResolvedCatchBoundary,
{
getResetKey: () => resetKey,
errorComponent: routeErrorComponent || ErrorComponent,
onCatch: (error, errorInfo) => {
if (isNotFound(error)) throw error;
warning(false, `Error in route match: ${matchId}`);
routeOnCatch == null ? void 0 : routeOnCatch(error, errorInfo);
},
children: /* @__PURE__ */ jsx(
ResolvedNotFoundBoundary,
{
fallback: (error) => {
if (!routeNotFoundComponent || error.routeId && error.routeId !== routeId || !error.routeId && !route.isRoot)
throw error;
return React.createElement(routeNotFoundComponent, error);
},
children: /* @__PURE__ */ jsx(MatchInner, { matchId })
}
)
}
) }) }),
parentRouteId === rootRouteId && router.options.scrollRestoration ? /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(OnRendered, {}),
/* @__PURE__ */ jsx(ScrollRestoration, {})
] }) : null
] });
});
function OnRendered() {
var _a;
const router = useRouter();
const prevLocationRef = React.useRef(
void 0
);
return /* @__PURE__ */ jsx(
"script",
{
suppressHydrationWarning: true,
ref: (el) => {
var _a2;
if (el && (prevLocationRef.current === void 0 || prevLocationRef.current.href !== ((_a2 = router.state.resolvedLocation) == null ? void 0 : _a2.href))) {
router.emit({
type: "onRendered",
...getLocationChangeInfo(router.state)
});
prevLocationRef.current = router.state.resolvedLocation;
}
}
},
(_a = router.state.resolvedLocation) == null ? void 0 : _a.state.key
);
}
const MatchInner = React.memo(function MatchInnerImpl({
matchId
}) {
var _a, _b, _c;
const router = useRouter();
const { match, key, routeId } = useRouterState({
select: (s) => {
const matchIndex = s.matches.findIndex((d) => d.id === matchId);
const match2 = s.matches[matchIndex];
const routeId2 = match2.routeId;
const remountFn = router.routesById[routeId2].options.remountDeps ?? router.options.defaultRemountDeps;
const remountDeps = remountFn == null ? void 0 : remountFn({
routeId: routeId2,
loaderDeps: match2.loaderDeps,
params: match2._strictParams,
search: match2._strictSearch
});
const key2 = remountDeps ? JSON.stringify(remountDeps) : void 0;
return {
key: key2,
routeId: routeId2,
match: pick(match2, ["id", "status", "error"])
};
},
structuralSharing: true
});
const route = router.routesById[routeId];
const out = React.useMemo(() => {
const Comp = route.options.component ?? router.options.defaultComponent;
if (Comp) {
return /* @__PURE__ */ jsx(Comp, {}, key);
}
return /* @__PURE__ */ jsx(Outlet, {});
}, [key, route.options.component, router.options.defaultComponent]);
const RouteErrorComponent = (route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent;
if (match.status === "notFound") {
invariant(isNotFound(match.error), "Expected a notFound error");
return renderRouteNotFound(router, route, match.error);
}
if (match.status === "redirected") {
invariant(isRedirect(match.error), "Expected a redirect error");
throw (_a = router.getMatch(match.id)) == null ? void 0 : _a.loadPromise;
}
if (match.status === "error") {
if (router.isServer) {
return /* @__PURE__ */ jsx(
RouteErrorComponent,
{
error: match.error,
reset: void 0,
info: {
componentStack: ""
}
}
);
}
throw match.error;
}
if (match.status === "pending") {
const pendingMinMs = route.options.pendingMinMs ?? router.options.defaultPendingMinMs;
if (pendingMinMs && !((_b = router.getMatch(match.id)) == null ? void 0 : _b.minPendingPromise)) {
if (!router.isServer) {
const minPendingPromise = createControlledPromise();
Promise.resolve().then(() => {
router.updateMatch(match.id, (prev) => ({
...prev,
minPendingPromise
}));
});
setTimeout(() => {
minPendingPromise.resolve();
router.updateMatch(match.id, (prev) => ({
...prev,
minPendingPromise: void 0
}));
}, pendingMinMs);
}
}
throw (_c = router.getMatch(match.id)) == null ? void 0 : _c.loadPromise;
}
return out;
});
const Outlet = React.memo(function OutletImpl() {
const router = useRouter();
const matchId = React.useContext(matchContext);
const routeId = useRouterState({
select: (s) => {
var _a;
return (_a = s.matches.find((d) => d.id === matchId)) == null ? void 0 : _a.routeId;
}
});
const route = router.routesById[routeId];
const parentGlobalNotFound = useRouterState({
select: (s) => {
const matches = s.matches;
const parentMatch = matches.find((d) => d.id === matchId);
invariant(
parentMatch,
`Could not find parent match for matchId "${matchId}"`
);
return parentMatch.globalNotFound;
}
});
const childMatchId = useRouterState({
select: (s) => {
var _a;
const matches = s.matches;
const index = matches.findIndex((d) => d.id === matchId);
return (_a = matches[index + 1]) == null ? void 0 : _a.id;
}
});
if (parentGlobalNotFound) {
return renderRouteNotFound(router, route, void 0);
}
if (!childMatchId) {
return null;
}
const nextMatch = /* @__PURE__ */ jsx(Match, { matchId: childMatchId });
const pendingElement = router.options.defaultPendingComponent ? /* @__PURE__ */ jsx(router.options.defaultPendingComponent, {}) : null;
if (matchId === rootRouteId) {
return /* @__PURE__ */ jsx(React.Suspense, { fallback: pendingElement, children: nextMatch });
}
return nextMatch;
});
export {
Match,
MatchInner,
Outlet
};
//# sourceMappingURL=Match.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_index","require","BLOCK_SCOPED_SYMBOL","Symbol","for","isLet","node","isVariableDeclaration","kind"],"sources":["../../src/validators/isLet.ts"],"sourcesContent":["import { isVariableDeclaration } from \"./generated/index.ts\";\nimport type * as t from \"../index.ts\";\n\nif (!process.env.BABEL_8_BREAKING) {\n // eslint-disable-next-line no-var\n var BLOCK_SCOPED_SYMBOL = Symbol.for(\"var used to be block scoped\");\n}\n\n/**\n * Check if the input `node` is a `let` variable declaration.\n */\nexport default function isLet(node: t.Node): boolean {\n if (process.env.BABEL_8_BREAKING) {\n return isVariableDeclaration(node) && node.kind !== \"var\";\n } else {\n return (\n isVariableDeclaration(node) &&\n (node.kind !== \"var\" ||\n // @ts-expect-error Fixme: document private properties\n node[BLOCK_SCOPED_SYMBOL])\n );\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAGmC;EAEjC,IAAIC,mBAAmB,GAAGC,MAAM,CAACC,GAAG,CAAC,6BAA6B,CAAC;AACrE;AAKe,SAASC,KAAKA,CAACC,IAAY,EAAW;EAG5C;IACL,OACE,IAAAC,4BAAqB,EAACD,IAAI,CAAC,KAC1BA,IAAI,CAACE,IAAI,KAAK,KAAK,IAElBF,IAAI,CAACJ,mBAAmB,CAAC,CAAC;EAEhC;AACF","ignoreList":[]}

View File

@@ -0,0 +1 @@
{"version":3,"file":"not-found.cjs","sources":["../../src/not-found.tsx"],"sourcesContent":["import * as React from 'react'\nimport { isNotFound } from '@tanstack/router-core'\nimport { CatchBoundary } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport type { ErrorInfo } from 'react'\nimport type { NotFoundError } from '@tanstack/router-core'\n\nexport function CatchNotFound(props: {\n fallback?: (error: NotFoundError) => React.ReactElement\n onCatch?: (error: Error, errorInfo: ErrorInfo) => void\n children: React.ReactNode\n}) {\n // TODO: Some way for the user to programmatically reset the not-found boundary?\n const resetKey = useRouterState({\n select: (s) => `not-found-${s.location.pathname}-${s.status}`,\n })\n\n return (\n <CatchBoundary\n getResetKey={() => resetKey}\n onCatch={(error, errorInfo) => {\n if (isNotFound(error)) {\n props.onCatch?.(error, errorInfo)\n } else {\n throw error\n }\n }}\n errorComponent={({ error }: { error: Error }) => {\n if (isNotFound(error)) {\n return props.fallback?.(error)\n } else {\n throw error\n }\n }}\n >\n {props.children}\n </CatchBoundary>\n )\n}\n\nexport function DefaultGlobalNotFound() {\n return <p>Not Found</p>\n}\n"],"names":["useRouterState","jsx","CatchBoundary","isNotFound"],"mappings":";;;;;;AAOO,SAAS,cAAc,OAI3B;AAED,QAAM,WAAWA,eAAAA,eAAe;AAAA,IAC9B,QAAQ,CAAC,MAAM,aAAa,EAAE,SAAS,QAAQ,IAAI,EAAE,MAAM;AAAA,EAAA,CAC5D;AAGC,SAAAC,2BAAA;AAAA,IAACC,cAAA;AAAA,IAAA;AAAA,MACC,aAAa,MAAM;AAAA,MACnB,SAAS,CAAC,OAAO,cAAc;;AACzB,YAAAC,WAAAA,WAAW,KAAK,GAAG;AACf,sBAAA,YAAA,+BAAU,OAAO;AAAA,QAAS,OAC3B;AACC,gBAAA;AAAA,QAAA;AAAA,MAEV;AAAA,MACA,gBAAgB,CAAC,EAAE,YAA8B;;AAC3C,YAAAA,WAAAA,WAAW,KAAK,GAAG;AACd,kBAAA,WAAM,aAAN,+BAAiB;AAAA,QAAK,OACxB;AACC,gBAAA;AAAA,QAAA;AAAA,MAEV;AAAA,MAEC,UAAM,MAAA;AAAA,IAAA;AAAA,EACT;AAEJ;AAEO,SAAS,wBAAwB;AAC/B,SAAAF,2BAAA,IAAC,OAAE,UAAS,YAAA,CAAA;AACrB;;;"}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D mC","161":"E F A B"},B:{"2":"0 9 Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I","161":"C L M G N O P"},C:{"2":"0 1 2 3 4 5 6 7 8 9 nC LC J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC qC rC"},D:{"2":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC"},E:{"2":"J PB K D E F A B C L M G sC SC tC uC vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C"},F:{"2":"0 1 2 3 4 5 6 7 8 F B C G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 4C 5C 6C 7C FC kC 8C GC"},G:{"2":"E SC 9C lC AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC"},H:{"2":"WD"},I:{"2":"LC J I XD YD ZD aD lC bD cD"},J:{"2":"D A"},K:{"2":"A B C H FC kC GC"},L:{"2":"I"},M:{"2":"EC"},N:{"16":"A B"},O:{"2":"HC"},P:{"2":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"2":"oD"},R:{"2":"pD"},S:{"2":"qD rD"}},B:5,C:"CSS Text 4 text-spacing",D:false};

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B mC"},B:{"1":"LB MB NB OB I","2":"C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w","132":"0 9 x y z AB BB CB DB EB FB GB HB IB JB KB"},C:{"1":"CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC","2":"0 1 2 3 4 5 6 7 8 9 nC LC J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB qC rC"},D:{"1":"LB MB NB OB I PC EC QC RC","2":"1 2 3 4 5 6 7 8 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w","132":"0 9 x y z AB BB CB DB EB FB GB HB IB JB KB"},E:{"1":"fC 2C KC gC hC iC jC 3C","2":"J PB K D E F A B C L M G sC SC tC uC vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC"},F:{"1":"0 z","2":"1 2 3 4 5 6 7 8 F B C G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h 4C 5C 6C 7C FC kC 8C GC","132":"i j k l m n o p q r s t u v w x y"},G:{"1":"fC VD KC gC hC iC jC","2":"E SC 9C lC AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC"},H:{"2":"WD"},I:{"1":"I","2":"LC J XD YD ZD aD lC bD cD"},J:{"2":"D A"},K:{"2":"A B C FC kC GC","132":"H"},L:{"1":"I"},M:{"1":"EC"},N:{"2":"A B"},O:{"2":"HC"},P:{"2":"1 2 3 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD","132":"4 5 6 7 8"},Q:{"2":"oD"},R:{"2":"pD"},S:{"2":"qD rD"}},B:5,C:"CSS text-wrap: balance",D:true};

View File

@@ -0,0 +1,55 @@
import gensync, { type Handler } from "gensync";
import loadConfig from "./config/index.ts";
import type { InputOptions, ResolvedConfig } from "./config/index.ts";
import { run } from "./transformation/index.ts";
import type { FileResult, FileResultCallback } from "./transformation/index.ts";
import * as fs from "./gensync-utils/fs.ts";
type transformFileBrowserType = typeof import("./transform-file-browser");
type transformFileType = typeof import("./transform-file");
// Kind of gross, but essentially asserting that the exports of this module are the same as the
// exports of transform-file-browser, since this file may be replaced at bundle time with
// transform-file-browser.
({}) as any as transformFileBrowserType as transformFileType;
const transformFileRunner = gensync(function* (
filename: string,
opts?: InputOptions,
): Handler<FileResult | null> {
const options = { ...opts, filename };
const config: ResolvedConfig | null = yield* loadConfig(options);
if (config === null) return null;
const code = yield* fs.readFile(filename, "utf8");
return yield* run(config, code);
});
// @ts-expect-error TS doesn't detect that this signature is compatible
export function transformFile(
filename: string,
callback: FileResultCallback,
): void;
export function transformFile(
filename: string,
opts: InputOptions | undefined | null,
callback: FileResultCallback,
): void;
export function transformFile(
...args: Parameters<typeof transformFileRunner.errback>
) {
transformFileRunner.errback(...args);
}
export function transformFileSync(
...args: Parameters<typeof transformFileRunner.sync>
) {
return transformFileRunner.sync(...args);
}
export function transformFileAsync(
...args: Parameters<typeof transformFileRunner.async>
) {
return transformFileRunner.async(...args);
}